blob: 9767d32c6d7be4aa3a932c6f28e2351dd33ec3d9 [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,
587 cert_chain: ZVec,
588}
589
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700590/// This type represents a Keystore 2.0 key entry.
591/// An entry has a unique `id` by which it can be found in the database.
592/// It has a security level field, key parameters, and three optional fields
593/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800594#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700595pub struct KeyEntry {
596 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800597 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700598 cert: Option<Vec<u8>>,
599 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800600 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700601 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800602 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800603 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700604}
605
606impl KeyEntry {
607 /// Returns the unique id of the Key entry.
608 pub fn id(&self) -> i64 {
609 self.id
610 }
611 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800612 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
613 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700614 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800615 /// Extracts the Optional KeyMint blob including its metadata.
616 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
617 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700618 }
619 /// Exposes the optional public certificate.
620 pub fn cert(&self) -> &Option<Vec<u8>> {
621 &self.cert
622 }
623 /// Extracts the optional public certificate.
624 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
625 self.cert.take()
626 }
627 /// Exposes the optional public certificate chain.
628 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
629 &self.cert_chain
630 }
631 /// Extracts the optional public certificate_chain.
632 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
633 self.cert_chain.take()
634 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800635 /// Returns the uuid of the owning KeyMint instance.
636 pub fn km_uuid(&self) -> &Uuid {
637 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700638 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700639 /// Exposes the key parameters of this key entry.
640 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
641 &self.parameters
642 }
643 /// Consumes this key entry and extracts the keyparameters from it.
644 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
645 self.parameters
646 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800647 /// Exposes the key metadata of this key entry.
648 pub fn metadata(&self) -> &KeyMetaData {
649 &self.metadata
650 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800651 /// This returns true if the entry is a pure certificate entry with no
652 /// private key component.
653 pub fn pure_cert(&self) -> bool {
654 self.pure_cert
655 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000656 /// Consumes this key entry and extracts the keyparameters and metadata from it.
657 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
658 (self.parameters, self.metadata)
659 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700660}
661
662/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800663#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700664pub struct SubComponentType(u32);
665impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800666 /// Persistent identifier for a key blob.
667 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700668 /// Persistent identifier for a certificate blob.
669 pub const CERT: SubComponentType = Self(1);
670 /// Persistent identifier for a certificate chain blob.
671 pub const CERT_CHAIN: SubComponentType = Self(2);
672}
673
674impl ToSql for SubComponentType {
675 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
676 self.0.to_sql()
677 }
678}
679
680impl FromSql for SubComponentType {
681 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
682 Ok(Self(u32::column_result(value)?))
683 }
684}
685
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800686/// This trait is private to the database module. It is used to convey whether or not the garbage
687/// collector shall be invoked after a database access. All closures passed to
688/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
689/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
690/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
691/// `.need_gc()`.
692trait DoGc<T> {
693 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
694
695 fn no_gc(self) -> Result<(bool, T)>;
696
697 fn need_gc(self) -> Result<(bool, T)>;
698}
699
700impl<T> DoGc<T> for Result<T> {
701 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
702 self.map(|r| (need_gc, r))
703 }
704
705 fn no_gc(self) -> Result<(bool, T)> {
706 self.do_gc(false)
707 }
708
709 fn need_gc(self) -> Result<(bool, T)> {
710 self.do_gc(true)
711 }
712}
713
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700714/// KeystoreDB wraps a connection to an SQLite database and tracks its
715/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700716pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700717 conn: Connection,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800718 gc: Option<Gc>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700719}
720
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000721/// Database representation of the monotonic time retrieved from the system call clock_gettime with
722/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds.
723#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
724pub struct MonotonicRawTime(i64);
725
726impl MonotonicRawTime {
727 /// Constructs a new MonotonicRawTime
728 pub fn now() -> Self {
729 Self(get_current_time_in_seconds())
730 }
731
732 /// Returns the integer value of MonotonicRawTime as i64
733 pub fn seconds(&self) -> i64 {
734 self.0
735 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800736
737 /// Like i64::checked_sub.
738 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
739 self.0.checked_sub(other.0).map(Self)
740 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000741}
742
743impl ToSql for MonotonicRawTime {
744 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
745 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
746 }
747}
748
749impl FromSql for MonotonicRawTime {
750 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
751 Ok(Self(i64::column_result(value)?))
752 }
753}
754
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000755/// This struct encapsulates the information to be stored in the database about the auth tokens
756/// received by keystore.
757pub struct AuthTokenEntry {
758 auth_token: HardwareAuthToken,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000759 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000760}
761
762impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000763 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000764 AuthTokenEntry { auth_token, time_received }
765 }
766
767 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800768 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000769 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800770 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
771 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000772 })
773 }
774
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000775 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800776 pub fn auth_token(&self) -> &HardwareAuthToken {
777 &self.auth_token
778 }
779
780 /// Returns the auth token wrapped by the AuthTokenEntry
781 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000782 self.auth_token
783 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800784
785 /// Returns the time that this auth token was received.
786 pub fn time_received(&self) -> MonotonicRawTime {
787 self.time_received
788 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000789}
790
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800791/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
792/// This object does not allow access to the database connection. But it keeps a database
793/// connection alive in order to keep the in memory per boot database alive.
794pub struct PerBootDbKeepAlive(Connection);
795
Joel Galenson26f4d012020-07-17 14:57:21 -0700796impl KeystoreDB {
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800797 const PERBOOT_DB_FILE_NAME: &'static str = &"file:perboot.sqlite?mode=memory&cache=shared";
798
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000799 /// The alias of the user super key.
800 pub const USER_SUPER_KEY_ALIAS: &'static str = &"USER_SUPER_KEY";
801
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800802 /// This creates a PerBootDbKeepAlive object to keep the per boot database alive.
803 pub fn keep_perboot_db_alive() -> Result<PerBootDbKeepAlive> {
804 let conn = Connection::open_in_memory()
805 .context("In keep_perboot_db_alive: Failed to initialize SQLite connection.")?;
806
807 conn.execute("ATTACH DATABASE ? as perboot;", params![Self::PERBOOT_DB_FILE_NAME])
808 .context("In keep_perboot_db_alive: Failed to attach database perboot.")?;
809 Ok(PerBootDbKeepAlive(conn))
810 }
811
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700812 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800813 /// files persistent.sqlite and perboot.sqlite in the given directory.
814 /// It also attempts to initialize all of the tables.
815 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700816 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800817 pub fn new(db_root: &Path, gc: Option<Gc>) -> Result<Self> {
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800818 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800819 let mut persistent_path = db_root.to_path_buf();
820 persistent_path.push("persistent.sqlite");
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700821
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800822 // Now convert them to strings prefixed with "file:"
823 let mut persistent_path_str = "file:".to_owned();
824 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800825
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800826 let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800827
Janis Danisevskis66784c42021-01-27 08:40:25 -0800828 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
829 conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?;
830
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800831 let mut db = Self { conn, gc };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800832 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800833 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800834 })?;
835 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700836 }
837
Janis Danisevskis66784c42021-01-27 08:40:25 -0800838 fn init_tables(tx: &Transaction) -> Result<()> {
839 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700840 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700841 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800842 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700843 domain INTEGER,
844 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800845 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800846 state INTEGER,
847 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700848 NO_PARAMS,
849 )
850 .context("Failed to initialize \"keyentry\" table.")?;
851
Janis Danisevskis66784c42021-01-27 08:40:25 -0800852 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800853 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
854 ON keyentry(id);",
855 NO_PARAMS,
856 )
857 .context("Failed to create index keyentry_id_index.")?;
858
859 tx.execute(
860 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
861 ON keyentry(domain, namespace, alias);",
862 NO_PARAMS,
863 )
864 .context("Failed to create index keyentry_domain_namespace_index.")?;
865
866 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700867 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
868 id INTEGER PRIMARY KEY,
869 subcomponent_type INTEGER,
870 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800871 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700872 NO_PARAMS,
873 )
874 .context("Failed to initialize \"blobentry\" table.")?;
875
Janis Danisevskis66784c42021-01-27 08:40:25 -0800876 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800877 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
878 ON blobentry(keyentryid);",
879 NO_PARAMS,
880 )
881 .context("Failed to create index blobentry_keyentryid_index.")?;
882
883 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800884 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
885 id INTEGER PRIMARY KEY,
886 blobentryid INTEGER,
887 tag INTEGER,
888 data ANY,
889 UNIQUE (blobentryid, tag));",
890 NO_PARAMS,
891 )
892 .context("Failed to initialize \"blobmetadata\" table.")?;
893
894 tx.execute(
895 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
896 ON blobmetadata(blobentryid);",
897 NO_PARAMS,
898 )
899 .context("Failed to create index blobmetadata_blobentryid_index.")?;
900
901 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700902 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000903 keyentryid INTEGER,
904 tag INTEGER,
905 data ANY,
906 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700907 NO_PARAMS,
908 )
909 .context("Failed to initialize \"keyparameter\" table.")?;
910
Janis Danisevskis66784c42021-01-27 08:40:25 -0800911 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800912 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
913 ON keyparameter(keyentryid);",
914 NO_PARAMS,
915 )
916 .context("Failed to create index keyparameter_keyentryid_index.")?;
917
918 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800919 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
920 keyentryid INTEGER,
921 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000922 data ANY,
923 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800924 NO_PARAMS,
925 )
926 .context("Failed to initialize \"keymetadata\" table.")?;
927
Janis Danisevskis66784c42021-01-27 08:40:25 -0800928 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800929 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
930 ON keymetadata(keyentryid);",
931 NO_PARAMS,
932 )
933 .context("Failed to create index keymetadata_keyentryid_index.")?;
934
935 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800936 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700937 id INTEGER UNIQUE,
938 grantee INTEGER,
939 keyentryid INTEGER,
940 access_vector INTEGER);",
941 NO_PARAMS,
942 )
943 .context("Failed to initialize \"grant\" table.")?;
944
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000945 //TODO: only drop the following two perboot tables if this is the first start up
946 //during the boot (b/175716626).
Janis Danisevskis66784c42021-01-27 08:40:25 -0800947 // tx.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000948 // .context("Failed to drop perboot.authtoken table")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -0800949 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000950 "CREATE TABLE IF NOT EXISTS perboot.authtoken (
951 id INTEGER PRIMARY KEY,
952 challenge INTEGER,
953 user_id INTEGER,
954 auth_id INTEGER,
955 authenticator_type INTEGER,
956 timestamp INTEGER,
957 mac BLOB,
958 time_received INTEGER,
959 UNIQUE(user_id, auth_id, authenticator_type));",
960 NO_PARAMS,
961 )
962 .context("Failed to initialize \"authtoken\" table.")?;
963
Janis Danisevskis66784c42021-01-27 08:40:25 -0800964 // tx.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000965 // .context("Failed to drop perboot.metadata table")?;
966 // metadata table stores certain miscellaneous information required for keystore functioning
967 // during a boot cycle, as key-value pairs.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800968 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000969 "CREATE TABLE IF NOT EXISTS perboot.metadata (
970 key TEXT,
971 value BLOB,
972 UNIQUE(key));",
973 NO_PARAMS,
974 )
975 .context("Failed to initialize \"metadata\" table.")?;
Joel Galenson0891bc12020-07-20 10:37:03 -0700976 Ok(())
977 }
978
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700979 fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> {
980 let conn =
981 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
982
Janis Danisevskis66784c42021-01-27 08:40:25 -0800983 loop {
984 if let Err(e) = conn
985 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
986 .context("Failed to attach database persistent.")
987 {
988 if Self::is_locked_error(&e) {
989 std::thread::sleep(std::time::Duration::from_micros(500));
990 continue;
991 } else {
992 return Err(e);
993 }
994 }
995 break;
996 }
997 loop {
998 if let Err(e) = conn
999 .execute("ATTACH DATABASE ? as perboot;", params![perboot_file])
1000 .context("Failed to attach database perboot.")
1001 {
1002 if Self::is_locked_error(&e) {
1003 std::thread::sleep(std::time::Duration::from_micros(500));
1004 continue;
1005 } else {
1006 return Err(e);
1007 }
1008 }
1009 break;
1010 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001011
1012 Ok(conn)
1013 }
1014
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001015 /// This function is intended to be used by the garbage collector.
1016 /// It deletes the blob given by `blob_id_to_delete`. It then tries to find a superseded
1017 /// key blob that might need special handling by the garbage collector.
1018 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1019 /// need special handling and returns None.
1020 pub fn handle_next_superseded_blob(
1021 &mut self,
1022 blob_id_to_delete: Option<i64>,
1023 ) -> Result<Option<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001024 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001025 // Delete the given blob if one was given.
1026 if let Some(blob_id_to_delete) = blob_id_to_delete {
1027 tx.execute(
1028 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
1029 params![blob_id_to_delete],
1030 )
1031 .context("Trying to delete blob metadata.")?;
1032 tx.execute(
1033 "DELETE FROM persistent.blobentry WHERE id = ?;",
1034 params![blob_id_to_delete],
1035 )
1036 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001037 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001038
1039 // Find another superseded keyblob load its metadata and return it.
1040 if let Some((blob_id, blob)) = tx
1041 .query_row(
1042 "SELECT id, blob FROM persistent.blobentry
1043 WHERE subcomponent_type = ?
1044 AND (
1045 id NOT IN (
1046 SELECT MAX(id) FROM persistent.blobentry
1047 WHERE subcomponent_type = ?
1048 GROUP BY keyentryid, subcomponent_type
1049 )
1050 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1051 );",
1052 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1053 |row| Ok((row.get(0)?, row.get(1)?)),
1054 )
1055 .optional()
1056 .context("Trying to query superseded blob.")?
1057 {
1058 let blob_metadata = BlobMetaData::load_from_db(blob_id, tx)
1059 .context("Trying to load blob metadata.")?;
1060 return Ok(Some((blob_id, blob, blob_metadata))).no_gc();
1061 }
1062
1063 // We did not find any superseded key blob, so let's remove other superseded blob in
1064 // one transaction.
1065 tx.execute(
1066 "DELETE FROM persistent.blobentry
1067 WHERE NOT subcomponent_type = ?
1068 AND (
1069 id NOT IN (
1070 SELECT MAX(id) FROM persistent.blobentry
1071 WHERE NOT subcomponent_type = ?
1072 GROUP BY keyentryid, subcomponent_type
1073 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1074 );",
1075 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1076 )
1077 .context("Trying to purge superseded blobs.")?;
1078
1079 Ok(None).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001080 })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001081 .context("In handle_next_superseded_blob.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001082 }
1083
1084 /// This maintenance function should be called only once before the database is used for the
1085 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1086 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1087 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1088 /// Keystore crashed at some point during key generation. Callers may want to log such
1089 /// occurrences.
1090 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1091 /// it to `KeyLifeCycle::Live` may have grants.
1092 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001093 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1094 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001095 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1096 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1097 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001098 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001099 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001100 })
1101 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001102 }
1103
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001104 /// Checks if a key exists with given key type and key descriptor properties.
1105 pub fn key_exists(
1106 &mut self,
1107 domain: Domain,
1108 nspace: i64,
1109 alias: &str,
1110 key_type: KeyType,
1111 ) -> Result<bool> {
1112 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1113 let key_descriptor =
1114 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1115 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1116 match result {
1117 Ok(_) => Ok(true),
1118 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1119 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1120 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1121 },
1122 }
1123 .no_gc()
1124 })
1125 .context("In key_exists.")
1126 }
1127
Hasini Gunasingheda895552021-01-27 19:34:37 +00001128 /// Stores a super key in the database.
1129 pub fn store_super_key(
1130 &mut self,
1131 user_id: i64,
1132 blob_info: &(&[u8], &BlobMetaData),
1133 ) -> Result<KeyEntry> {
1134 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1135 let key_id = Self::insert_with_retry(|id| {
1136 tx.execute(
1137 "INSERT into persistent.keyentry
1138 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001139 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001140 params![
1141 id,
1142 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001143 Domain::APP.0,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001144 user_id,
1145 Self::USER_SUPER_KEY_ALIAS,
1146 KeyLifeCycle::Live,
1147 &KEYSTORE_UUID,
1148 ],
1149 )
1150 })
1151 .context("Failed to insert into keyentry table.")?;
1152
1153 let (blob, blob_metadata) = *blob_info;
1154 Self::set_blob_internal(
1155 &tx,
1156 key_id,
1157 SubComponentType::KEY_BLOB,
1158 Some(blob),
1159 Some(blob_metadata),
1160 )
1161 .context("Failed to store key blob.")?;
1162
1163 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1164 .context("Trying to load key components.")
1165 .no_gc()
1166 })
1167 .context("In store_super_key.")
1168 }
1169
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001170 /// Loads super key of a given user, if exists
1171 pub fn load_super_key(&mut self, user_id: u32) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
1172 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1173 let key_descriptor = KeyDescriptor {
1174 domain: Domain::APP,
1175 nspace: user_id as u64 as i64,
1176 alias: Some(String::from("USER_SUPER_KEY")),
1177 blob: None,
1178 };
1179 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1180 match id {
1181 Ok(id) => {
1182 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1183 .context("In load_super_key. Failed to load key entry.")?;
1184 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1185 }
1186 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1187 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1188 _ => Err(error).context("In load_super_key."),
1189 },
1190 }
1191 .no_gc()
1192 })
1193 .context("In load_super_key.")
1194 }
1195
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001196 /// Atomically loads a key entry and associated metadata or creates it using the
1197 /// callback create_new_key callback. The callback is called during a database
1198 /// transaction. This means that implementers should be mindful about using
1199 /// blocking operations such as IPC or grabbing mutexes.
1200 pub fn get_or_create_key_with<F>(
1201 &mut self,
1202 domain: Domain,
1203 namespace: i64,
1204 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001205 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001206 create_new_key: F,
1207 ) -> Result<(KeyIdGuard, KeyEntry)>
1208 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001209 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001210 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001211 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1212 let id = {
1213 let mut stmt = tx
1214 .prepare(
1215 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001216 WHERE
1217 key_type = ?
1218 AND domain = ?
1219 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001220 AND alias = ?
1221 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001222 )
1223 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1224 let mut rows = stmt
1225 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1226 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001227
Janis Danisevskis66784c42021-01-27 08:40:25 -08001228 db_utils::with_rows_extract_one(&mut rows, |row| {
1229 Ok(match row {
1230 Some(r) => r.get(0).context("Failed to unpack id.")?,
1231 None => None,
1232 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001233 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001234 .context("In get_or_create_key_with.")?
1235 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001236
Janis Danisevskis66784c42021-01-27 08:40:25 -08001237 let (id, entry) = match id {
1238 Some(id) => (
1239 id,
1240 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1241 .context("In get_or_create_key_with.")?,
1242 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001243
Janis Danisevskis66784c42021-01-27 08:40:25 -08001244 None => {
1245 let id = Self::insert_with_retry(|id| {
1246 tx.execute(
1247 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001248 (id, key_type, domain, namespace, alias, state, km_uuid)
1249 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001250 params![
1251 id,
1252 KeyType::Super,
1253 domain.0,
1254 namespace,
1255 alias,
1256 KeyLifeCycle::Live,
1257 km_uuid,
1258 ],
1259 )
1260 })
1261 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001262
Janis Danisevskis66784c42021-01-27 08:40:25 -08001263 let (blob, metadata) =
1264 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001265 Self::set_blob_internal(
1266 &tx,
1267 id,
1268 SubComponentType::KEY_BLOB,
1269 Some(&blob),
1270 Some(&metadata),
1271 )
1272 .context("In get_of_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001273 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001274 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001275 KeyEntry {
1276 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001277 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001278 pure_cert: false,
1279 ..Default::default()
1280 },
1281 )
1282 }
1283 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001284 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001285 })
1286 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001287 }
1288
Janis Danisevskis66784c42021-01-27 08:40:25 -08001289 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1290 /// waiting for the database file to become available. This makes it
1291 /// impossible to successfully recover from a locked database when the
1292 /// transaction holding the device busy is in the same process on a
1293 /// different connection. As a result the busy handler has to time out and
1294 /// fail in order to make progress.
1295 ///
1296 /// Instead, we set the busy handler to None (return immediately). And catch
1297 /// Busy and Locked errors (the latter occur on in memory databases with
1298 /// shared cache, e.g., the per-boot database.) and restart the transaction
1299 /// after a grace period of half a millisecond.
1300 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001301 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001302 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1303 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001304 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1305 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001306 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001307 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001308 loop {
1309 match self
1310 .conn
1311 .transaction_with_behavior(behavior)
1312 .context("In with_transaction.")
1313 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1314 .and_then(|(result, tx)| {
1315 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1316 Ok(result)
1317 }) {
1318 Ok(result) => break Ok(result),
1319 Err(e) => {
1320 if Self::is_locked_error(&e) {
1321 std::thread::sleep(std::time::Duration::from_micros(500));
1322 continue;
1323 } else {
1324 return Err(e).context("In with_transaction.");
1325 }
1326 }
1327 }
1328 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001329 .map(|(need_gc, result)| {
1330 if need_gc {
1331 if let Some(ref gc) = self.gc {
1332 gc.notify_gc();
1333 }
1334 }
1335 result
1336 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001337 }
1338
1339 fn is_locked_error(e: &anyhow::Error) -> bool {
1340 matches!(e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1341 Some(rusqlite::ffi::Error {
1342 code: rusqlite::ErrorCode::DatabaseBusy,
1343 ..
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001344 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001345 | Some(rusqlite::ffi::Error {
1346 code: rusqlite::ErrorCode::DatabaseLocked,
1347 ..
1348 }))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001349 }
1350
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001351 /// Creates a new key entry and allocates a new randomized id for the new key.
1352 /// The key id gets associated with a domain and namespace but not with an alias.
1353 /// To complete key generation `rebind_alias` should be called after all of the
1354 /// key artifacts, i.e., blobs and parameters have been associated with the new
1355 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1356 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001357 pub fn create_key_entry(
1358 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001359 domain: &Domain,
1360 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001361 km_uuid: &Uuid,
1362 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001363 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001364 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001365 })
1366 .context("In create_key_entry.")
1367 }
1368
1369 fn create_key_entry_internal(
1370 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001371 domain: &Domain,
1372 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001373 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001374 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001375 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001376 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001377 _ => {
1378 return Err(KsError::sys())
1379 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1380 }
1381 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001382 Ok(KEY_ID_LOCK.get(
1383 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001384 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001385 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001386 (id, key_type, domain, namespace, alias, state, km_uuid)
1387 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001388 params![
1389 id,
1390 KeyType::Client,
1391 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001392 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001393 KeyLifeCycle::Existing,
1394 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001395 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001396 )
1397 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001398 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001399 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001400 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001401
Max Bires2b2e6562020-09-22 11:22:36 -07001402 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1403 /// The key id gets associated with a domain and namespace later but not with an alias. The
1404 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1405 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1406 /// a key.
1407 pub fn create_attestation_key_entry(
1408 &mut self,
1409 maced_public_key: &[u8],
1410 raw_public_key: &[u8],
1411 private_key: &[u8],
1412 km_uuid: &Uuid,
1413 ) -> Result<()> {
1414 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1415 let key_id = KEY_ID_LOCK.get(
1416 Self::insert_with_retry(|id| {
1417 tx.execute(
1418 "INSERT into persistent.keyentry
1419 (id, key_type, domain, namespace, alias, state, km_uuid)
1420 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1421 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1422 )
1423 })
1424 .context("In create_key_entry")?,
1425 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001426 Self::set_blob_internal(
1427 &tx,
1428 key_id.0,
1429 SubComponentType::KEY_BLOB,
1430 Some(private_key),
1431 None,
1432 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001433 let mut metadata = KeyMetaData::new();
1434 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1435 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1436 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001437 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001438 })
1439 .context("In create_attestation_key_entry")
1440 }
1441
Janis Danisevskis377d1002021-01-27 19:07:48 -08001442 /// Set a new blob and associates it with the given key id. Each blob
1443 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001444 /// Each key can have one of each sub component type associated. If more
1445 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001446 /// will get garbage collected.
1447 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1448 /// removed by setting blob to None.
1449 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001450 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001451 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001452 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001453 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001454 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001455 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001456 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001457 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001458 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001459 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001460 }
1461
Janis Danisevskis377d1002021-01-27 19:07:48 -08001462 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001463 tx: &Transaction,
1464 key_id: i64,
1465 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001466 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001467 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001468 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001469 match (blob, sc_type) {
1470 (Some(blob), _) => {
1471 tx.execute(
1472 "INSERT INTO persistent.blobentry
1473 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1474 params![sc_type, key_id, blob],
1475 )
1476 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001477 if let Some(blob_metadata) = blob_metadata {
1478 let blob_id = tx
1479 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1480 row.get(0)
1481 })
1482 .context("In set_blob_internal: Failed to get new blob id.")?;
1483 blob_metadata
1484 .store_in_db(blob_id, tx)
1485 .context("In set_blob_internal: Trying to store blob metadata.")?;
1486 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001487 }
1488 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1489 tx.execute(
1490 "DELETE FROM persistent.blobentry
1491 WHERE subcomponent_type = ? AND keyentryid = ?;",
1492 params![sc_type, key_id],
1493 )
1494 .context("In set_blob_internal: Failed to delete blob.")?;
1495 }
1496 (None, _) => {
1497 return Err(KsError::sys())
1498 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1499 }
1500 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001501 Ok(())
1502 }
1503
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001504 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1505 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001506 #[cfg(test)]
1507 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001508 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001509 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001510 })
1511 .context("In insert_keyparameter.")
1512 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001513
Janis Danisevskis66784c42021-01-27 08:40:25 -08001514 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001515 tx: &Transaction,
1516 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001517 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001518 ) -> Result<()> {
1519 let mut stmt = tx
1520 .prepare(
1521 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1522 VALUES (?, ?, ?, ?);",
1523 )
1524 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1525
Janis Danisevskis66784c42021-01-27 08:40:25 -08001526 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001527 stmt.insert(params![
1528 key_id.0,
1529 p.get_tag().0,
1530 p.key_parameter_value(),
1531 p.security_level().0
1532 ])
1533 .with_context(|| {
1534 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1535 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001536 }
1537 Ok(())
1538 }
1539
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001540 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001541 #[cfg(test)]
1542 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001543 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001544 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001545 })
1546 .context("In insert_key_metadata.")
1547 }
1548
Max Bires2b2e6562020-09-22 11:22:36 -07001549 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1550 /// on the public key.
1551 pub fn store_signed_attestation_certificate_chain(
1552 &mut self,
1553 raw_public_key: &[u8],
1554 cert_chain: &[u8],
1555 expiration_date: i64,
1556 km_uuid: &Uuid,
1557 ) -> Result<()> {
1558 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1559 let mut stmt = tx
1560 .prepare(
1561 "SELECT keyentryid
1562 FROM persistent.keymetadata
1563 WHERE tag = ? AND data = ? AND keyentryid IN
1564 (SELECT id
1565 FROM persistent.keyentry
1566 WHERE
1567 alias IS NULL AND
1568 domain IS NULL AND
1569 namespace IS NULL AND
1570 key_type = ? AND
1571 km_uuid = ?);",
1572 )
1573 .context("Failed to store attestation certificate chain.")?;
1574 let mut rows = stmt
1575 .query(params![
1576 KeyMetaData::AttestationRawPubKey,
1577 raw_public_key,
1578 KeyType::Attestation,
1579 km_uuid
1580 ])
1581 .context("Failed to fetch keyid")?;
1582 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1583 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1584 .get(0)
1585 .context("Failed to unpack id.")
1586 })
1587 .context("Failed to get key_id.")?;
1588 let num_updated = tx
1589 .execute(
1590 "UPDATE persistent.keyentry
1591 SET alias = ?
1592 WHERE id = ?;",
1593 params!["signed", key_id],
1594 )
1595 .context("Failed to update alias.")?;
1596 if num_updated != 1 {
1597 return Err(KsError::sys()).context("Alias not updated for the key.");
1598 }
1599 let mut metadata = KeyMetaData::new();
1600 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1601 expiration_date,
1602 )));
1603 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001604 Self::set_blob_internal(
1605 &tx,
1606 key_id,
1607 SubComponentType::CERT_CHAIN,
1608 Some(cert_chain),
1609 None,
1610 )
1611 .context("Failed to insert cert chain")?;
1612 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001613 })
1614 .context("In store_signed_attestation_certificate_chain: ")
1615 }
1616
1617 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1618 /// currently have a key assigned to it.
1619 pub fn assign_attestation_key(
1620 &mut self,
1621 domain: Domain,
1622 namespace: i64,
1623 km_uuid: &Uuid,
1624 ) -> Result<()> {
1625 match domain {
1626 Domain::APP | Domain::SELINUX => {}
1627 _ => {
1628 return Err(KsError::sys()).context(format!(
1629 concat!(
1630 "In assign_attestation_key: Domain {:?} ",
1631 "must be either App or SELinux.",
1632 ),
1633 domain
1634 ));
1635 }
1636 }
1637 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1638 let result = tx
1639 .execute(
1640 "UPDATE persistent.keyentry
1641 SET domain=?1, namespace=?2
1642 WHERE
1643 id =
1644 (SELECT MIN(id)
1645 FROM persistent.keyentry
1646 WHERE ALIAS IS NOT NULL
1647 AND domain IS NULL
1648 AND key_type IS ?3
1649 AND state IS ?4
1650 AND km_uuid IS ?5)
1651 AND
1652 (SELECT COUNT(*)
1653 FROM persistent.keyentry
1654 WHERE domain=?1
1655 AND namespace=?2
1656 AND key_type IS ?3
1657 AND state IS ?4
1658 AND km_uuid IS ?5) = 0;",
1659 params![
1660 domain.0 as u32,
1661 namespace,
1662 KeyType::Attestation,
1663 KeyLifeCycle::Live,
1664 km_uuid,
1665 ],
1666 )
1667 .context("Failed to assign attestation key")?;
1668 if result != 1 {
1669 return Err(KsError::sys()).context(format!(
1670 "Expected to update a single entry but instead updated {}.",
1671 result
1672 ));
1673 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001674 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001675 })
1676 .context("In assign_attestation_key: ")
1677 }
1678
1679 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1680 /// provisioning server, or the maximum number available if there are not num_keys number of
1681 /// entries in the table.
1682 pub fn fetch_unsigned_attestation_keys(
1683 &mut self,
1684 num_keys: i32,
1685 km_uuid: &Uuid,
1686 ) -> Result<Vec<Vec<u8>>> {
1687 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1688 let mut stmt = tx
1689 .prepare(
1690 "SELECT data
1691 FROM persistent.keymetadata
1692 WHERE tag = ? AND keyentryid IN
1693 (SELECT id
1694 FROM persistent.keyentry
1695 WHERE
1696 alias IS NULL AND
1697 domain IS NULL AND
1698 namespace IS NULL AND
1699 key_type = ? AND
1700 km_uuid = ?
1701 LIMIT ?);",
1702 )
1703 .context("Failed to prepare statement")?;
1704 let rows = stmt
1705 .query_map(
1706 params![
1707 KeyMetaData::AttestationMacedPublicKey,
1708 KeyType::Attestation,
1709 km_uuid,
1710 num_keys
1711 ],
1712 |row| Ok(row.get(0)?),
1713 )?
1714 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1715 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001716 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001717 })
1718 .context("In fetch_unsigned_attestation_keys")
1719 }
1720
1721 /// Removes any keys that have expired as of the current time. Returns the number of keys
1722 /// marked unreferenced that are bound to be garbage collected.
1723 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
1724 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1725 let mut stmt = tx
1726 .prepare(
1727 "SELECT keyentryid, data
1728 FROM persistent.keymetadata
1729 WHERE tag = ? AND keyentryid IN
1730 (SELECT id
1731 FROM persistent.keyentry
1732 WHERE key_type = ?);",
1733 )
1734 .context("Failed to prepare query")?;
1735 let key_ids_to_check = stmt
1736 .query_map(
1737 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1738 |row| Ok((row.get(0)?, row.get(1)?)),
1739 )?
1740 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1741 .context("Failed to get date metadata")?;
1742 let curr_time = DateTime::from_millis_epoch(
1743 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1744 );
1745 let mut num_deleted = 0;
1746 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1747 if Self::mark_unreferenced(&tx, id)? {
1748 num_deleted += 1;
1749 }
1750 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001751 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001752 })
1753 .context("In delete_expired_attestation_keys: ")
1754 }
1755
1756 /// Counts the number of keys that will expire by the provided epoch date and the number of
1757 /// keys not currently assigned to a domain.
1758 pub fn get_attestation_pool_status(
1759 &mut self,
1760 date: i64,
1761 km_uuid: &Uuid,
1762 ) -> Result<AttestationPoolStatus> {
1763 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1764 let mut stmt = tx.prepare(
1765 "SELECT data
1766 FROM persistent.keymetadata
1767 WHERE tag = ? AND keyentryid IN
1768 (SELECT id
1769 FROM persistent.keyentry
1770 WHERE alias IS NOT NULL
1771 AND key_type = ?
1772 AND km_uuid = ?
1773 AND state = ?);",
1774 )?;
1775 let times = stmt
1776 .query_map(
1777 params![
1778 KeyMetaData::AttestationExpirationDate,
1779 KeyType::Attestation,
1780 km_uuid,
1781 KeyLifeCycle::Live
1782 ],
1783 |row| Ok(row.get(0)?),
1784 )?
1785 .collect::<rusqlite::Result<Vec<DateTime>>>()
1786 .context("Failed to execute metadata statement")?;
1787 let expiring =
1788 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1789 as i32;
1790 stmt = tx.prepare(
1791 "SELECT alias, domain
1792 FROM persistent.keyentry
1793 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1794 )?;
1795 let rows = stmt
1796 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1797 Ok((row.get(0)?, row.get(1)?))
1798 })?
1799 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
1800 .context("Failed to execute keyentry statement")?;
1801 let mut unassigned = 0i32;
1802 let mut attested = 0i32;
1803 let total = rows.len() as i32;
1804 for (alias, domain) in rows {
1805 match (alias, domain) {
1806 (Some(_alias), None) => {
1807 attested += 1;
1808 unassigned += 1;
1809 }
1810 (Some(_alias), Some(_domain)) => {
1811 attested += 1;
1812 }
1813 _ => {}
1814 }
1815 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001816 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001817 })
1818 .context("In get_attestation_pool_status: ")
1819 }
1820
1821 /// Fetches the private key and corresponding certificate chain assigned to a
1822 /// domain/namespace pair. Will either return nothing if the domain/namespace is
1823 /// not assigned, or one CertificateChain.
1824 pub fn retrieve_attestation_key_and_cert_chain(
1825 &mut self,
1826 domain: Domain,
1827 namespace: i64,
1828 km_uuid: &Uuid,
1829 ) -> Result<Option<CertificateChain>> {
1830 match domain {
1831 Domain::APP | Domain::SELINUX => {}
1832 _ => {
1833 return Err(KsError::sys())
1834 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1835 }
1836 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001837 self.with_transaction(TransactionBehavior::Deferred, |tx| {
1838 let mut stmt = tx.prepare(
1839 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07001840 FROM persistent.blobentry
1841 WHERE keyentryid IN
1842 (SELECT id
1843 FROM persistent.keyentry
1844 WHERE key_type = ?
1845 AND domain = ?
1846 AND namespace = ?
1847 AND state = ?
1848 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001849 )?;
1850 let rows = stmt
1851 .query_map(
1852 params![
1853 KeyType::Attestation,
1854 domain.0 as u32,
1855 namespace,
1856 KeyLifeCycle::Live,
1857 km_uuid
1858 ],
1859 |row| Ok((row.get(0)?, row.get(1)?)),
1860 )?
1861 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
1862 .context("In retrieve_attestation_key_and_cert_chain: query failed.")?;
1863 if rows.is_empty() {
1864 return Ok(None).no_gc();
1865 } else if rows.len() != 2 {
1866 return Err(KsError::sys()).context(format!(
1867 concat!(
Max Bires2b2e6562020-09-22 11:22:36 -07001868 "In retrieve_attestation_key_and_cert_chain: Expected to get a single attestation",
1869 "key chain but instead got {}."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001870 rows.len()
1871 ));
Max Bires2b2e6562020-09-22 11:22:36 -07001872 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001873 let mut km_blob: Vec<u8> = Vec::new();
1874 let mut cert_chain_blob: Vec<u8> = Vec::new();
1875 for row in rows {
1876 let sub_type: SubComponentType = row.0;
1877 match sub_type {
1878 SubComponentType::KEY_BLOB => {
1879 km_blob = row.1;
1880 }
1881 SubComponentType::CERT_CHAIN => {
1882 cert_chain_blob = row.1;
1883 }
1884 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
1885 }
1886 }
1887 Ok(Some(CertificateChain {
1888 private_key: ZVec::try_from(km_blob)?,
1889 cert_chain: ZVec::try_from(cert_chain_blob)?,
1890 }))
1891 .no_gc()
1892 })
Max Bires2b2e6562020-09-22 11:22:36 -07001893 }
1894
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001895 /// Updates the alias column of the given key id `newid` with the given alias,
1896 /// and atomically, removes the alias, domain, and namespace from another row
1897 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001898 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1899 /// collector.
1900 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001901 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001902 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001903 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001904 domain: &Domain,
1905 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001906 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001907 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001908 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001909 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001910 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001911 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001912 domain
1913 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001914 }
1915 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001916 let updated = tx
1917 .execute(
1918 "UPDATE persistent.keyentry
1919 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07001920 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001921 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
1922 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001923 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001924 let result = tx
1925 .execute(
1926 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001927 SET alias = ?, state = ?
1928 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
1929 params![
1930 alias,
1931 KeyLifeCycle::Live,
1932 newid.0,
1933 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001934 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001935 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001936 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001937 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001938 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001939 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07001940 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001941 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001942 result
1943 ));
1944 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001945 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001946 }
1947
1948 /// Store a new key in a single transaction.
1949 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1950 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001951 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1952 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001953 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001954 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001955 key: &KeyDescriptor,
1956 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001957 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08001958 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001959 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001960 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001961 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001962 let (alias, domain, namespace) = match key {
1963 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1964 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1965 (alias, key.domain, nspace)
1966 }
1967 _ => {
1968 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1969 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
1970 }
1971 };
1972 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001973 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001974 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001975 let (blob, blob_metadata) = *blob_info;
1976 Self::set_blob_internal(
1977 tx,
1978 key_id.id(),
1979 SubComponentType::KEY_BLOB,
1980 Some(blob),
1981 Some(&blob_metadata),
1982 )
1983 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001984 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001985 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001986 .context("Trying to insert the certificate.")?;
1987 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001988 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001989 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001990 tx,
1991 key_id.id(),
1992 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001993 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001994 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001995 )
1996 .context("Trying to insert the certificate chain.")?;
1997 }
1998 Self::insert_keyparameter_internal(tx, &key_id, params)
1999 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002000 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002001 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002002 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002003 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002004 })
2005 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002006 }
2007
Janis Danisevskis377d1002021-01-27 19:07:48 -08002008 /// Store a new certificate
2009 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2010 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002011 pub fn store_new_certificate(
2012 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002013 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002014 cert: &[u8],
2015 km_uuid: &Uuid,
2016 ) -> Result<KeyIdGuard> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002017 let (alias, domain, namespace) = match key {
2018 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2019 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2020 (alias, key.domain, nspace)
2021 }
2022 _ => {
2023 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2024 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2025 )
2026 }
2027 };
2028 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002029 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002030 .context("Trying to create new key entry.")?;
2031
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002032 Self::set_blob_internal(
2033 tx,
2034 key_id.id(),
2035 SubComponentType::CERT_CHAIN,
2036 Some(cert),
2037 None,
2038 )
2039 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002040
2041 let mut metadata = KeyMetaData::new();
2042 metadata.add(KeyMetaEntry::CreationDate(
2043 DateTime::now().context("Trying to make creation time.")?,
2044 ));
2045
2046 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2047
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002048 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002049 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002050 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002051 })
2052 .context("In store_new_certificate.")
2053 }
2054
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002055 // Helper function loading the key_id given the key descriptor
2056 // tuple comprising domain, namespace, and alias.
2057 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002058 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002059 let alias = key
2060 .alias
2061 .as_ref()
2062 .map_or_else(|| Err(KsError::sys()), Ok)
2063 .context("In load_key_entry_id: Alias must be specified.")?;
2064 let mut stmt = tx
2065 .prepare(
2066 "SELECT id FROM persistent.keyentry
2067 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002068 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002069 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002070 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002071 AND alias = ?
2072 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002073 )
2074 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2075 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002076 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002077 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002078 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002079 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002080 .get(0)
2081 .context("Failed to unpack id.")
2082 })
2083 .context("In load_key_entry_id.")
2084 }
2085
2086 /// This helper function completes the access tuple of a key, which is required
2087 /// to perform access control. The strategy depends on the `domain` field in the
2088 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002089 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002090 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002091 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002092 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002093 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002094 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002095 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002096 /// `namespace`.
2097 /// In each case the information returned is sufficient to perform the access
2098 /// check and the key id can be used to load further key artifacts.
2099 fn load_access_tuple(
2100 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002101 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002102 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002103 caller_uid: u32,
2104 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2105 match key.domain {
2106 // Domain App or SELinux. In this case we load the key_id from
2107 // the keyentry database for further loading of key components.
2108 // We already have the full access tuple to perform access control.
2109 // The only distinction is that we use the caller_uid instead
2110 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002111 // Domain::APP.
2112 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002113 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002114 if access_key.domain == Domain::APP {
2115 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002116 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002117 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002118 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002119
2120 Ok((key_id, access_key, None))
2121 }
2122
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002123 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002124 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002125 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002126 let mut stmt = tx
2127 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002128 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002129 WHERE grantee = ? AND id = ?;",
2130 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002131 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002132 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002133 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002134 .context("Domain:Grant: query failed.")?;
2135 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002136 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002137 let r =
2138 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002139 Ok((
2140 r.get(0).context("Failed to unpack key_id.")?,
2141 r.get(1).context("Failed to unpack access_vector.")?,
2142 ))
2143 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002144 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002145 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002146 }
2147
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002148 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002149 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002150 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002151 let (domain, namespace): (Domain, i64) = {
2152 let mut stmt = tx
2153 .prepare(
2154 "SELECT domain, namespace FROM persistent.keyentry
2155 WHERE
2156 id = ?
2157 AND state = ?;",
2158 )
2159 .context("Domain::KEY_ID: prepare statement failed")?;
2160 let mut rows = stmt
2161 .query(params![key.nspace, KeyLifeCycle::Live])
2162 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002163 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002164 let r =
2165 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002166 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002167 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002168 r.get(1).context("Failed to unpack namespace.")?,
2169 ))
2170 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002171 .context("Domain::KEY_ID.")?
2172 };
2173
2174 // We may use a key by id after loading it by grant.
2175 // In this case we have to check if the caller has a grant for this particular
2176 // key. We can skip this if we already know that the caller is the owner.
2177 // But we cannot know this if domain is anything but App. E.g. in the case
2178 // of Domain::SELINUX we have to speculatively check for grants because we have to
2179 // consult the SEPolicy before we know if the caller is the owner.
2180 let access_vector: Option<KeyPermSet> =
2181 if domain != Domain::APP || namespace != caller_uid as i64 {
2182 let access_vector: Option<i32> = tx
2183 .query_row(
2184 "SELECT access_vector FROM persistent.grant
2185 WHERE grantee = ? AND keyentryid = ?;",
2186 params![caller_uid as i64, key.nspace],
2187 |row| row.get(0),
2188 )
2189 .optional()
2190 .context("Domain::KEY_ID: query grant failed.")?;
2191 access_vector.map(|p| p.into())
2192 } else {
2193 None
2194 };
2195
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002196 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002197 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002198 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002199 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002200
Janis Danisevskis45760022021-01-19 16:34:10 -08002201 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002202 }
2203 _ => Err(anyhow!(KsError::sys())),
2204 }
2205 }
2206
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002207 fn load_blob_components(
2208 key_id: i64,
2209 load_bits: KeyEntryLoadBits,
2210 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002211 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002212 let mut stmt = tx
2213 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002214 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002215 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2216 )
2217 .context("In load_blob_components: prepare statement failed.")?;
2218
2219 let mut rows =
2220 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2221
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002222 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002223 let mut cert_blob: Option<Vec<u8>> = None;
2224 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002225 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002226 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002227 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002228 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002229 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002230 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2231 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002232 key_blob = Some((
2233 row.get(0).context("Failed to extract key blob id.")?,
2234 row.get(2).context("Failed to extract key blob.")?,
2235 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002236 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002237 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002238 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002239 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002240 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002241 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002242 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002243 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002244 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002245 (SubComponentType::CERT, _, _)
2246 | (SubComponentType::CERT_CHAIN, _, _)
2247 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002248 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2249 }
2250 Ok(())
2251 })
2252 .context("In load_blob_components.")?;
2253
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002254 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2255 Ok(Some((
2256 blob,
2257 BlobMetaData::load_from_db(blob_id, tx)
2258 .context("In load_blob_components: Trying to load blob_metadata.")?,
2259 )))
2260 })?;
2261
2262 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002263 }
2264
2265 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2266 let mut stmt = tx
2267 .prepare(
2268 "SELECT tag, data, security_level from persistent.keyparameter
2269 WHERE keyentryid = ?;",
2270 )
2271 .context("In load_key_parameters: prepare statement failed.")?;
2272
2273 let mut parameters: Vec<KeyParameter> = Vec::new();
2274
2275 let mut rows =
2276 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002277 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002278 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2279 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002280 parameters.push(
2281 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2282 .context("Failed to read KeyParameter.")?,
2283 );
2284 Ok(())
2285 })
2286 .context("In load_key_parameters.")?;
2287
2288 Ok(parameters)
2289 }
2290
Qi Wub9433b52020-12-01 14:52:46 +08002291 /// Decrements the usage count of a limited use key. This function first checks whether the
2292 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2293 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2294 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002295 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Qi Wub9433b52020-12-01 14:52:46 +08002296 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2297 let limit: Option<i32> = tx
2298 .query_row(
2299 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2300 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2301 |row| row.get(0),
2302 )
2303 .optional()
2304 .context("Trying to load usage count")?;
2305
2306 let limit = limit
2307 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2308 .context("The Key no longer exists. Key is exhausted.")?;
2309
2310 tx.execute(
2311 "UPDATE persistent.keyparameter
2312 SET data = data - 1
2313 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2314 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2315 )
2316 .context("Failed to update key usage count.")?;
2317
2318 match limit {
2319 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002320 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002321 .context("Trying to mark limited use key for deletion."),
2322 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002323 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002324 }
2325 })
2326 .context("In check_and_update_key_usage_count.")
2327 }
2328
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002329 /// Load a key entry by the given key descriptor.
2330 /// It uses the `check_permission` callback to verify if the access is allowed
2331 /// given the key access tuple read from the database using `load_access_tuple`.
2332 /// With `load_bits` the caller may specify which blobs shall be loaded from
2333 /// the blob database.
2334 pub fn load_key_entry(
2335 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002336 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002337 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002338 load_bits: KeyEntryLoadBits,
2339 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002340 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2341 ) -> Result<(KeyIdGuard, KeyEntry)> {
2342 loop {
2343 match self.load_key_entry_internal(
2344 key,
2345 key_type,
2346 load_bits,
2347 caller_uid,
2348 &check_permission,
2349 ) {
2350 Ok(result) => break Ok(result),
2351 Err(e) => {
2352 if Self::is_locked_error(&e) {
2353 std::thread::sleep(std::time::Duration::from_micros(500));
2354 continue;
2355 } else {
2356 return Err(e).context("In load_key_entry.");
2357 }
2358 }
2359 }
2360 }
2361 }
2362
2363 fn load_key_entry_internal(
2364 &mut self,
2365 key: &KeyDescriptor,
2366 key_type: KeyType,
2367 load_bits: KeyEntryLoadBits,
2368 caller_uid: u32,
2369 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002370 ) -> Result<(KeyIdGuard, KeyEntry)> {
2371 // KEY ID LOCK 1/2
2372 // If we got a key descriptor with a key id we can get the lock right away.
2373 // Otherwise we have to defer it until we know the key id.
2374 let key_id_guard = match key.domain {
2375 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2376 _ => None,
2377 };
2378
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002379 let tx = self
2380 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002381 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002382 .context("In load_key_entry: Failed to initialize transaction.")?;
2383
2384 // Load the key_id and complete the access control tuple.
2385 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002386 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2387 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002388
2389 // Perform access control. It is vital that we return here if the permission is denied.
2390 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002391 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002392
Janis Danisevskisaec14592020-11-12 09:41:49 -08002393 // KEY ID LOCK 2/2
2394 // If we did not get a key id lock by now, it was because we got a key descriptor
2395 // without a key id. At this point we got the key id, so we can try and get a lock.
2396 // However, we cannot block here, because we are in the middle of the transaction.
2397 // So first we try to get the lock non blocking. If that fails, we roll back the
2398 // transaction and block until we get the lock. After we successfully got the lock,
2399 // we start a new transaction and load the access tuple again.
2400 //
2401 // We don't need to perform access control again, because we already established
2402 // that the caller had access to the given key. But we need to make sure that the
2403 // key id still exists. So we have to load the key entry by key id this time.
2404 let (key_id_guard, tx) = match key_id_guard {
2405 None => match KEY_ID_LOCK.try_get(key_id) {
2406 None => {
2407 // Roll back the transaction.
2408 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002409
Janis Danisevskisaec14592020-11-12 09:41:49 -08002410 // Block until we have a key id lock.
2411 let key_id_guard = KEY_ID_LOCK.get(key_id);
2412
2413 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002414 let tx = self
2415 .conn
2416 .unchecked_transaction()
2417 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002418
2419 Self::load_access_tuple(
2420 &tx,
2421 // This time we have to load the key by the retrieved key id, because the
2422 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002423 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002424 domain: Domain::KEY_ID,
2425 nspace: key_id,
2426 ..Default::default()
2427 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002428 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002429 caller_uid,
2430 )
2431 .context("In load_key_entry. (deferred key lock)")?;
2432 (key_id_guard, tx)
2433 }
2434 Some(l) => (l, tx),
2435 },
2436 Some(key_id_guard) => (key_id_guard, tx),
2437 };
2438
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002439 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2440 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002441
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002442 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2443
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002444 Ok((key_id_guard, key_entry))
2445 }
2446
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002447 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002448 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002449 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2450 .context("Trying to delete keyentry.")?;
2451 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2452 .context("Trying to delete keymetadata.")?;
2453 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2454 .context("Trying to delete keyparameters.")?;
2455 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2456 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002457 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002458 }
2459
2460 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002461 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002462 pub fn unbind_key(
2463 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002464 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002465 key_type: KeyType,
2466 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002467 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002468 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002469 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2470 let (key_id, access_key_descriptor, access_vector) =
2471 Self::load_access_tuple(tx, key, key_type, caller_uid)
2472 .context("Trying to get access tuple.")?;
2473
2474 // Perform access control. It is vital that we return here if the permission is denied.
2475 // So do not touch that '?' at the end.
2476 check_permission(&access_key_descriptor, access_vector)
2477 .context("While checking permission.")?;
2478
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002479 Self::mark_unreferenced(tx, key_id)
2480 .map(|need_gc| (need_gc, ()))
2481 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002482 })
2483 .context("In unbind_key.")
2484 }
2485
Max Bires8e93d2b2021-01-14 13:17:59 -08002486 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2487 tx.query_row(
2488 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2489 params![key_id],
2490 |row| row.get(0),
2491 )
2492 .context("In get_key_km_uuid.")
2493 }
2494
Hasini Gunasingheda895552021-01-27 19:34:37 +00002495 /// Delete the keys created on behalf of the user, denoted by the user id.
2496 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2497 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2498 /// The caller of this function should notify the gc if the returned value is true.
2499 pub fn unbind_keys_for_user(
2500 &mut self,
2501 user_id: u32,
2502 keep_non_super_encrypted_keys: bool,
2503 ) -> Result<()> {
2504 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2505 let mut stmt = tx
2506 .prepare(&format!(
2507 "SELECT id from persistent.keyentry
2508 WHERE (
2509 key_type = ?
2510 AND domain = ?
2511 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2512 AND state = ?
2513 ) OR (
2514 key_type = ?
2515 AND namespace = ?
2516 AND alias = ?
2517 AND state = ?
2518 );",
2519 aid_user_offset = AID_USER_OFFSET
2520 ))
2521 .context(concat!(
2522 "In unbind_keys_for_user. ",
2523 "Failed to prepare the query to find the keys created by apps."
2524 ))?;
2525
2526 let mut rows = stmt
2527 .query(params![
2528 // WHERE client key:
2529 KeyType::Client,
2530 Domain::APP.0 as u32,
2531 user_id,
2532 KeyLifeCycle::Live,
2533 // OR super key:
2534 KeyType::Super,
2535 user_id,
2536 Self::USER_SUPER_KEY_ALIAS,
2537 KeyLifeCycle::Live
2538 ])
2539 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2540
2541 let mut key_ids: Vec<i64> = Vec::new();
2542 db_utils::with_rows_extract_all(&mut rows, |row| {
2543 key_ids
2544 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2545 Ok(())
2546 })
2547 .context("In unbind_keys_for_user.")?;
2548
2549 let mut notify_gc = false;
2550 for key_id in key_ids {
2551 if keep_non_super_encrypted_keys {
2552 // Load metadata and filter out non-super-encrypted keys.
2553 if let (_, Some((_, blob_metadata)), _, _) =
2554 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2555 .context("In unbind_keys_for_user: Trying to load blob info.")?
2556 {
2557 if blob_metadata.encrypted_by().is_none() {
2558 continue;
2559 }
2560 }
2561 }
2562 notify_gc = Self::mark_unreferenced(&tx, key_id as u64 as i64)
2563 .context("In unbind_keys_for_user.")?
2564 || notify_gc;
2565 }
2566 Ok(()).do_gc(notify_gc)
2567 })
2568 .context("In unbind_keys_for_user.")
2569 }
2570
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002571 fn load_key_components(
2572 tx: &Transaction,
2573 load_bits: KeyEntryLoadBits,
2574 key_id: i64,
2575 ) -> Result<KeyEntry> {
2576 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2577
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002578 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002579 Self::load_blob_components(key_id, load_bits, &tx)
2580 .context("In load_key_components.")?;
2581
Max Bires8e93d2b2021-01-14 13:17:59 -08002582 let parameters = Self::load_key_parameters(key_id, &tx)
2583 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002584
Max Bires8e93d2b2021-01-14 13:17:59 -08002585 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2586 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002587
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002588 Ok(KeyEntry {
2589 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002590 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002591 cert: cert_blob,
2592 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002593 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002594 parameters,
2595 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002596 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002597 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002598 }
2599
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002600 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2601 /// The key descriptors will have the domain, nspace, and alias field set.
2602 /// Domain must be APP or SELINUX, the caller must make sure of that.
2603 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002604 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2605 let mut stmt = tx
2606 .prepare(
2607 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002608 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002609 )
2610 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002611
Janis Danisevskis66784c42021-01-27 08:40:25 -08002612 let mut rows = stmt
2613 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2614 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002615
Janis Danisevskis66784c42021-01-27 08:40:25 -08002616 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2617 db_utils::with_rows_extract_all(&mut rows, |row| {
2618 descriptors.push(KeyDescriptor {
2619 domain,
2620 nspace: namespace,
2621 alias: Some(row.get(0).context("Trying to extract alias.")?),
2622 blob: None,
2623 });
2624 Ok(())
2625 })
2626 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002627 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002628 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002629 }
2630
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002631 /// Adds a grant to the grant table.
2632 /// Like `load_key_entry` this function loads the access tuple before
2633 /// it uses the callback for a permission check. Upon success,
2634 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2635 /// grant table. The new row will have a randomized id, which is used as
2636 /// grant id in the namespace field of the resulting KeyDescriptor.
2637 pub fn grant(
2638 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002639 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002640 caller_uid: u32,
2641 grantee_uid: u32,
2642 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002643 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002644 ) -> Result<KeyDescriptor> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002645 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2646 // Load the key_id and complete the access control tuple.
2647 // We ignore the access vector here because grants cannot be granted.
2648 // The access vector returned here expresses the permissions the
2649 // grantee has if key.domain == Domain::GRANT. But this vector
2650 // cannot include the grant permission by design, so there is no way the
2651 // subsequent permission check can pass.
2652 // We could check key.domain == Domain::GRANT and fail early.
2653 // But even if we load the access tuple by grant here, the permission
2654 // check denies the attempt to create a grant by grant descriptor.
2655 let (key_id, access_key_descriptor, _) =
2656 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2657 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002658
Janis Danisevskis66784c42021-01-27 08:40:25 -08002659 // Perform access control. It is vital that we return here if the permission
2660 // was denied. So do not touch that '?' at the end of the line.
2661 // This permission check checks if the caller has the grant permission
2662 // for the given key and in addition to all of the permissions
2663 // expressed in `access_vector`.
2664 check_permission(&access_key_descriptor, &access_vector)
2665 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002666
Janis Danisevskis66784c42021-01-27 08:40:25 -08002667 let grant_id = if let Some(grant_id) = tx
2668 .query_row(
2669 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002670 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002671 params![key_id, grantee_uid],
2672 |row| row.get(0),
2673 )
2674 .optional()
2675 .context("In grant: Failed get optional existing grant id.")?
2676 {
2677 tx.execute(
2678 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002679 SET access_vector = ?
2680 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002681 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002682 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08002683 .context("In grant: Failed to update existing grant.")?;
2684 grant_id
2685 } else {
2686 Self::insert_with_retry(|id| {
2687 tx.execute(
2688 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2689 VALUES (?, ?, ?, ?);",
2690 params![id, grantee_uid, key_id, i32::from(access_vector)],
2691 )
2692 })
2693 .context("In grant")?
2694 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002695
Janis Danisevskis66784c42021-01-27 08:40:25 -08002696 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002697 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002698 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002699 }
2700
2701 /// This function checks permissions like `grant` and `load_key_entry`
2702 /// before removing a grant from the grant table.
2703 pub fn ungrant(
2704 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002705 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002706 caller_uid: u32,
2707 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002708 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002709 ) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002710 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2711 // Load the key_id and complete the access control tuple.
2712 // We ignore the access vector here because grants cannot be granted.
2713 let (key_id, access_key_descriptor, _) =
2714 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2715 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002716
Janis Danisevskis66784c42021-01-27 08:40:25 -08002717 // Perform access control. We must return here if the permission
2718 // was denied. So do not touch the '?' at the end of this line.
2719 check_permission(&access_key_descriptor)
2720 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002721
Janis Danisevskis66784c42021-01-27 08:40:25 -08002722 tx.execute(
2723 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002724 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002725 params![key_id, grantee_uid],
2726 )
2727 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002728
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002729 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002730 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002731 }
2732
Joel Galenson845f74b2020-09-09 14:11:55 -07002733 // Generates a random id and passes it to the given function, which will
2734 // try to insert it into a database. If that insertion fails, retry;
2735 // otherwise return the id.
2736 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2737 loop {
2738 let newid: i64 = random();
2739 match inserter(newid) {
2740 // If the id already existed, try again.
2741 Err(rusqlite::Error::SqliteFailure(
2742 libsqlite3_sys::Error {
2743 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2744 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2745 },
2746 _,
2747 )) => (),
2748 Err(e) => {
2749 return Err(e).context("In insert_with_retry: failed to insert into database.")
2750 }
2751 _ => return Ok(newid),
2752 }
2753 }
2754 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002755
2756 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
2757 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002758 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2759 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002760 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
2761 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
2762 params![
2763 auth_token.challenge,
2764 auth_token.userId,
2765 auth_token.authenticatorId,
2766 auth_token.authenticatorType.0 as i32,
2767 auth_token.timestamp.milliSeconds as i64,
2768 auth_token.mac,
2769 MonotonicRawTime::now(),
2770 ],
2771 )
2772 .context("In insert_auth_token: failed to insert auth token into the database")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002773 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002774 })
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002775 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002776
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002777 /// Find the newest auth token matching the given predicate.
2778 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002779 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002780 p: F,
2781 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
2782 where
2783 F: Fn(&AuthTokenEntry) -> bool,
2784 {
2785 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2786 let mut stmt = tx
2787 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
2788 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002789
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002790 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002791
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002792 while let Some(row) = rows.next().context("Failed to get next row.")? {
2793 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002794 HardwareAuthToken {
2795 challenge: row.get(1)?,
2796 userId: row.get(2)?,
2797 authenticatorId: row.get(3)?,
2798 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
2799 timestamp: Timestamp { milliSeconds: row.get(5)? },
2800 mac: row.get(6)?,
2801 },
2802 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002803 );
2804 if p(&entry) {
2805 return Ok(Some((
2806 entry,
2807 Self::get_last_off_body(tx)
2808 .context("In find_auth_token_entry: Trying to get last off body")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002809 )))
2810 .no_gc();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002811 }
2812 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002813 Ok(None).no_gc()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002814 })
2815 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002816 }
2817
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002818 /// Insert last_off_body into the metadata table at the initialization of auth token table
Janis Danisevskis66784c42021-01-27 08:40:25 -08002819 pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
2820 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2821 tx.execute(
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002822 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
2823 params!["last_off_body", last_off_body],
2824 )
2825 .context("In insert_last_off_body: failed to insert.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002826 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002827 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002828 }
2829
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002830 /// Update last_off_body when on_device_off_body is called
Janis Danisevskis66784c42021-01-27 08:40:25 -08002831 pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
2832 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2833 tx.execute(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002834 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
2835 params![last_off_body, "last_off_body"],
2836 )
2837 .context("In update_last_off_body: failed to update.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002838 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002839 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002840 }
2841
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002842 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002843 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002844 tx.query_row(
2845 "SELECT value from perboot.metadata WHERE key = ?;",
2846 params!["last_off_body"],
2847 |row| Ok(row.get(0)?),
2848 )
2849 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002850 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002851}
2852
2853#[cfg(test)]
2854mod tests {
2855
2856 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002857 use crate::key_parameter::{
2858 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2859 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2860 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002861 use crate::key_perm_set;
2862 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00002863 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002864 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002865 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2866 HardwareAuthToken::HardwareAuthToken,
2867 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002868 };
2869 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002870 Timestamp::Timestamp,
2871 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002872 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002873 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07002874 use std::cell::RefCell;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002875 use std::sync::atomic::{AtomicU8, Ordering};
2876 use std::sync::Arc;
2877 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002878 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08002879 #[cfg(disabled)]
2880 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002881
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002882 fn new_test_db() -> Result<KeystoreDB> {
2883 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
2884
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002885 let mut db = KeystoreDB { conn, gc: None };
Janis Danisevskis66784c42021-01-27 08:40:25 -08002886 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002887 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002888 })?;
2889 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002890 }
2891
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002892 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
2893 where
2894 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
2895 {
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002896 let super_key = Arc::new(SuperKeyManager::new());
2897
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002898 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002899 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002900
2901 KeystoreDB::new(path, Some(gc))
2902 }
2903
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002904 fn rebind_alias(
2905 db: &mut KeystoreDB,
2906 newid: &KeyIdGuard,
2907 alias: &str,
2908 domain: Domain,
2909 namespace: i64,
2910 ) -> Result<bool> {
2911 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002912 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002913 })
2914 .context("In rebind_alias.")
2915 }
2916
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002917 #[test]
2918 fn datetime() -> Result<()> {
2919 let conn = Connection::open_in_memory()?;
2920 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
2921 let now = SystemTime::now();
2922 let duration = Duration::from_secs(1000);
2923 let then = now.checked_sub(duration).unwrap();
2924 let soon = now.checked_add(duration).unwrap();
2925 conn.execute(
2926 "INSERT INTO test (ts) VALUES (?), (?), (?);",
2927 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
2928 )?;
2929 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
2930 let mut rows = stmt.query(NO_PARAMS)?;
2931 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
2932 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
2933 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
2934 assert!(rows.next()?.is_none());
2935 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
2936 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
2937 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
2938 Ok(())
2939 }
2940
Joel Galenson0891bc12020-07-20 10:37:03 -07002941 // Ensure that we're using the "injected" random function, not the real one.
2942 #[test]
2943 fn test_mocked_random() {
2944 let rand1 = random();
2945 let rand2 = random();
2946 let rand3 = random();
2947 if rand1 == rand2 {
2948 assert_eq!(rand2 + 1, rand3);
2949 } else {
2950 assert_eq!(rand1 + 1, rand2);
2951 assert_eq!(rand2, rand3);
2952 }
2953 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002954
Joel Galenson26f4d012020-07-17 14:57:21 -07002955 // Test that we have the correct tables.
2956 #[test]
2957 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002958 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07002959 let tables = db
2960 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07002961 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07002962 .query_map(params![], |row| row.get(0))?
2963 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002964 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002965 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002966 assert_eq!(tables[1], "blobmetadata");
2967 assert_eq!(tables[2], "grant");
2968 assert_eq!(tables[3], "keyentry");
2969 assert_eq!(tables[4], "keymetadata");
2970 assert_eq!(tables[5], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002971 let tables = db
2972 .conn
2973 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
2974 .query_map(params![], |row| row.get(0))?
2975 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002976
2977 assert_eq!(tables.len(), 2);
2978 assert_eq!(tables[0], "authtoken");
2979 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07002980 Ok(())
2981 }
2982
2983 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002984 fn test_auth_token_table_invariant() -> Result<()> {
2985 let mut db = new_test_db()?;
2986 let auth_token1 = HardwareAuthToken {
2987 challenge: i64::MAX,
2988 userId: 200,
2989 authenticatorId: 200,
2990 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2991 timestamp: Timestamp { milliSeconds: 500 },
2992 mac: String::from("mac").into_bytes(),
2993 };
2994 db.insert_auth_token(&auth_token1)?;
2995 let auth_tokens_returned = get_auth_tokens(&mut db)?;
2996 assert_eq!(auth_tokens_returned.len(), 1);
2997
2998 // insert another auth token with the same values for the columns in the UNIQUE constraint
2999 // of the auth token table and different value for timestamp
3000 let auth_token2 = HardwareAuthToken {
3001 challenge: i64::MAX,
3002 userId: 200,
3003 authenticatorId: 200,
3004 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3005 timestamp: Timestamp { milliSeconds: 600 },
3006 mac: String::from("mac").into_bytes(),
3007 };
3008
3009 db.insert_auth_token(&auth_token2)?;
3010 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
3011 assert_eq!(auth_tokens_returned.len(), 1);
3012
3013 if let Some(auth_token) = auth_tokens_returned.pop() {
3014 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3015 }
3016
3017 // insert another auth token with the different values for the columns in the UNIQUE
3018 // constraint of the auth token table
3019 let auth_token3 = HardwareAuthToken {
3020 challenge: i64::MAX,
3021 userId: 201,
3022 authenticatorId: 200,
3023 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3024 timestamp: Timestamp { milliSeconds: 600 },
3025 mac: String::from("mac").into_bytes(),
3026 };
3027
3028 db.insert_auth_token(&auth_token3)?;
3029 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3030 assert_eq!(auth_tokens_returned.len(), 2);
3031
3032 Ok(())
3033 }
3034
3035 // utility function for test_auth_token_table_invariant()
3036 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
3037 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
3038
3039 let auth_token_entries: Vec<AuthTokenEntry> = stmt
3040 .query_map(NO_PARAMS, |row| {
3041 Ok(AuthTokenEntry::new(
3042 HardwareAuthToken {
3043 challenge: row.get(1)?,
3044 userId: row.get(2)?,
3045 authenticatorId: row.get(3)?,
3046 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3047 timestamp: Timestamp { milliSeconds: row.get(5)? },
3048 mac: row.get(6)?,
3049 },
3050 row.get(7)?,
3051 ))
3052 })?
3053 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
3054 Ok(auth_token_entries)
3055 }
3056
3057 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003058 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003059 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003060 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003061
Janis Danisevskis66784c42021-01-27 08:40:25 -08003062 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003063 let entries = get_keyentry(&db)?;
3064 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003065
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003066 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003067
3068 let entries_new = get_keyentry(&db)?;
3069 assert_eq!(entries, entries_new);
3070 Ok(())
3071 }
3072
3073 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003074 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003075 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3076 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003077 }
3078
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003079 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003080
Janis Danisevskis66784c42021-01-27 08:40:25 -08003081 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3082 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003083
3084 let entries = get_keyentry(&db)?;
3085 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003086 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3087 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003088
3089 // Test that we must pass in a valid Domain.
3090 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003091 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003092 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003093 );
3094 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003095 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003096 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003097 );
3098 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003099 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003100 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003101 );
3102
3103 Ok(())
3104 }
3105
Joel Galenson33c04ad2020-08-03 11:04:38 -07003106 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003107 fn test_add_unsigned_key() -> Result<()> {
3108 let mut db = new_test_db()?;
3109 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3110 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3111 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3112 db.create_attestation_key_entry(
3113 &public_key,
3114 &raw_public_key,
3115 &private_key,
3116 &KEYSTORE_UUID,
3117 )?;
3118 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3119 assert_eq!(keys.len(), 1);
3120 assert_eq!(keys[0], public_key);
3121 Ok(())
3122 }
3123
3124 #[test]
3125 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3126 let mut db = new_test_db()?;
3127 let expiration_date: i64 = 20;
3128 let namespace: i64 = 30;
3129 let base_byte: u8 = 1;
3130 let loaded_values =
3131 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3132 let chain =
3133 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3134 assert_eq!(true, chain.is_some());
3135 let cert_chain = chain.unwrap();
3136 assert_eq!(cert_chain.private_key.to_vec(), loaded_values[2]);
3137 assert_eq!(cert_chain.cert_chain.to_vec(), loaded_values[1]);
3138 Ok(())
3139 }
3140
3141 #[test]
3142 fn test_get_attestation_pool_status() -> Result<()> {
3143 let mut db = new_test_db()?;
3144 let namespace: i64 = 30;
3145 load_attestation_key_pool(
3146 &mut db, 10, /* expiration */
3147 namespace, 0x01, /* base_byte */
3148 )?;
3149 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3150 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3151 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3152 assert_eq!(status.expiring, 0);
3153 assert_eq!(status.attested, 3);
3154 assert_eq!(status.unassigned, 0);
3155 assert_eq!(status.total, 3);
3156 assert_eq!(
3157 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3158 1
3159 );
3160 assert_eq!(
3161 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3162 2
3163 );
3164 assert_eq!(
3165 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3166 3
3167 );
3168 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3169 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3170 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3171 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
3172 db.create_attestation_key_entry(
3173 &public_key,
3174 &raw_public_key,
3175 &private_key,
3176 &KEYSTORE_UUID,
3177 )?;
3178 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3179 assert_eq!(status.attested, 3);
3180 assert_eq!(status.unassigned, 0);
3181 assert_eq!(status.total, 4);
3182 db.store_signed_attestation_certificate_chain(
3183 &raw_public_key,
3184 &cert_chain,
3185 20,
3186 &KEYSTORE_UUID,
3187 )?;
3188 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3189 assert_eq!(status.attested, 4);
3190 assert_eq!(status.unassigned, 1);
3191 assert_eq!(status.total, 4);
3192 Ok(())
3193 }
3194
3195 #[test]
3196 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003197 let temp_dir =
3198 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3199 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003200 let expiration_date: i64 =
3201 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3202 let namespace: i64 = 30;
3203 let namespace_del1: i64 = 45;
3204 let namespace_del2: i64 = 60;
3205 let entry_values = load_attestation_key_pool(
3206 &mut db,
3207 expiration_date,
3208 namespace,
3209 0x01, /* base_byte */
3210 )?;
3211 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3212 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003213
3214 let blob_entry_row_count: u32 = db
3215 .conn
3216 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3217 .expect("Failed to get blob entry row count.");
3218 // We expect 6 rows here because there are two blobs per attestation key, i.e.,
3219 // One key and one certificate.
3220 assert_eq!(blob_entry_row_count, 6);
3221
Max Bires2b2e6562020-09-22 11:22:36 -07003222 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3223
3224 let mut cert_chain =
3225 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003226 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003227 let value = cert_chain.unwrap();
3228 assert_eq!(entry_values[1], value.cert_chain.to_vec());
3229 assert_eq!(entry_values[2], value.private_key.to_vec());
3230
3231 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3232 Domain::APP,
3233 namespace_del1,
3234 &KEYSTORE_UUID,
3235 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003236 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003237 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3238 Domain::APP,
3239 namespace_del2,
3240 &KEYSTORE_UUID,
3241 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003242 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003243
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003244 // Give the garbage collector half a second to catch up.
3245 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003246
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003247 let blob_entry_row_count: u32 = db
3248 .conn
3249 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3250 .expect("Failed to get blob entry row count.");
3251 // There shound be 2 blob entries left, because we deleted two of the attestation
3252 // key entries with two blobs each.
3253 assert_eq!(blob_entry_row_count, 2);
Max Bires2b2e6562020-09-22 11:22:36 -07003254
Max Bires2b2e6562020-09-22 11:22:36 -07003255 Ok(())
3256 }
3257
3258 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003259 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003260 fn extractor(
3261 ke: &KeyEntryRow,
3262 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3263 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003264 }
3265
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003266 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003267 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3268 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003269 let entries = get_keyentry(&db)?;
3270 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003271 assert_eq!(
3272 extractor(&entries[0]),
3273 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3274 );
3275 assert_eq!(
3276 extractor(&entries[1]),
3277 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3278 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003279
3280 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003281 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003282 let entries = get_keyentry(&db)?;
3283 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003284 assert_eq!(
3285 extractor(&entries[0]),
3286 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3287 );
3288 assert_eq!(
3289 extractor(&entries[1]),
3290 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3291 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003292
3293 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003294 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003295 let entries = get_keyentry(&db)?;
3296 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003297 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3298 assert_eq!(
3299 extractor(&entries[1]),
3300 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3301 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003302
3303 // Test that we must pass in a valid Domain.
3304 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003305 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003306 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003307 );
3308 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003309 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003310 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003311 );
3312 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003313 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003314 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003315 );
3316
3317 // Test that we correctly handle setting an alias for something that does not exist.
3318 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003319 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003320 "Expected to update a single entry but instead updated 0",
3321 );
3322 // Test that we correctly abort the transaction in this case.
3323 let entries = get_keyentry(&db)?;
3324 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003325 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3326 assert_eq!(
3327 extractor(&entries[1]),
3328 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3329 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003330
3331 Ok(())
3332 }
3333
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003334 #[test]
3335 fn test_grant_ungrant() -> Result<()> {
3336 const CALLER_UID: u32 = 15;
3337 const GRANTEE_UID: u32 = 12;
3338 const SELINUX_NAMESPACE: i64 = 7;
3339
3340 let mut db = new_test_db()?;
3341 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003342 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3343 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3344 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003345 )?;
3346 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003347 domain: super::Domain::APP,
3348 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003349 alias: Some("key".to_string()),
3350 blob: None,
3351 };
3352 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3353 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3354
3355 // Reset totally predictable random number generator in case we
3356 // are not the first test running on this thread.
3357 reset_random();
3358 let next_random = 0i64;
3359
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003360 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003361 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003362 assert_eq!(*a, PVEC1);
3363 assert_eq!(
3364 *k,
3365 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003366 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003367 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003368 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003369 alias: Some("key".to_string()),
3370 blob: None,
3371 }
3372 );
3373 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003374 })
3375 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003376
3377 assert_eq!(
3378 app_granted_key,
3379 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003380 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003381 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003382 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003383 alias: None,
3384 blob: None,
3385 }
3386 );
3387
3388 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003389 domain: super::Domain::SELINUX,
3390 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003391 alias: Some("yek".to_string()),
3392 blob: None,
3393 };
3394
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003395 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003396 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003397 assert_eq!(*a, PVEC1);
3398 assert_eq!(
3399 *k,
3400 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003401 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003402 // namespace must be the supplied SELinux
3403 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003404 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003405 alias: Some("yek".to_string()),
3406 blob: None,
3407 }
3408 );
3409 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003410 })
3411 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003412
3413 assert_eq!(
3414 selinux_granted_key,
3415 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003416 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003417 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003418 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003419 alias: None,
3420 blob: None,
3421 }
3422 );
3423
3424 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003425 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003426 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003427 assert_eq!(*a, PVEC2);
3428 assert_eq!(
3429 *k,
3430 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003431 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003432 // namespace must be the supplied SELinux
3433 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003434 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003435 alias: Some("yek".to_string()),
3436 blob: None,
3437 }
3438 );
3439 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003440 })
3441 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003442
3443 assert_eq!(
3444 selinux_granted_key,
3445 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003446 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003447 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003448 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003449 alias: None,
3450 blob: None,
3451 }
3452 );
3453
3454 {
3455 // Limiting scope of stmt, because it borrows db.
3456 let mut stmt = db
3457 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003458 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003459 let mut rows =
3460 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3461 Ok((
3462 row.get(0)?,
3463 row.get(1)?,
3464 row.get(2)?,
3465 KeyPermSet::from(row.get::<_, i32>(3)?),
3466 ))
3467 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003468
3469 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003470 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003471 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003472 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003473 assert!(rows.next().is_none());
3474 }
3475
3476 debug_dump_keyentry_table(&mut db)?;
3477 println!("app_key {:?}", app_key);
3478 println!("selinux_key {:?}", selinux_key);
3479
Janis Danisevskis66784c42021-01-27 08:40:25 -08003480 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3481 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003482
3483 Ok(())
3484 }
3485
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003486 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003487 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3488 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3489
3490 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003491 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003492 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003493 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003494 let mut blob_metadata = BlobMetaData::new();
3495 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3496 db.set_blob(
3497 &key_id,
3498 SubComponentType::KEY_BLOB,
3499 Some(TEST_KEY_BLOB),
3500 Some(&blob_metadata),
3501 )?;
3502 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3503 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003504 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003505
3506 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003507 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003508 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003509 )?;
3510 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003511 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3512 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003513 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003514 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003515 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003516 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003517 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003518 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003519 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003520
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003521 drop(rows);
3522 drop(stmt);
3523
3524 assert_eq!(
3525 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3526 BlobMetaData::load_from_db(id, tx).no_gc()
3527 })
3528 .expect("Should find blob metadata."),
3529 blob_metadata
3530 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003531 Ok(())
3532 }
3533
3534 static TEST_ALIAS: &str = "my super duper key";
3535
3536 #[test]
3537 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3538 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003539 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003540 .context("test_insert_and_load_full_keyentry_domain_app")?
3541 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003542 let (_key_guard, key_entry) = db
3543 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003544 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003545 domain: Domain::APP,
3546 nspace: 0,
3547 alias: Some(TEST_ALIAS.to_string()),
3548 blob: None,
3549 },
3550 KeyType::Client,
3551 KeyEntryLoadBits::BOTH,
3552 1,
3553 |_k, _av| Ok(()),
3554 )
3555 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003556 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003557
3558 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003559 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003560 domain: Domain::APP,
3561 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003562 alias: Some(TEST_ALIAS.to_string()),
3563 blob: None,
3564 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003565 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003566 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003567 |_, _| Ok(()),
3568 )
3569 .unwrap();
3570
3571 assert_eq!(
3572 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3573 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003574 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003575 domain: Domain::APP,
3576 nspace: 0,
3577 alias: Some(TEST_ALIAS.to_string()),
3578 blob: None,
3579 },
3580 KeyType::Client,
3581 KeyEntryLoadBits::NONE,
3582 1,
3583 |_k, _av| Ok(()),
3584 )
3585 .unwrap_err()
3586 .root_cause()
3587 .downcast_ref::<KsError>()
3588 );
3589
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003590 Ok(())
3591 }
3592
3593 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003594 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3595 let mut db = new_test_db()?;
3596
3597 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003598 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003599 domain: Domain::APP,
3600 nspace: 1,
3601 alias: Some(TEST_ALIAS.to_string()),
3602 blob: None,
3603 },
3604 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003605 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003606 )
3607 .expect("Trying to insert cert.");
3608
3609 let (_key_guard, mut key_entry) = db
3610 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003611 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003612 domain: Domain::APP,
3613 nspace: 1,
3614 alias: Some(TEST_ALIAS.to_string()),
3615 blob: None,
3616 },
3617 KeyType::Client,
3618 KeyEntryLoadBits::PUBLIC,
3619 1,
3620 |_k, _av| Ok(()),
3621 )
3622 .expect("Trying to read certificate entry.");
3623
3624 assert!(key_entry.pure_cert());
3625 assert!(key_entry.cert().is_none());
3626 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3627
3628 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003629 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003630 domain: Domain::APP,
3631 nspace: 1,
3632 alias: Some(TEST_ALIAS.to_string()),
3633 blob: None,
3634 },
3635 KeyType::Client,
3636 1,
3637 |_, _| Ok(()),
3638 )
3639 .unwrap();
3640
3641 assert_eq!(
3642 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3643 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003644 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003645 domain: Domain::APP,
3646 nspace: 1,
3647 alias: Some(TEST_ALIAS.to_string()),
3648 blob: None,
3649 },
3650 KeyType::Client,
3651 KeyEntryLoadBits::NONE,
3652 1,
3653 |_k, _av| Ok(()),
3654 )
3655 .unwrap_err()
3656 .root_cause()
3657 .downcast_ref::<KsError>()
3658 );
3659
3660 Ok(())
3661 }
3662
3663 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003664 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3665 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003666 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003667 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3668 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003669 let (_key_guard, key_entry) = db
3670 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003671 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003672 domain: Domain::SELINUX,
3673 nspace: 1,
3674 alias: Some(TEST_ALIAS.to_string()),
3675 blob: None,
3676 },
3677 KeyType::Client,
3678 KeyEntryLoadBits::BOTH,
3679 1,
3680 |_k, _av| Ok(()),
3681 )
3682 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003683 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003684
3685 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003686 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003687 domain: Domain::SELINUX,
3688 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003689 alias: Some(TEST_ALIAS.to_string()),
3690 blob: None,
3691 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003692 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003693 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003694 |_, _| Ok(()),
3695 )
3696 .unwrap();
3697
3698 assert_eq!(
3699 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3700 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003701 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003702 domain: Domain::SELINUX,
3703 nspace: 1,
3704 alias: Some(TEST_ALIAS.to_string()),
3705 blob: None,
3706 },
3707 KeyType::Client,
3708 KeyEntryLoadBits::NONE,
3709 1,
3710 |_k, _av| Ok(()),
3711 )
3712 .unwrap_err()
3713 .root_cause()
3714 .downcast_ref::<KsError>()
3715 );
3716
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003717 Ok(())
3718 }
3719
3720 #[test]
3721 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3722 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003723 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003724 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3725 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003726 let (_, key_entry) = db
3727 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003728 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003729 KeyType::Client,
3730 KeyEntryLoadBits::BOTH,
3731 1,
3732 |_k, _av| Ok(()),
3733 )
3734 .unwrap();
3735
Qi Wub9433b52020-12-01 14:52:46 +08003736 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003737
3738 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003739 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003740 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003741 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003742 |_, _| Ok(()),
3743 )
3744 .unwrap();
3745
3746 assert_eq!(
3747 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3748 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003749 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003750 KeyType::Client,
3751 KeyEntryLoadBits::NONE,
3752 1,
3753 |_k, _av| Ok(()),
3754 )
3755 .unwrap_err()
3756 .root_cause()
3757 .downcast_ref::<KsError>()
3758 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003759
3760 Ok(())
3761 }
3762
3763 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003764 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3765 let mut db = new_test_db()?;
3766 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3767 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3768 .0;
3769 // Update the usage count of the limited use key.
3770 db.check_and_update_key_usage_count(key_id)?;
3771
3772 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003773 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003774 KeyType::Client,
3775 KeyEntryLoadBits::BOTH,
3776 1,
3777 |_k, _av| Ok(()),
3778 )?;
3779
3780 // The usage count is decremented now.
3781 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3782
3783 Ok(())
3784 }
3785
3786 #[test]
3787 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3788 let mut db = new_test_db()?;
3789 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3790 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3791 .0;
3792 // Update the usage count of the limited use key.
3793 db.check_and_update_key_usage_count(key_id).expect(concat!(
3794 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3795 "This should succeed."
3796 ));
3797
3798 // Try to update the exhausted limited use key.
3799 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3800 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3801 "This should fail."
3802 ));
3803 assert_eq!(
3804 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3805 e.root_cause().downcast_ref::<KsError>().unwrap()
3806 );
3807
3808 Ok(())
3809 }
3810
3811 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003812 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3813 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003814 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003815 .context("test_insert_and_load_full_keyentry_from_grant")?
3816 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003817
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003818 let granted_key = db
3819 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003820 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003821 domain: Domain::APP,
3822 nspace: 0,
3823 alias: Some(TEST_ALIAS.to_string()),
3824 blob: None,
3825 },
3826 1,
3827 2,
3828 key_perm_set![KeyPerm::use_()],
3829 |_k, _av| Ok(()),
3830 )
3831 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003832
3833 debug_dump_grant_table(&mut db)?;
3834
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003835 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003836 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3837 assert_eq!(Domain::GRANT, k.domain);
3838 assert!(av.unwrap().includes(KeyPerm::use_()));
3839 Ok(())
3840 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003841 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003842
Qi Wub9433b52020-12-01 14:52:46 +08003843 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003844
Janis Danisevskis66784c42021-01-27 08:40:25 -08003845 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003846
3847 assert_eq!(
3848 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3849 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003850 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003851 KeyType::Client,
3852 KeyEntryLoadBits::NONE,
3853 2,
3854 |_k, _av| Ok(()),
3855 )
3856 .unwrap_err()
3857 .root_cause()
3858 .downcast_ref::<KsError>()
3859 );
3860
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003861 Ok(())
3862 }
3863
Janis Danisevskis45760022021-01-19 16:34:10 -08003864 // This test attempts to load a key by key id while the caller is not the owner
3865 // but a grant exists for the given key and the caller.
3866 #[test]
3867 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3868 let mut db = new_test_db()?;
3869 const OWNER_UID: u32 = 1u32;
3870 const GRANTEE_UID: u32 = 2u32;
3871 const SOMEONE_ELSE_UID: u32 = 3u32;
3872 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3873 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3874 .0;
3875
3876 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003877 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003878 domain: Domain::APP,
3879 nspace: 0,
3880 alias: Some(TEST_ALIAS.to_string()),
3881 blob: None,
3882 },
3883 OWNER_UID,
3884 GRANTEE_UID,
3885 key_perm_set![KeyPerm::use_()],
3886 |_k, _av| Ok(()),
3887 )
3888 .unwrap();
3889
3890 debug_dump_grant_table(&mut db)?;
3891
3892 let id_descriptor =
3893 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3894
3895 let (_, key_entry) = db
3896 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003897 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003898 KeyType::Client,
3899 KeyEntryLoadBits::BOTH,
3900 GRANTEE_UID,
3901 |k, av| {
3902 assert_eq!(Domain::APP, k.domain);
3903 assert_eq!(OWNER_UID as i64, k.nspace);
3904 assert!(av.unwrap().includes(KeyPerm::use_()));
3905 Ok(())
3906 },
3907 )
3908 .unwrap();
3909
3910 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3911
3912 let (_, key_entry) = db
3913 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003914 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003915 KeyType::Client,
3916 KeyEntryLoadBits::BOTH,
3917 SOMEONE_ELSE_UID,
3918 |k, av| {
3919 assert_eq!(Domain::APP, k.domain);
3920 assert_eq!(OWNER_UID as i64, k.nspace);
3921 assert!(av.is_none());
3922 Ok(())
3923 },
3924 )
3925 .unwrap();
3926
3927 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3928
Janis Danisevskis66784c42021-01-27 08:40:25 -08003929 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003930
3931 assert_eq!(
3932 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3933 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003934 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003935 KeyType::Client,
3936 KeyEntryLoadBits::NONE,
3937 GRANTEE_UID,
3938 |_k, _av| Ok(()),
3939 )
3940 .unwrap_err()
3941 .root_cause()
3942 .downcast_ref::<KsError>()
3943 );
3944
3945 Ok(())
3946 }
3947
Janis Danisevskisaec14592020-11-12 09:41:49 -08003948 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
3949
Janis Danisevskisaec14592020-11-12 09:41:49 -08003950 #[test]
3951 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
3952 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003953 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
3954 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003955 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08003956 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003957 .context("test_insert_and_load_full_keyentry_domain_app")?
3958 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003959 let (_key_guard, key_entry) = db
3960 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003961 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003962 domain: Domain::APP,
3963 nspace: 0,
3964 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
3965 blob: None,
3966 },
3967 KeyType::Client,
3968 KeyEntryLoadBits::BOTH,
3969 33,
3970 |_k, _av| Ok(()),
3971 )
3972 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003973 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08003974 let state = Arc::new(AtomicU8::new(1));
3975 let state2 = state.clone();
3976
3977 // Spawning a second thread that attempts to acquire the key id lock
3978 // for the same key as the primary thread. The primary thread then
3979 // waits, thereby forcing the secondary thread into the second stage
3980 // of acquiring the lock (see KEY ID LOCK 2/2 above).
3981 // The test succeeds if the secondary thread observes the transition
3982 // of `state` from 1 to 2, despite having a whole second to overtake
3983 // the primary thread.
3984 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003985 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003986 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08003987 assert!(db
3988 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003989 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08003990 domain: Domain::APP,
3991 nspace: 0,
3992 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
3993 blob: None,
3994 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003995 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08003996 KeyEntryLoadBits::BOTH,
3997 33,
3998 |_k, _av| Ok(()),
3999 )
4000 .is_ok());
4001 // We should only see a 2 here because we can only return
4002 // from load_key_entry when the `_key_guard` expires,
4003 // which happens at the end of the scope.
4004 assert_eq!(2, state2.load(Ordering::Relaxed));
4005 });
4006
4007 thread::sleep(std::time::Duration::from_millis(1000));
4008
4009 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4010
4011 // Return the handle from this scope so we can join with the
4012 // secondary thread after the key id lock has expired.
4013 handle
4014 // This is where the `_key_guard` goes out of scope,
4015 // which is the reason for concurrent load_key_entry on the same key
4016 // to unblock.
4017 };
4018 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4019 // main test thread. We will not see failing asserts in secondary threads otherwise.
4020 handle.join().unwrap();
4021 Ok(())
4022 }
4023
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004024 #[test]
Janis Danisevskis66784c42021-01-27 08:40:25 -08004025 fn teset_database_busy_error_code() {
4026 let temp_dir =
4027 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4028
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004029 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4030 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004031
4032 let _tx1 = db1
4033 .conn
4034 .transaction_with_behavior(TransactionBehavior::Immediate)
4035 .expect("Failed to create first transaction.");
4036
4037 let error = db2
4038 .conn
4039 .transaction_with_behavior(TransactionBehavior::Immediate)
4040 .context("Transaction begin failed.")
4041 .expect_err("This should fail.");
4042 let root_cause = error.root_cause();
4043 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4044 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4045 {
4046 return;
4047 }
4048 panic!(
4049 "Unexpected error {:?} \n{:?} \n{:?}",
4050 error,
4051 root_cause,
4052 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4053 )
4054 }
4055
4056 #[cfg(disabled)]
4057 #[test]
4058 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4059 let temp_dir = Arc::new(
4060 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4061 .expect("Failed to create temp dir."),
4062 );
4063
4064 let test_begin = Instant::now();
4065
4066 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4067 const KEY_COUNT: u32 = 500u32;
4068 const OPEN_DB_COUNT: u32 = 50u32;
4069
4070 let mut actual_key_count = KEY_COUNT;
4071 // First insert KEY_COUNT keys.
4072 for count in 0..KEY_COUNT {
4073 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4074 actual_key_count = count;
4075 break;
4076 }
4077 let alias = format!("test_alias_{}", count);
4078 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4079 .expect("Failed to make key entry.");
4080 }
4081
4082 // Insert more keys from a different thread and into a different namespace.
4083 let temp_dir1 = temp_dir.clone();
4084 let handle1 = thread::spawn(move || {
4085 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4086
4087 for count in 0..actual_key_count {
4088 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4089 return;
4090 }
4091 let alias = format!("test_alias_{}", count);
4092 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4093 .expect("Failed to make key entry.");
4094 }
4095
4096 // then unbind them again.
4097 for count in 0..actual_key_count {
4098 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4099 return;
4100 }
4101 let key = KeyDescriptor {
4102 domain: Domain::APP,
4103 nspace: -1,
4104 alias: Some(format!("test_alias_{}", count)),
4105 blob: None,
4106 };
4107 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4108 }
4109 });
4110
4111 // And start unbinding the first set of keys.
4112 let temp_dir2 = temp_dir.clone();
4113 let handle2 = thread::spawn(move || {
4114 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4115
4116 for count in 0..actual_key_count {
4117 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4118 return;
4119 }
4120 let key = KeyDescriptor {
4121 domain: Domain::APP,
4122 nspace: -1,
4123 alias: Some(format!("test_alias_{}", count)),
4124 blob: None,
4125 };
4126 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4127 }
4128 });
4129
4130 let stop_deleting = Arc::new(AtomicU8::new(0));
4131 let stop_deleting2 = stop_deleting.clone();
4132
4133 // And delete anything that is unreferenced keys.
4134 let temp_dir3 = temp_dir.clone();
4135 let handle3 = thread::spawn(move || {
4136 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4137
4138 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4139 while let Some((key_guard, _key)) =
4140 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4141 {
4142 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4143 return;
4144 }
4145 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4146 }
4147 std::thread::sleep(std::time::Duration::from_millis(100));
4148 }
4149 });
4150
4151 // While a lot of inserting and deleting is going on we have to open database connections
4152 // successfully and use them.
4153 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4154 // out of scope.
4155 #[allow(clippy::redundant_clone)]
4156 let temp_dir4 = temp_dir.clone();
4157 let handle4 = thread::spawn(move || {
4158 for count in 0..OPEN_DB_COUNT {
4159 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4160 return;
4161 }
4162 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4163
4164 let alias = format!("test_alias_{}", count);
4165 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4166 .expect("Failed to make key entry.");
4167 let key = KeyDescriptor {
4168 domain: Domain::APP,
4169 nspace: -1,
4170 alias: Some(alias),
4171 blob: None,
4172 };
4173 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4174 }
4175 });
4176
4177 handle1.join().expect("Thread 1 panicked.");
4178 handle2.join().expect("Thread 2 panicked.");
4179 handle4.join().expect("Thread 4 panicked.");
4180
4181 stop_deleting.store(1, Ordering::Relaxed);
4182 handle3.join().expect("Thread 3 panicked.");
4183
4184 Ok(())
4185 }
4186
4187 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004188 fn list() -> Result<()> {
4189 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004190 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004191 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4192 (Domain::APP, 1, "test1"),
4193 (Domain::APP, 1, "test2"),
4194 (Domain::APP, 1, "test3"),
4195 (Domain::APP, 1, "test4"),
4196 (Domain::APP, 1, "test5"),
4197 (Domain::APP, 1, "test6"),
4198 (Domain::APP, 1, "test7"),
4199 (Domain::APP, 2, "test1"),
4200 (Domain::APP, 2, "test2"),
4201 (Domain::APP, 2, "test3"),
4202 (Domain::APP, 2, "test4"),
4203 (Domain::APP, 2, "test5"),
4204 (Domain::APP, 2, "test6"),
4205 (Domain::APP, 2, "test8"),
4206 (Domain::SELINUX, 100, "test1"),
4207 (Domain::SELINUX, 100, "test2"),
4208 (Domain::SELINUX, 100, "test3"),
4209 (Domain::SELINUX, 100, "test4"),
4210 (Domain::SELINUX, 100, "test5"),
4211 (Domain::SELINUX, 100, "test6"),
4212 (Domain::SELINUX, 100, "test9"),
4213 ];
4214
4215 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4216 .iter()
4217 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004218 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4219 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004220 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4221 });
4222 (entry.id(), *ns)
4223 })
4224 .collect();
4225
4226 for (domain, namespace) in
4227 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4228 {
4229 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4230 .iter()
4231 .filter_map(|(domain, ns, alias)| match ns {
4232 ns if *ns == *namespace => Some(KeyDescriptor {
4233 domain: *domain,
4234 nspace: *ns,
4235 alias: Some(alias.to_string()),
4236 blob: None,
4237 }),
4238 _ => None,
4239 })
4240 .collect();
4241 list_o_descriptors.sort();
4242 let mut list_result = db.list(*domain, *namespace)?;
4243 list_result.sort();
4244 assert_eq!(list_o_descriptors, list_result);
4245
4246 let mut list_o_ids: Vec<i64> = list_o_descriptors
4247 .into_iter()
4248 .map(|d| {
4249 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004250 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004251 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004252 KeyType::Client,
4253 KeyEntryLoadBits::NONE,
4254 *namespace as u32,
4255 |_, _| Ok(()),
4256 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004257 .unwrap();
4258 entry.id()
4259 })
4260 .collect();
4261 list_o_ids.sort_unstable();
4262 let mut loaded_entries: Vec<i64> = list_o_keys
4263 .iter()
4264 .filter_map(|(id, ns)| match ns {
4265 ns if *ns == *namespace => Some(*id),
4266 _ => None,
4267 })
4268 .collect();
4269 loaded_entries.sort_unstable();
4270 assert_eq!(list_o_ids, loaded_entries);
4271 }
4272 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4273
4274 Ok(())
4275 }
4276
Joel Galenson0891bc12020-07-20 10:37:03 -07004277 // Helpers
4278
4279 // Checks that the given result is an error containing the given string.
4280 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4281 let error_str = format!(
4282 "{:#?}",
4283 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4284 );
4285 assert!(
4286 error_str.contains(target),
4287 "The string \"{}\" should contain \"{}\"",
4288 error_str,
4289 target
4290 );
4291 }
4292
Joel Galenson2aab4432020-07-22 15:27:57 -07004293 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004294 #[allow(dead_code)]
4295 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004296 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004297 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004298 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004299 namespace: Option<i64>,
4300 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004301 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004302 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004303 }
4304
4305 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4306 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004307 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004308 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004309 Ok(KeyEntryRow {
4310 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004311 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004312 domain: match row.get(2)? {
4313 Some(i) => Some(Domain(i)),
4314 None => None,
4315 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004316 namespace: row.get(3)?,
4317 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004318 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004319 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004320 })
4321 })?
4322 .map(|r| r.context("Could not read keyentry row."))
4323 .collect::<Result<Vec<_>>>()
4324 }
4325
Max Bires2b2e6562020-09-22 11:22:36 -07004326 fn load_attestation_key_pool(
4327 db: &mut KeystoreDB,
4328 expiration_date: i64,
4329 namespace: i64,
4330 base_byte: u8,
4331 ) -> Result<Vec<Vec<u8>>> {
4332 let mut chain: Vec<Vec<u8>> = Vec::new();
4333 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4334 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4335 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4336 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
4337 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4338 db.store_signed_attestation_certificate_chain(
4339 &raw_public_key,
4340 &cert_chain,
4341 expiration_date,
4342 &KEYSTORE_UUID,
4343 )?;
4344 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
4345 chain.push(public_key);
4346 chain.push(cert_chain);
4347 chain.push(priv_key);
4348 chain.push(raw_public_key);
4349 Ok(chain)
4350 }
4351
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004352 // Note: The parameters and SecurityLevel associations are nonsensical. This
4353 // collection is only used to check if the parameters are preserved as expected by the
4354 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004355 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4356 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004357 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4358 KeyParameter::new(
4359 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4360 SecurityLevel::TRUSTED_ENVIRONMENT,
4361 ),
4362 KeyParameter::new(
4363 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4364 SecurityLevel::TRUSTED_ENVIRONMENT,
4365 ),
4366 KeyParameter::new(
4367 KeyParameterValue::Algorithm(Algorithm::RSA),
4368 SecurityLevel::TRUSTED_ENVIRONMENT,
4369 ),
4370 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4371 KeyParameter::new(
4372 KeyParameterValue::BlockMode(BlockMode::ECB),
4373 SecurityLevel::TRUSTED_ENVIRONMENT,
4374 ),
4375 KeyParameter::new(
4376 KeyParameterValue::BlockMode(BlockMode::GCM),
4377 SecurityLevel::TRUSTED_ENVIRONMENT,
4378 ),
4379 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4380 KeyParameter::new(
4381 KeyParameterValue::Digest(Digest::MD5),
4382 SecurityLevel::TRUSTED_ENVIRONMENT,
4383 ),
4384 KeyParameter::new(
4385 KeyParameterValue::Digest(Digest::SHA_2_224),
4386 SecurityLevel::TRUSTED_ENVIRONMENT,
4387 ),
4388 KeyParameter::new(
4389 KeyParameterValue::Digest(Digest::SHA_2_256),
4390 SecurityLevel::STRONGBOX,
4391 ),
4392 KeyParameter::new(
4393 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4394 SecurityLevel::TRUSTED_ENVIRONMENT,
4395 ),
4396 KeyParameter::new(
4397 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4398 SecurityLevel::TRUSTED_ENVIRONMENT,
4399 ),
4400 KeyParameter::new(
4401 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4402 SecurityLevel::STRONGBOX,
4403 ),
4404 KeyParameter::new(
4405 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4406 SecurityLevel::TRUSTED_ENVIRONMENT,
4407 ),
4408 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4409 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4410 KeyParameter::new(
4411 KeyParameterValue::EcCurve(EcCurve::P_224),
4412 SecurityLevel::TRUSTED_ENVIRONMENT,
4413 ),
4414 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4415 KeyParameter::new(
4416 KeyParameterValue::EcCurve(EcCurve::P_384),
4417 SecurityLevel::TRUSTED_ENVIRONMENT,
4418 ),
4419 KeyParameter::new(
4420 KeyParameterValue::EcCurve(EcCurve::P_521),
4421 SecurityLevel::TRUSTED_ENVIRONMENT,
4422 ),
4423 KeyParameter::new(
4424 KeyParameterValue::RSAPublicExponent(3),
4425 SecurityLevel::TRUSTED_ENVIRONMENT,
4426 ),
4427 KeyParameter::new(
4428 KeyParameterValue::IncludeUniqueID,
4429 SecurityLevel::TRUSTED_ENVIRONMENT,
4430 ),
4431 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4432 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4433 KeyParameter::new(
4434 KeyParameterValue::ActiveDateTime(1234567890),
4435 SecurityLevel::STRONGBOX,
4436 ),
4437 KeyParameter::new(
4438 KeyParameterValue::OriginationExpireDateTime(1234567890),
4439 SecurityLevel::TRUSTED_ENVIRONMENT,
4440 ),
4441 KeyParameter::new(
4442 KeyParameterValue::UsageExpireDateTime(1234567890),
4443 SecurityLevel::TRUSTED_ENVIRONMENT,
4444 ),
4445 KeyParameter::new(
4446 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4447 SecurityLevel::TRUSTED_ENVIRONMENT,
4448 ),
4449 KeyParameter::new(
4450 KeyParameterValue::MaxUsesPerBoot(1234567890),
4451 SecurityLevel::TRUSTED_ENVIRONMENT,
4452 ),
4453 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4454 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4455 KeyParameter::new(
4456 KeyParameterValue::NoAuthRequired,
4457 SecurityLevel::TRUSTED_ENVIRONMENT,
4458 ),
4459 KeyParameter::new(
4460 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4461 SecurityLevel::TRUSTED_ENVIRONMENT,
4462 ),
4463 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4464 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4465 KeyParameter::new(
4466 KeyParameterValue::TrustedUserPresenceRequired,
4467 SecurityLevel::TRUSTED_ENVIRONMENT,
4468 ),
4469 KeyParameter::new(
4470 KeyParameterValue::TrustedConfirmationRequired,
4471 SecurityLevel::TRUSTED_ENVIRONMENT,
4472 ),
4473 KeyParameter::new(
4474 KeyParameterValue::UnlockedDeviceRequired,
4475 SecurityLevel::TRUSTED_ENVIRONMENT,
4476 ),
4477 KeyParameter::new(
4478 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4479 SecurityLevel::SOFTWARE,
4480 ),
4481 KeyParameter::new(
4482 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4483 SecurityLevel::SOFTWARE,
4484 ),
4485 KeyParameter::new(
4486 KeyParameterValue::CreationDateTime(12345677890),
4487 SecurityLevel::SOFTWARE,
4488 ),
4489 KeyParameter::new(
4490 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4491 SecurityLevel::TRUSTED_ENVIRONMENT,
4492 ),
4493 KeyParameter::new(
4494 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4495 SecurityLevel::TRUSTED_ENVIRONMENT,
4496 ),
4497 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4498 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4499 KeyParameter::new(
4500 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4501 SecurityLevel::SOFTWARE,
4502 ),
4503 KeyParameter::new(
4504 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4505 SecurityLevel::TRUSTED_ENVIRONMENT,
4506 ),
4507 KeyParameter::new(
4508 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4509 SecurityLevel::TRUSTED_ENVIRONMENT,
4510 ),
4511 KeyParameter::new(
4512 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4513 SecurityLevel::TRUSTED_ENVIRONMENT,
4514 ),
4515 KeyParameter::new(
4516 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4517 SecurityLevel::TRUSTED_ENVIRONMENT,
4518 ),
4519 KeyParameter::new(
4520 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4521 SecurityLevel::TRUSTED_ENVIRONMENT,
4522 ),
4523 KeyParameter::new(
4524 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4525 SecurityLevel::TRUSTED_ENVIRONMENT,
4526 ),
4527 KeyParameter::new(
4528 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4529 SecurityLevel::TRUSTED_ENVIRONMENT,
4530 ),
4531 KeyParameter::new(
4532 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4533 SecurityLevel::TRUSTED_ENVIRONMENT,
4534 ),
4535 KeyParameter::new(
4536 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4537 SecurityLevel::TRUSTED_ENVIRONMENT,
4538 ),
4539 KeyParameter::new(
4540 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4541 SecurityLevel::TRUSTED_ENVIRONMENT,
4542 ),
4543 KeyParameter::new(
4544 KeyParameterValue::VendorPatchLevel(3),
4545 SecurityLevel::TRUSTED_ENVIRONMENT,
4546 ),
4547 KeyParameter::new(
4548 KeyParameterValue::BootPatchLevel(4),
4549 SecurityLevel::TRUSTED_ENVIRONMENT,
4550 ),
4551 KeyParameter::new(
4552 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4553 SecurityLevel::TRUSTED_ENVIRONMENT,
4554 ),
4555 KeyParameter::new(
4556 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4557 SecurityLevel::TRUSTED_ENVIRONMENT,
4558 ),
4559 KeyParameter::new(
4560 KeyParameterValue::MacLength(256),
4561 SecurityLevel::TRUSTED_ENVIRONMENT,
4562 ),
4563 KeyParameter::new(
4564 KeyParameterValue::ResetSinceIdRotation,
4565 SecurityLevel::TRUSTED_ENVIRONMENT,
4566 ),
4567 KeyParameter::new(
4568 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4569 SecurityLevel::TRUSTED_ENVIRONMENT,
4570 ),
Qi Wub9433b52020-12-01 14:52:46 +08004571 ];
4572 if let Some(value) = max_usage_count {
4573 params.push(KeyParameter::new(
4574 KeyParameterValue::UsageCountLimit(value),
4575 SecurityLevel::SOFTWARE,
4576 ));
4577 }
4578 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004579 }
4580
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004581 fn make_test_key_entry(
4582 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004583 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004584 namespace: i64,
4585 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004586 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004587 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004588 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004589 let mut blob_metadata = BlobMetaData::new();
4590 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4591 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4592 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4593 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4594 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4595
4596 db.set_blob(
4597 &key_id,
4598 SubComponentType::KEY_BLOB,
4599 Some(TEST_KEY_BLOB),
4600 Some(&blob_metadata),
4601 )?;
4602 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4603 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004604
4605 let params = make_test_params(max_usage_count);
4606 db.insert_keyparameter(&key_id, &params)?;
4607
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004608 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004609 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004610 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004611 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004612 Ok(key_id)
4613 }
4614
Qi Wub9433b52020-12-01 14:52:46 +08004615 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4616 let params = make_test_params(max_usage_count);
4617
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004618 let mut blob_metadata = BlobMetaData::new();
4619 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4620 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4621 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4622 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4623 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4624
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004625 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004626 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004627
4628 KeyEntry {
4629 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004630 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004631 cert: Some(TEST_CERT_BLOB.to_vec()),
4632 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004633 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004634 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004635 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004636 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004637 }
4638 }
4639
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004640 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004641 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004642 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004643 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004644 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004645 NO_PARAMS,
4646 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004647 Ok((
4648 row.get(0)?,
4649 row.get(1)?,
4650 row.get(2)?,
4651 row.get(3)?,
4652 row.get(4)?,
4653 row.get(5)?,
4654 row.get(6)?,
4655 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004656 },
4657 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004658
4659 println!("Key entry table rows:");
4660 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004661 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004662 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004663 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4664 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004665 );
4666 }
4667 Ok(())
4668 }
4669
4670 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004671 let mut stmt = db
4672 .conn
4673 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004674 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
4675 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
4676 })?;
4677
4678 println!("Grant table rows:");
4679 for r in rows {
4680 let (id, gt, ki, av) = r.unwrap();
4681 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
4682 }
4683 Ok(())
4684 }
4685
Joel Galenson0891bc12020-07-20 10:37:03 -07004686 // Use a custom random number generator that repeats each number once.
4687 // This allows us to test repeated elements.
4688
4689 thread_local! {
4690 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
4691 }
4692
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004693 fn reset_random() {
4694 RANDOM_COUNTER.with(|counter| {
4695 *counter.borrow_mut() = 0;
4696 })
4697 }
4698
Joel Galenson0891bc12020-07-20 10:37:03 -07004699 pub fn random() -> i64 {
4700 RANDOM_COUNTER.with(|counter| {
4701 let result = *counter.borrow() / 2;
4702 *counter.borrow_mut() += 1;
4703 result
4704 })
4705 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004706
4707 #[test]
4708 fn test_last_off_body() -> Result<()> {
4709 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08004710 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004711 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
4712 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
4713 tx.commit()?;
4714 let one_second = Duration::from_secs(1);
4715 thread::sleep(one_second);
4716 db.update_last_off_body(MonotonicRawTime::now())?;
4717 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
4718 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
4719 tx2.commit()?;
4720 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
4721 Ok(())
4722 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00004723
4724 #[test]
4725 fn test_unbind_keys_for_user() -> Result<()> {
4726 let mut db = new_test_db()?;
4727 db.unbind_keys_for_user(1, false)?;
4728
4729 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
4730 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
4731 db.unbind_keys_for_user(2, false)?;
4732
4733 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
4734 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
4735
4736 db.unbind_keys_for_user(1, true)?;
4737 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
4738
4739 Ok(())
4740 }
4741
4742 #[test]
4743 fn test_store_super_key() -> Result<()> {
4744 let mut db = new_test_db()?;
4745 let pw = "xyzabc".as_bytes();
4746 let super_key = keystore2_crypto::generate_aes256_key()?;
4747 let secret = String::from("keystore2 is great.");
4748 let secret_bytes = secret.into_bytes();
4749 let (encrypted_secret, iv, tag) =
4750 keystore2_crypto::aes_gcm_encrypt(&secret_bytes, &super_key)?;
4751
4752 let (encrypted_super_key, metadata) =
4753 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
4754 db.store_super_key(1, &(&encrypted_super_key, &metadata))?;
4755
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00004756 //check if super key exists
4757 assert!(db.key_exists(Domain::APP, 1, "USER_SUPER_KEY", KeyType::Super)?);
4758
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00004759 let (_, key_entry) = db.load_super_key(1)?.unwrap();
Hasini Gunasingheda895552021-01-27 19:34:37 +00004760 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(key_entry, &pw)?;
4761
4762 let decrypted_secret_bytes = keystore2_crypto::aes_gcm_decrypt(
4763 &encrypted_secret,
4764 &iv,
4765 &tag,
4766 &loaded_super_key.get_key(),
4767 )?;
4768 let decrypted_secret = String::from_utf8((&decrypted_secret_bytes).to_vec())?;
4769 assert_eq!(String::from("keystore2 is great."), decrypted_secret);
4770 Ok(())
4771 }
Joel Galenson26f4d012020-07-17 14:57:21 -07004772}