blob: db06bff51b46d826fcb6e468b3447026298d74ab [file] [log] [blame]
Joel Galenson26f4d012020-07-17 14:57:21 -07001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070015//! This is the Keystore 2.0 database module.
16//! The database module provides a connection to the backing SQLite store.
17//! We have two databases one for persistent key blob storage and one for
18//! items that have a per boot life cycle.
19//!
20//! ## Persistent database
21//! The persistent database has tables for key blobs. They are organized
22//! as follows:
23//! The `keyentry` table is the primary table for key entries. It is
24//! accompanied by two tables for blobs and parameters.
25//! Each key entry occupies exactly one row in the `keyentry` table and
26//! zero or more rows in the tables `blobentry` and `keyparameter`.
27//!
28//! ## Per boot database
29//! The per boot database stores items with a per boot lifecycle.
30//! Currently, there is only the `grant` table in this database.
31//! Grants are references to a key that can be used to access a key by
32//! clients that don't own that key. Grants can only be created by the
33//! owner of a key. And only certain components can create grants.
34//! This is governed by SEPolicy.
35//!
36//! ## Access control
37//! Some database functions that load keys or create grants perform
38//! access control. This is because in some cases access control
39//! can only be performed after some information about the designated
40//! key was loaded from the database. To decouple the permission checks
41//! from the database module these functions take permission check
42//! callbacks.
Joel Galenson26f4d012020-07-17 14:57:21 -070043
Qi Wub9433b52020-12-01 14:52:46 +080044use crate::error::{Error as KsError, ErrorCode, ResponseCode};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080045use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080046use crate::key_parameter::{KeyParameter, Tag};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070047use crate::permission::KeyPermSet;
Hasini Gunasingheda895552021-01-27 19:34:37 +000048use crate::utils::{get_current_time_in_seconds, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080049use crate::{
50 db_utils::{self, SqlField},
51 gc::Gc,
52};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080053use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080054use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis60400fe2020-08-26 15:24:42 -070055
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000056use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080057 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000058 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080059};
60use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000061 Timestamp::Timestamp,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000062};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070063use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070064 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070065};
Max Bires2b2e6562020-09-22 11:22:36 -070066use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
67 AttestationPoolStatus::AttestationPoolStatus,
68};
69
70use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080071use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000072use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070073#[cfg(not(test))]
74use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070075use rusqlite::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080076 params,
77 types::FromSql,
78 types::FromSqlResult,
79 types::ToSqlOutput,
80 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080081 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070082};
Max Bires2b2e6562020-09-22 11:22:36 -070083
Janis Danisevskisaec14592020-11-12 09:41:49 -080084use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080085 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080086 path::Path,
87 sync::{Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080088 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080089};
Max Bires2b2e6562020-09-22 11:22:36 -070090
Joel Galenson0891bc12020-07-20 10:37:03 -070091#[cfg(test)]
92use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070093
Janis Danisevskisb42fc182020-12-15 08:41:27 -080094impl_metadata!(
95 /// A set of metadata for key entries.
96 #[derive(Debug, Default, Eq, PartialEq)]
97 pub struct KeyMetaData;
98 /// A metadata entry for key entries.
99 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
100 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800101 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800102 CreationDate(DateTime) with accessor creation_date,
103 /// Expiration date for attestation keys.
104 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700105 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
106 /// provisioning
107 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
108 /// Vector representing the raw public key so results from the server can be matched
109 /// to the right entry
110 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800111 // --- ADD NEW META DATA FIELDS HERE ---
112 // For backwards compatibility add new entries only to
113 // end of this list and above this comment.
114 };
115);
116
117impl KeyMetaData {
118 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
119 let mut stmt = tx
120 .prepare(
121 "SELECT tag, data from persistent.keymetadata
122 WHERE keyentryid = ?;",
123 )
124 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
125
126 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
127
128 let mut rows =
129 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
130 db_utils::with_rows_extract_all(&mut rows, |row| {
131 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
132 metadata.insert(
133 db_tag,
134 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
135 .context("Failed to read KeyMetaEntry.")?,
136 );
137 Ok(())
138 })
139 .context("In KeyMetaData::load_from_db.")?;
140
141 Ok(Self { data: metadata })
142 }
143
144 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
145 let mut stmt = tx
146 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000147 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800148 VALUES (?, ?, ?);",
149 )
150 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
151
152 let iter = self.data.iter();
153 for (tag, entry) in iter {
154 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
155 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
156 })?;
157 }
158 Ok(())
159 }
160}
161
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800162impl_metadata!(
163 /// A set of metadata for key blobs.
164 #[derive(Debug, Default, Eq, PartialEq)]
165 pub struct BlobMetaData;
166 /// A metadata entry for key blobs.
167 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
168 pub enum BlobMetaEntry {
169 /// If present, indicates that the blob is encrypted with another key or a key derived
170 /// from a password.
171 EncryptedBy(EncryptedBy) with accessor encrypted_by,
172 /// If the blob is password encrypted this field is set to the
173 /// salt used for the key derivation.
174 Salt(Vec<u8>) with accessor salt,
175 /// If the blob is encrypted, this field is set to the initialization vector.
176 Iv(Vec<u8>) with accessor iv,
177 /// If the blob is encrypted, this field holds the AEAD TAG.
178 AeadTag(Vec<u8>) with accessor aead_tag,
179 /// The uuid of the owning KeyMint instance.
180 KmUuid(Uuid) with accessor km_uuid,
181 // --- ADD NEW META DATA FIELDS HERE ---
182 // For backwards compatibility add new entries only to
183 // end of this list and above this comment.
184 };
185);
186
187impl BlobMetaData {
188 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
189 let mut stmt = tx
190 .prepare(
191 "SELECT tag, data from persistent.blobmetadata
192 WHERE blobentryid = ?;",
193 )
194 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
195
196 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
197
198 let mut rows =
199 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
200 db_utils::with_rows_extract_all(&mut rows, |row| {
201 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
202 metadata.insert(
203 db_tag,
204 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
205 .context("Failed to read BlobMetaEntry.")?,
206 );
207 Ok(())
208 })
209 .context("In BlobMetaData::load_from_db.")?;
210
211 Ok(Self { data: metadata })
212 }
213
214 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
215 let mut stmt = tx
216 .prepare(
217 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
218 VALUES (?, ?, ?);",
219 )
220 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
221
222 let iter = self.data.iter();
223 for (tag, entry) in iter {
224 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
225 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
226 })?;
227 }
228 Ok(())
229 }
230}
231
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800232/// Indicates the type of the keyentry.
233#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
234pub enum KeyType {
235 /// This is a client key type. These keys are created or imported through the Keystore 2.0
236 /// AIDL interface android.system.keystore2.
237 Client,
238 /// This is a super key type. These keys are created by keystore itself and used to encrypt
239 /// other key blobs to provide LSKF binding.
240 Super,
241 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
242 Attestation,
243}
244
245impl ToSql for KeyType {
246 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
247 Ok(ToSqlOutput::Owned(Value::Integer(match self {
248 KeyType::Client => 0,
249 KeyType::Super => 1,
250 KeyType::Attestation => 2,
251 })))
252 }
253}
254
255impl FromSql for KeyType {
256 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
257 match i64::column_result(value)? {
258 0 => Ok(KeyType::Client),
259 1 => Ok(KeyType::Super),
260 2 => Ok(KeyType::Attestation),
261 v => Err(FromSqlError::OutOfRange(v)),
262 }
263 }
264}
265
Max Bires8e93d2b2021-01-14 13:17:59 -0800266/// Uuid representation that can be stored in the database.
267/// Right now it can only be initialized from SecurityLevel.
268/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
269#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
270pub struct Uuid([u8; 16]);
271
272impl Deref for Uuid {
273 type Target = [u8; 16];
274
275 fn deref(&self) -> &Self::Target {
276 &self.0
277 }
278}
279
280impl From<SecurityLevel> for Uuid {
281 fn from(sec_level: SecurityLevel) -> Self {
282 Self((sec_level.0 as u128).to_be_bytes())
283 }
284}
285
286impl ToSql for Uuid {
287 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
288 self.0.to_sql()
289 }
290}
291
292impl FromSql for Uuid {
293 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
294 let blob = Vec::<u8>::column_result(value)?;
295 if blob.len() != 16 {
296 return Err(FromSqlError::OutOfRange(blob.len() as i64));
297 }
298 let mut arr = [0u8; 16];
299 arr.copy_from_slice(&blob);
300 Ok(Self(arr))
301 }
302}
303
304/// Key entries that are not associated with any KeyMint instance, such as pure certificate
305/// entries are associated with this UUID.
306pub static KEYSTORE_UUID: Uuid = Uuid([
307 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
308]);
309
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800310/// Indicates how the sensitive part of this key blob is encrypted.
311#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
312pub enum EncryptedBy {
313 /// The keyblob is encrypted by a user password.
314 /// In the database this variant is represented as NULL.
315 Password,
316 /// The keyblob is encrypted by another key with wrapped key id.
317 /// In the database this variant is represented as non NULL value
318 /// that is convertible to i64, typically NUMERIC.
319 KeyId(i64),
320}
321
322impl ToSql for EncryptedBy {
323 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
324 match self {
325 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
326 Self::KeyId(id) => id.to_sql(),
327 }
328 }
329}
330
331impl FromSql for EncryptedBy {
332 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
333 match value {
334 ValueRef::Null => Ok(Self::Password),
335 _ => Ok(Self::KeyId(i64::column_result(value)?)),
336 }
337 }
338}
339
340/// A database representation of wall clock time. DateTime stores unix epoch time as
341/// i64 in milliseconds.
342#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
343pub struct DateTime(i64);
344
345/// Error type returned when creating DateTime or converting it from and to
346/// SystemTime.
347#[derive(thiserror::Error, Debug)]
348pub enum DateTimeError {
349 /// This is returned when SystemTime and Duration computations fail.
350 #[error(transparent)]
351 SystemTimeError(#[from] SystemTimeError),
352
353 /// This is returned when type conversions fail.
354 #[error(transparent)]
355 TypeConversion(#[from] std::num::TryFromIntError),
356
357 /// This is returned when checked time arithmetic failed.
358 #[error("Time arithmetic failed.")]
359 TimeArithmetic,
360}
361
362impl DateTime {
363 /// Constructs a new DateTime object denoting the current time. This may fail during
364 /// conversion to unix epoch time and during conversion to the internal i64 representation.
365 pub fn now() -> Result<Self, DateTimeError> {
366 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
367 }
368
369 /// Constructs a new DateTime object from milliseconds.
370 pub fn from_millis_epoch(millis: i64) -> Self {
371 Self(millis)
372 }
373
374 /// Returns unix epoch time in milliseconds.
375 pub fn to_millis_epoch(&self) -> i64 {
376 self.0
377 }
378
379 /// Returns unix epoch time in seconds.
380 pub fn to_secs_epoch(&self) -> i64 {
381 self.0 / 1000
382 }
383}
384
385impl ToSql for DateTime {
386 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
387 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
388 }
389}
390
391impl FromSql for DateTime {
392 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
393 Ok(Self(i64::column_result(value)?))
394 }
395}
396
397impl TryInto<SystemTime> for DateTime {
398 type Error = DateTimeError;
399
400 fn try_into(self) -> Result<SystemTime, Self::Error> {
401 // We want to construct a SystemTime representation equivalent to self, denoting
402 // a point in time THEN, but we cannot set the time directly. We can only construct
403 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
404 // and between EPOCH and THEN. With this common reference we can construct the
405 // duration between NOW and THEN which we can add to our SystemTime representation
406 // of NOW to get a SystemTime representation of THEN.
407 // Durations can only be positive, thus the if statement below.
408 let now = SystemTime::now();
409 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
410 let then_epoch = Duration::from_millis(self.0.try_into()?);
411 Ok(if now_epoch > then_epoch {
412 // then = now - (now_epoch - then_epoch)
413 now_epoch
414 .checked_sub(then_epoch)
415 .and_then(|d| now.checked_sub(d))
416 .ok_or(DateTimeError::TimeArithmetic)?
417 } else {
418 // then = now + (then_epoch - now_epoch)
419 then_epoch
420 .checked_sub(now_epoch)
421 .and_then(|d| now.checked_add(d))
422 .ok_or(DateTimeError::TimeArithmetic)?
423 })
424 }
425}
426
427impl TryFrom<SystemTime> for DateTime {
428 type Error = DateTimeError;
429
430 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
431 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
432 }
433}
434
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800435#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
436enum KeyLifeCycle {
437 /// Existing keys have a key ID but are not fully populated yet.
438 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
439 /// them to Unreferenced for garbage collection.
440 Existing,
441 /// A live key is fully populated and usable by clients.
442 Live,
443 /// An unreferenced key is scheduled for garbage collection.
444 Unreferenced,
445}
446
447impl ToSql for KeyLifeCycle {
448 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
449 match self {
450 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
451 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
452 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
453 }
454 }
455}
456
457impl FromSql for KeyLifeCycle {
458 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
459 match i64::column_result(value)? {
460 0 => Ok(KeyLifeCycle::Existing),
461 1 => Ok(KeyLifeCycle::Live),
462 2 => Ok(KeyLifeCycle::Unreferenced),
463 v => Err(FromSqlError::OutOfRange(v)),
464 }
465 }
466}
467
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700468/// Keys have a KeyMint blob component and optional public certificate and
469/// certificate chain components.
470/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
471/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800472#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700473pub struct KeyEntryLoadBits(u32);
474
475impl KeyEntryLoadBits {
476 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
477 pub const NONE: KeyEntryLoadBits = Self(0);
478 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
479 pub const KM: KeyEntryLoadBits = Self(1);
480 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
481 pub const PUBLIC: KeyEntryLoadBits = Self(2);
482 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
483 pub const BOTH: KeyEntryLoadBits = Self(3);
484
485 /// Returns true if this object indicates that the public components shall be loaded.
486 pub const fn load_public(&self) -> bool {
487 self.0 & Self::PUBLIC.0 != 0
488 }
489
490 /// Returns true if the object indicates that the KeyMint component shall be loaded.
491 pub const fn load_km(&self) -> bool {
492 self.0 & Self::KM.0 != 0
493 }
494}
495
Janis Danisevskisaec14592020-11-12 09:41:49 -0800496lazy_static! {
497 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
498}
499
500struct KeyIdLockDb {
501 locked_keys: Mutex<HashSet<i64>>,
502 cond_var: Condvar,
503}
504
505/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
506/// from the database a second time. Most functions manipulating the key blob database
507/// require a KeyIdGuard.
508#[derive(Debug)]
509pub struct KeyIdGuard(i64);
510
511impl KeyIdLockDb {
512 fn new() -> Self {
513 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
514 }
515
516 /// This function blocks until an exclusive lock for the given key entry id can
517 /// be acquired. It returns a guard object, that represents the lifecycle of the
518 /// acquired lock.
519 pub fn get(&self, key_id: i64) -> KeyIdGuard {
520 let mut locked_keys = self.locked_keys.lock().unwrap();
521 while locked_keys.contains(&key_id) {
522 locked_keys = self.cond_var.wait(locked_keys).unwrap();
523 }
524 locked_keys.insert(key_id);
525 KeyIdGuard(key_id)
526 }
527
528 /// This function attempts to acquire an exclusive lock on a given key id. If the
529 /// given key id is already taken the function returns None immediately. If a lock
530 /// can be acquired this function returns a guard object, that represents the
531 /// lifecycle of the acquired lock.
532 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
533 let mut locked_keys = self.locked_keys.lock().unwrap();
534 if locked_keys.insert(key_id) {
535 Some(KeyIdGuard(key_id))
536 } else {
537 None
538 }
539 }
540}
541
542impl KeyIdGuard {
543 /// Get the numeric key id of the locked key.
544 pub fn id(&self) -> i64 {
545 self.0
546 }
547}
548
549impl Drop for KeyIdGuard {
550 fn drop(&mut self) {
551 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
552 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800553 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800554 KEY_ID_LOCK.cond_var.notify_all();
555 }
556}
557
Max Bires8e93d2b2021-01-14 13:17:59 -0800558/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700559#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800560pub struct CertificateInfo {
561 cert: Option<Vec<u8>>,
562 cert_chain: Option<Vec<u8>>,
563}
564
565impl CertificateInfo {
566 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
567 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
568 Self { cert, cert_chain }
569 }
570
571 /// Take the cert
572 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
573 self.cert.take()
574 }
575
576 /// Take the cert chain
577 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
578 self.cert_chain.take()
579 }
580}
581
Max Bires2b2e6562020-09-22 11:22:36 -0700582/// This type represents a certificate chain with a private key corresponding to the leaf
583/// certificate. TODO(jbires): This will be used in a follow-on CL, for now it's used in the tests.
584#[allow(dead_code)]
585pub struct CertificateChain {
586 private_key: ZVec,
Max Biresb2e1d032021-02-08 21:35:05 -0800587 batch_cert: ZVec,
Max Bires2b2e6562020-09-22 11:22:36 -0700588 cert_chain: ZVec,
589}
590
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700591/// This type represents a Keystore 2.0 key entry.
592/// An entry has a unique `id` by which it can be found in the database.
593/// It has a security level field, key parameters, and three optional fields
594/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800595#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700596pub struct KeyEntry {
597 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800598 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700599 cert: Option<Vec<u8>>,
600 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800601 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700602 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800603 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800604 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700605}
606
607impl KeyEntry {
608 /// Returns the unique id of the Key entry.
609 pub fn id(&self) -> i64 {
610 self.id
611 }
612 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800613 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
614 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700615 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800616 /// Extracts the Optional KeyMint blob including its metadata.
617 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
618 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700619 }
620 /// Exposes the optional public certificate.
621 pub fn cert(&self) -> &Option<Vec<u8>> {
622 &self.cert
623 }
624 /// Extracts the optional public certificate.
625 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
626 self.cert.take()
627 }
628 /// Exposes the optional public certificate chain.
629 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
630 &self.cert_chain
631 }
632 /// Extracts the optional public certificate_chain.
633 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
634 self.cert_chain.take()
635 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800636 /// Returns the uuid of the owning KeyMint instance.
637 pub fn km_uuid(&self) -> &Uuid {
638 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700639 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700640 /// Exposes the key parameters of this key entry.
641 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
642 &self.parameters
643 }
644 /// Consumes this key entry and extracts the keyparameters from it.
645 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
646 self.parameters
647 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800648 /// Exposes the key metadata of this key entry.
649 pub fn metadata(&self) -> &KeyMetaData {
650 &self.metadata
651 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800652 /// This returns true if the entry is a pure certificate entry with no
653 /// private key component.
654 pub fn pure_cert(&self) -> bool {
655 self.pure_cert
656 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000657 /// Consumes this key entry and extracts the keyparameters and metadata from it.
658 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
659 (self.parameters, self.metadata)
660 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700661}
662
663/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800664#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700665pub struct SubComponentType(u32);
666impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800667 /// Persistent identifier for a key blob.
668 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700669 /// Persistent identifier for a certificate blob.
670 pub const CERT: SubComponentType = Self(1);
671 /// Persistent identifier for a certificate chain blob.
672 pub const CERT_CHAIN: SubComponentType = Self(2);
673}
674
675impl ToSql for SubComponentType {
676 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
677 self.0.to_sql()
678 }
679}
680
681impl FromSql for SubComponentType {
682 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
683 Ok(Self(u32::column_result(value)?))
684 }
685}
686
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800687/// This trait is private to the database module. It is used to convey whether or not the garbage
688/// collector shall be invoked after a database access. All closures passed to
689/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
690/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
691/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
692/// `.need_gc()`.
693trait DoGc<T> {
694 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
695
696 fn no_gc(self) -> Result<(bool, T)>;
697
698 fn need_gc(self) -> Result<(bool, T)>;
699}
700
701impl<T> DoGc<T> for Result<T> {
702 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
703 self.map(|r| (need_gc, r))
704 }
705
706 fn no_gc(self) -> Result<(bool, T)> {
707 self.do_gc(false)
708 }
709
710 fn need_gc(self) -> Result<(bool, T)> {
711 self.do_gc(true)
712 }
713}
714
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700715/// KeystoreDB wraps a connection to an SQLite database and tracks its
716/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700717pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700718 conn: Connection,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800719 gc: Option<Gc>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700720}
721
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000722/// Database representation of the monotonic time retrieved from the system call clock_gettime with
723/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds.
724#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
725pub struct MonotonicRawTime(i64);
726
727impl MonotonicRawTime {
728 /// Constructs a new MonotonicRawTime
729 pub fn now() -> Self {
730 Self(get_current_time_in_seconds())
731 }
732
733 /// Returns the integer value of MonotonicRawTime as i64
734 pub fn seconds(&self) -> i64 {
735 self.0
736 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800737
738 /// Like i64::checked_sub.
739 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
740 self.0.checked_sub(other.0).map(Self)
741 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000742}
743
744impl ToSql for MonotonicRawTime {
745 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
746 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
747 }
748}
749
750impl FromSql for MonotonicRawTime {
751 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
752 Ok(Self(i64::column_result(value)?))
753 }
754}
755
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000756/// This struct encapsulates the information to be stored in the database about the auth tokens
757/// received by keystore.
758pub struct AuthTokenEntry {
759 auth_token: HardwareAuthToken,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000760 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000761}
762
763impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000764 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000765 AuthTokenEntry { auth_token, time_received }
766 }
767
768 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800769 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000770 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800771 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
772 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000773 })
774 }
775
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000776 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800777 pub fn auth_token(&self) -> &HardwareAuthToken {
778 &self.auth_token
779 }
780
781 /// Returns the auth token wrapped by the AuthTokenEntry
782 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000783 self.auth_token
784 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800785
786 /// Returns the time that this auth token was received.
787 pub fn time_received(&self) -> MonotonicRawTime {
788 self.time_received
789 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000790}
791
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800792/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
793/// This object does not allow access to the database connection. But it keeps a database
794/// connection alive in order to keep the in memory per boot database alive.
795pub struct PerBootDbKeepAlive(Connection);
796
Joel Galenson26f4d012020-07-17 14:57:21 -0700797impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800798 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800799 const PERBOOT_DB_FILE_NAME: &'static str = &"file:perboot.sqlite?mode=memory&cache=shared";
800
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000801 /// The alias of the user super key.
802 pub const USER_SUPER_KEY_ALIAS: &'static str = &"USER_SUPER_KEY";
803
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800804 /// This creates a PerBootDbKeepAlive object to keep the per boot database alive.
805 pub fn keep_perboot_db_alive() -> Result<PerBootDbKeepAlive> {
806 let conn = Connection::open_in_memory()
807 .context("In keep_perboot_db_alive: Failed to initialize SQLite connection.")?;
808
809 conn.execute("ATTACH DATABASE ? as perboot;", params![Self::PERBOOT_DB_FILE_NAME])
810 .context("In keep_perboot_db_alive: Failed to attach database perboot.")?;
811 Ok(PerBootDbKeepAlive(conn))
812 }
813
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700814 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800815 /// files persistent.sqlite and perboot.sqlite in the given directory.
816 /// It also attempts to initialize all of the tables.
817 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700818 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800819 pub fn new(db_root: &Path, gc: Option<Gc>) -> Result<Self> {
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800820 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800821 let mut persistent_path = db_root.to_path_buf();
822 persistent_path.push("persistent.sqlite");
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700823
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800824 // Now convert them to strings prefixed with "file:"
825 let mut persistent_path_str = "file:".to_owned();
826 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800827
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800828 let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800829
Janis Danisevskis66784c42021-01-27 08:40:25 -0800830 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
831 conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?;
832
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800833 let mut db = Self { conn, gc };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800834 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800835 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800836 })?;
837 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700838 }
839
Janis Danisevskis66784c42021-01-27 08:40:25 -0800840 fn init_tables(tx: &Transaction) -> Result<()> {
841 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700842 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700843 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800844 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700845 domain INTEGER,
846 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800847 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800848 state INTEGER,
849 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700850 NO_PARAMS,
851 )
852 .context("Failed to initialize \"keyentry\" table.")?;
853
Janis Danisevskis66784c42021-01-27 08:40:25 -0800854 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800855 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
856 ON keyentry(id);",
857 NO_PARAMS,
858 )
859 .context("Failed to create index keyentry_id_index.")?;
860
861 tx.execute(
862 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
863 ON keyentry(domain, namespace, alias);",
864 NO_PARAMS,
865 )
866 .context("Failed to create index keyentry_domain_namespace_index.")?;
867
868 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700869 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
870 id INTEGER PRIMARY KEY,
871 subcomponent_type INTEGER,
872 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800873 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700874 NO_PARAMS,
875 )
876 .context("Failed to initialize \"blobentry\" table.")?;
877
Janis Danisevskis66784c42021-01-27 08:40:25 -0800878 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800879 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
880 ON blobentry(keyentryid);",
881 NO_PARAMS,
882 )
883 .context("Failed to create index blobentry_keyentryid_index.")?;
884
885 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800886 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
887 id INTEGER PRIMARY KEY,
888 blobentryid INTEGER,
889 tag INTEGER,
890 data ANY,
891 UNIQUE (blobentryid, tag));",
892 NO_PARAMS,
893 )
894 .context("Failed to initialize \"blobmetadata\" table.")?;
895
896 tx.execute(
897 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
898 ON blobmetadata(blobentryid);",
899 NO_PARAMS,
900 )
901 .context("Failed to create index blobmetadata_blobentryid_index.")?;
902
903 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700904 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000905 keyentryid INTEGER,
906 tag INTEGER,
907 data ANY,
908 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700909 NO_PARAMS,
910 )
911 .context("Failed to initialize \"keyparameter\" table.")?;
912
Janis Danisevskis66784c42021-01-27 08:40:25 -0800913 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800914 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
915 ON keyparameter(keyentryid);",
916 NO_PARAMS,
917 )
918 .context("Failed to create index keyparameter_keyentryid_index.")?;
919
920 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800921 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
922 keyentryid INTEGER,
923 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000924 data ANY,
925 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800926 NO_PARAMS,
927 )
928 .context("Failed to initialize \"keymetadata\" table.")?;
929
Janis Danisevskis66784c42021-01-27 08:40:25 -0800930 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800931 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
932 ON keymetadata(keyentryid);",
933 NO_PARAMS,
934 )
935 .context("Failed to create index keymetadata_keyentryid_index.")?;
936
937 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800938 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700939 id INTEGER UNIQUE,
940 grantee INTEGER,
941 keyentryid INTEGER,
942 access_vector INTEGER);",
943 NO_PARAMS,
944 )
945 .context("Failed to initialize \"grant\" table.")?;
946
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000947 //TODO: only drop the following two perboot tables if this is the first start up
948 //during the boot (b/175716626).
Janis Danisevskis66784c42021-01-27 08:40:25 -0800949 // tx.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000950 // .context("Failed to drop perboot.authtoken table")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -0800951 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000952 "CREATE TABLE IF NOT EXISTS perboot.authtoken (
953 id INTEGER PRIMARY KEY,
954 challenge INTEGER,
955 user_id INTEGER,
956 auth_id INTEGER,
957 authenticator_type INTEGER,
958 timestamp INTEGER,
959 mac BLOB,
960 time_received INTEGER,
961 UNIQUE(user_id, auth_id, authenticator_type));",
962 NO_PARAMS,
963 )
964 .context("Failed to initialize \"authtoken\" table.")?;
965
Janis Danisevskis66784c42021-01-27 08:40:25 -0800966 // tx.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000967 // .context("Failed to drop perboot.metadata table")?;
968 // metadata table stores certain miscellaneous information required for keystore functioning
969 // during a boot cycle, as key-value pairs.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800970 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000971 "CREATE TABLE IF NOT EXISTS perboot.metadata (
972 key TEXT,
973 value BLOB,
974 UNIQUE(key));",
975 NO_PARAMS,
976 )
977 .context("Failed to initialize \"metadata\" table.")?;
Joel Galenson0891bc12020-07-20 10:37:03 -0700978 Ok(())
979 }
980
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700981 fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> {
982 let conn =
983 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
984
Janis Danisevskis66784c42021-01-27 08:40:25 -0800985 loop {
986 if let Err(e) = conn
987 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
988 .context("Failed to attach database persistent.")
989 {
990 if Self::is_locked_error(&e) {
991 std::thread::sleep(std::time::Duration::from_micros(500));
992 continue;
993 } else {
994 return Err(e);
995 }
996 }
997 break;
998 }
999 loop {
1000 if let Err(e) = conn
1001 .execute("ATTACH DATABASE ? as perboot;", params![perboot_file])
1002 .context("Failed to attach database perboot.")
1003 {
1004 if Self::is_locked_error(&e) {
1005 std::thread::sleep(std::time::Duration::from_micros(500));
1006 continue;
1007 } else {
1008 return Err(e);
1009 }
1010 }
1011 break;
1012 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001013
1014 Ok(conn)
1015 }
1016
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001017 /// This function is intended to be used by the garbage collector.
1018 /// It deletes the blob given by `blob_id_to_delete`. It then tries to find a superseded
1019 /// key blob that might need special handling by the garbage collector.
1020 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1021 /// need special handling and returns None.
1022 pub fn handle_next_superseded_blob(
1023 &mut self,
1024 blob_id_to_delete: Option<i64>,
1025 ) -> Result<Option<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001026 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001027 // Delete the given blob if one was given.
1028 if let Some(blob_id_to_delete) = blob_id_to_delete {
1029 tx.execute(
1030 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
1031 params![blob_id_to_delete],
1032 )
1033 .context("Trying to delete blob metadata.")?;
1034 tx.execute(
1035 "DELETE FROM persistent.blobentry WHERE id = ?;",
1036 params![blob_id_to_delete],
1037 )
1038 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001039 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001040
1041 // Find another superseded keyblob load its metadata and return it.
1042 if let Some((blob_id, blob)) = tx
1043 .query_row(
1044 "SELECT id, blob FROM persistent.blobentry
1045 WHERE subcomponent_type = ?
1046 AND (
1047 id NOT IN (
1048 SELECT MAX(id) FROM persistent.blobentry
1049 WHERE subcomponent_type = ?
1050 GROUP BY keyentryid, subcomponent_type
1051 )
1052 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1053 );",
1054 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1055 |row| Ok((row.get(0)?, row.get(1)?)),
1056 )
1057 .optional()
1058 .context("Trying to query superseded blob.")?
1059 {
1060 let blob_metadata = BlobMetaData::load_from_db(blob_id, tx)
1061 .context("Trying to load blob metadata.")?;
1062 return Ok(Some((blob_id, blob, blob_metadata))).no_gc();
1063 }
1064
1065 // We did not find any superseded key blob, so let's remove other superseded blob in
1066 // one transaction.
1067 tx.execute(
1068 "DELETE FROM persistent.blobentry
1069 WHERE NOT subcomponent_type = ?
1070 AND (
1071 id NOT IN (
1072 SELECT MAX(id) FROM persistent.blobentry
1073 WHERE NOT subcomponent_type = ?
1074 GROUP BY keyentryid, subcomponent_type
1075 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1076 );",
1077 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1078 )
1079 .context("Trying to purge superseded blobs.")?;
1080
1081 Ok(None).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001082 })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001083 .context("In handle_next_superseded_blob.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001084 }
1085
1086 /// This maintenance function should be called only once before the database is used for the
1087 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1088 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1089 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1090 /// Keystore crashed at some point during key generation. Callers may want to log such
1091 /// occurrences.
1092 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1093 /// it to `KeyLifeCycle::Live` may have grants.
1094 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001095 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1096 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001097 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1098 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1099 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001100 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001101 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001102 })
1103 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001104 }
1105
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001106 /// Checks if a key exists with given key type and key descriptor properties.
1107 pub fn key_exists(
1108 &mut self,
1109 domain: Domain,
1110 nspace: i64,
1111 alias: &str,
1112 key_type: KeyType,
1113 ) -> Result<bool> {
1114 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1115 let key_descriptor =
1116 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1117 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1118 match result {
1119 Ok(_) => Ok(true),
1120 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1121 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1122 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1123 },
1124 }
1125 .no_gc()
1126 })
1127 .context("In key_exists.")
1128 }
1129
Hasini Gunasingheda895552021-01-27 19:34:37 +00001130 /// Stores a super key in the database.
1131 pub fn store_super_key(
1132 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001133 user_id: u32,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001134 blob_info: &(&[u8], &BlobMetaData),
1135 ) -> Result<KeyEntry> {
1136 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1137 let key_id = Self::insert_with_retry(|id| {
1138 tx.execute(
1139 "INSERT into persistent.keyentry
1140 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001141 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001142 params![
1143 id,
1144 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001145 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001146 user_id as i64,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001147 Self::USER_SUPER_KEY_ALIAS,
1148 KeyLifeCycle::Live,
1149 &KEYSTORE_UUID,
1150 ],
1151 )
1152 })
1153 .context("Failed to insert into keyentry table.")?;
1154
1155 let (blob, blob_metadata) = *blob_info;
1156 Self::set_blob_internal(
1157 &tx,
1158 key_id,
1159 SubComponentType::KEY_BLOB,
1160 Some(blob),
1161 Some(blob_metadata),
1162 )
1163 .context("Failed to store key blob.")?;
1164
1165 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1166 .context("Trying to load key components.")
1167 .no_gc()
1168 })
1169 .context("In store_super_key.")
1170 }
1171
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001172 /// Loads super key of a given user, if exists
1173 pub fn load_super_key(&mut self, user_id: u32) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
1174 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1175 let key_descriptor = KeyDescriptor {
1176 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001177 nspace: user_id as i64,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001178 alias: Some(String::from("USER_SUPER_KEY")),
1179 blob: None,
1180 };
1181 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1182 match id {
1183 Ok(id) => {
1184 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1185 .context("In load_super_key. Failed to load key entry.")?;
1186 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1187 }
1188 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1189 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1190 _ => Err(error).context("In load_super_key."),
1191 },
1192 }
1193 .no_gc()
1194 })
1195 .context("In load_super_key.")
1196 }
1197
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001198 /// Atomically loads a key entry and associated metadata or creates it using the
1199 /// callback create_new_key callback. The callback is called during a database
1200 /// transaction. This means that implementers should be mindful about using
1201 /// blocking operations such as IPC or grabbing mutexes.
1202 pub fn get_or_create_key_with<F>(
1203 &mut self,
1204 domain: Domain,
1205 namespace: i64,
1206 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001207 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001208 create_new_key: F,
1209 ) -> Result<(KeyIdGuard, KeyEntry)>
1210 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001211 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001212 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001213 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1214 let id = {
1215 let mut stmt = tx
1216 .prepare(
1217 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001218 WHERE
1219 key_type = ?
1220 AND domain = ?
1221 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001222 AND alias = ?
1223 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001224 )
1225 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1226 let mut rows = stmt
1227 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1228 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001229
Janis Danisevskis66784c42021-01-27 08:40:25 -08001230 db_utils::with_rows_extract_one(&mut rows, |row| {
1231 Ok(match row {
1232 Some(r) => r.get(0).context("Failed to unpack id.")?,
1233 None => None,
1234 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001235 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001236 .context("In get_or_create_key_with.")?
1237 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001238
Janis Danisevskis66784c42021-01-27 08:40:25 -08001239 let (id, entry) = match id {
1240 Some(id) => (
1241 id,
1242 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1243 .context("In get_or_create_key_with.")?,
1244 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001245
Janis Danisevskis66784c42021-01-27 08:40:25 -08001246 None => {
1247 let id = Self::insert_with_retry(|id| {
1248 tx.execute(
1249 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001250 (id, key_type, domain, namespace, alias, state, km_uuid)
1251 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001252 params![
1253 id,
1254 KeyType::Super,
1255 domain.0,
1256 namespace,
1257 alias,
1258 KeyLifeCycle::Live,
1259 km_uuid,
1260 ],
1261 )
1262 })
1263 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001264
Janis Danisevskis66784c42021-01-27 08:40:25 -08001265 let (blob, metadata) =
1266 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001267 Self::set_blob_internal(
1268 &tx,
1269 id,
1270 SubComponentType::KEY_BLOB,
1271 Some(&blob),
1272 Some(&metadata),
1273 )
1274 .context("In get_of_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001275 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001276 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001277 KeyEntry {
1278 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001279 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001280 pure_cert: false,
1281 ..Default::default()
1282 },
1283 )
1284 }
1285 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001286 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001287 })
1288 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001289 }
1290
Janis Danisevskis66784c42021-01-27 08:40:25 -08001291 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1292 /// waiting for the database file to become available. This makes it
1293 /// impossible to successfully recover from a locked database when the
1294 /// transaction holding the device busy is in the same process on a
1295 /// different connection. As a result the busy handler has to time out and
1296 /// fail in order to make progress.
1297 ///
1298 /// Instead, we set the busy handler to None (return immediately). And catch
1299 /// Busy and Locked errors (the latter occur on in memory databases with
1300 /// shared cache, e.g., the per-boot database.) and restart the transaction
1301 /// after a grace period of half a millisecond.
1302 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001303 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001304 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1305 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001306 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1307 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001308 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001309 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001310 loop {
1311 match self
1312 .conn
1313 .transaction_with_behavior(behavior)
1314 .context("In with_transaction.")
1315 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1316 .and_then(|(result, tx)| {
1317 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1318 Ok(result)
1319 }) {
1320 Ok(result) => break Ok(result),
1321 Err(e) => {
1322 if Self::is_locked_error(&e) {
1323 std::thread::sleep(std::time::Duration::from_micros(500));
1324 continue;
1325 } else {
1326 return Err(e).context("In with_transaction.");
1327 }
1328 }
1329 }
1330 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001331 .map(|(need_gc, result)| {
1332 if need_gc {
1333 if let Some(ref gc) = self.gc {
1334 gc.notify_gc();
1335 }
1336 }
1337 result
1338 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001339 }
1340
1341 fn is_locked_error(e: &anyhow::Error) -> bool {
1342 matches!(e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1343 Some(rusqlite::ffi::Error {
1344 code: rusqlite::ErrorCode::DatabaseBusy,
1345 ..
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001346 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001347 | Some(rusqlite::ffi::Error {
1348 code: rusqlite::ErrorCode::DatabaseLocked,
1349 ..
1350 }))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001351 }
1352
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001353 /// Creates a new key entry and allocates a new randomized id for the new key.
1354 /// The key id gets associated with a domain and namespace but not with an alias.
1355 /// To complete key generation `rebind_alias` should be called after all of the
1356 /// key artifacts, i.e., blobs and parameters have been associated with the new
1357 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1358 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001359 pub fn create_key_entry(
1360 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001361 domain: &Domain,
1362 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001363 km_uuid: &Uuid,
1364 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001365 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001366 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001367 })
1368 .context("In create_key_entry.")
1369 }
1370
1371 fn create_key_entry_internal(
1372 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001373 domain: &Domain,
1374 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001375 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001376 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001377 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001378 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001379 _ => {
1380 return Err(KsError::sys())
1381 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1382 }
1383 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001384 Ok(KEY_ID_LOCK.get(
1385 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001386 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001387 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001388 (id, key_type, domain, namespace, alias, state, km_uuid)
1389 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001390 params![
1391 id,
1392 KeyType::Client,
1393 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001394 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001395 KeyLifeCycle::Existing,
1396 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001397 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001398 )
1399 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001400 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001401 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001402 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001403
Max Bires2b2e6562020-09-22 11:22:36 -07001404 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1405 /// The key id gets associated with a domain and namespace later but not with an alias. The
1406 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1407 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1408 /// a key.
1409 pub fn create_attestation_key_entry(
1410 &mut self,
1411 maced_public_key: &[u8],
1412 raw_public_key: &[u8],
1413 private_key: &[u8],
1414 km_uuid: &Uuid,
1415 ) -> Result<()> {
1416 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1417 let key_id = KEY_ID_LOCK.get(
1418 Self::insert_with_retry(|id| {
1419 tx.execute(
1420 "INSERT into persistent.keyentry
1421 (id, key_type, domain, namespace, alias, state, km_uuid)
1422 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1423 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1424 )
1425 })
1426 .context("In create_key_entry")?,
1427 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001428 Self::set_blob_internal(
1429 &tx,
1430 key_id.0,
1431 SubComponentType::KEY_BLOB,
1432 Some(private_key),
1433 None,
1434 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001435 let mut metadata = KeyMetaData::new();
1436 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1437 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1438 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001439 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001440 })
1441 .context("In create_attestation_key_entry")
1442 }
1443
Janis Danisevskis377d1002021-01-27 19:07:48 -08001444 /// Set a new blob and associates it with the given key id. Each blob
1445 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001446 /// Each key can have one of each sub component type associated. If more
1447 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001448 /// will get garbage collected.
1449 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1450 /// removed by setting blob to None.
1451 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001452 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001453 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001454 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001455 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001456 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001457 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001458 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001459 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001460 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001461 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001462 }
1463
Janis Danisevskiseed69842021-02-18 20:04:10 -08001464 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1465 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1466 /// We use this to insert key blobs into the database which can then be garbage collected
1467 /// lazily by the key garbage collector.
1468 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
1469 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1470 Self::set_blob_internal(
1471 &tx,
1472 Self::UNASSIGNED_KEY_ID,
1473 SubComponentType::KEY_BLOB,
1474 Some(blob),
1475 Some(blob_metadata),
1476 )
1477 .need_gc()
1478 })
1479 .context("In set_deleted_blob.")
1480 }
1481
Janis Danisevskis377d1002021-01-27 19:07:48 -08001482 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001483 tx: &Transaction,
1484 key_id: i64,
1485 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001486 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001487 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001488 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001489 match (blob, sc_type) {
1490 (Some(blob), _) => {
1491 tx.execute(
1492 "INSERT INTO persistent.blobentry
1493 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1494 params![sc_type, key_id, blob],
1495 )
1496 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001497 if let Some(blob_metadata) = blob_metadata {
1498 let blob_id = tx
1499 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1500 row.get(0)
1501 })
1502 .context("In set_blob_internal: Failed to get new blob id.")?;
1503 blob_metadata
1504 .store_in_db(blob_id, tx)
1505 .context("In set_blob_internal: Trying to store blob metadata.")?;
1506 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001507 }
1508 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1509 tx.execute(
1510 "DELETE FROM persistent.blobentry
1511 WHERE subcomponent_type = ? AND keyentryid = ?;",
1512 params![sc_type, key_id],
1513 )
1514 .context("In set_blob_internal: Failed to delete blob.")?;
1515 }
1516 (None, _) => {
1517 return Err(KsError::sys())
1518 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1519 }
1520 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001521 Ok(())
1522 }
1523
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001524 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1525 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001526 #[cfg(test)]
1527 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001528 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001529 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001530 })
1531 .context("In insert_keyparameter.")
1532 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001533
Janis Danisevskis66784c42021-01-27 08:40:25 -08001534 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001535 tx: &Transaction,
1536 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001537 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001538 ) -> Result<()> {
1539 let mut stmt = tx
1540 .prepare(
1541 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1542 VALUES (?, ?, ?, ?);",
1543 )
1544 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1545
Janis Danisevskis66784c42021-01-27 08:40:25 -08001546 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001547 stmt.insert(params![
1548 key_id.0,
1549 p.get_tag().0,
1550 p.key_parameter_value(),
1551 p.security_level().0
1552 ])
1553 .with_context(|| {
1554 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1555 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001556 }
1557 Ok(())
1558 }
1559
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001560 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001561 #[cfg(test)]
1562 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001563 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001564 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001565 })
1566 .context("In insert_key_metadata.")
1567 }
1568
Max Bires2b2e6562020-09-22 11:22:36 -07001569 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1570 /// on the public key.
1571 pub fn store_signed_attestation_certificate_chain(
1572 &mut self,
1573 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001574 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001575 cert_chain: &[u8],
1576 expiration_date: i64,
1577 km_uuid: &Uuid,
1578 ) -> Result<()> {
1579 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1580 let mut stmt = tx
1581 .prepare(
1582 "SELECT keyentryid
1583 FROM persistent.keymetadata
1584 WHERE tag = ? AND data = ? AND keyentryid IN
1585 (SELECT id
1586 FROM persistent.keyentry
1587 WHERE
1588 alias IS NULL AND
1589 domain IS NULL AND
1590 namespace IS NULL AND
1591 key_type = ? AND
1592 km_uuid = ?);",
1593 )
1594 .context("Failed to store attestation certificate chain.")?;
1595 let mut rows = stmt
1596 .query(params![
1597 KeyMetaData::AttestationRawPubKey,
1598 raw_public_key,
1599 KeyType::Attestation,
1600 km_uuid
1601 ])
1602 .context("Failed to fetch keyid")?;
1603 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1604 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1605 .get(0)
1606 .context("Failed to unpack id.")
1607 })
1608 .context("Failed to get key_id.")?;
1609 let num_updated = tx
1610 .execute(
1611 "UPDATE persistent.keyentry
1612 SET alias = ?
1613 WHERE id = ?;",
1614 params!["signed", key_id],
1615 )
1616 .context("Failed to update alias.")?;
1617 if num_updated != 1 {
1618 return Err(KsError::sys()).context("Alias not updated for the key.");
1619 }
1620 let mut metadata = KeyMetaData::new();
1621 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1622 expiration_date,
1623 )));
1624 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001625 Self::set_blob_internal(
1626 &tx,
1627 key_id,
1628 SubComponentType::CERT_CHAIN,
1629 Some(cert_chain),
1630 None,
1631 )
1632 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001633 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1634 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001635 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001636 })
1637 .context("In store_signed_attestation_certificate_chain: ")
1638 }
1639
1640 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1641 /// currently have a key assigned to it.
1642 pub fn assign_attestation_key(
1643 &mut self,
1644 domain: Domain,
1645 namespace: i64,
1646 km_uuid: &Uuid,
1647 ) -> Result<()> {
1648 match domain {
1649 Domain::APP | Domain::SELINUX => {}
1650 _ => {
1651 return Err(KsError::sys()).context(format!(
1652 concat!(
1653 "In assign_attestation_key: Domain {:?} ",
1654 "must be either App or SELinux.",
1655 ),
1656 domain
1657 ));
1658 }
1659 }
1660 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1661 let result = tx
1662 .execute(
1663 "UPDATE persistent.keyentry
1664 SET domain=?1, namespace=?2
1665 WHERE
1666 id =
1667 (SELECT MIN(id)
1668 FROM persistent.keyentry
1669 WHERE ALIAS IS NOT NULL
1670 AND domain IS NULL
1671 AND key_type IS ?3
1672 AND state IS ?4
1673 AND km_uuid IS ?5)
1674 AND
1675 (SELECT COUNT(*)
1676 FROM persistent.keyentry
1677 WHERE domain=?1
1678 AND namespace=?2
1679 AND key_type IS ?3
1680 AND state IS ?4
1681 AND km_uuid IS ?5) = 0;",
1682 params![
1683 domain.0 as u32,
1684 namespace,
1685 KeyType::Attestation,
1686 KeyLifeCycle::Live,
1687 km_uuid,
1688 ],
1689 )
1690 .context("Failed to assign attestation key")?;
1691 if result != 1 {
1692 return Err(KsError::sys()).context(format!(
1693 "Expected to update a single entry but instead updated {}.",
1694 result
1695 ));
1696 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001697 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001698 })
1699 .context("In assign_attestation_key: ")
1700 }
1701
1702 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1703 /// provisioning server, or the maximum number available if there are not num_keys number of
1704 /// entries in the table.
1705 pub fn fetch_unsigned_attestation_keys(
1706 &mut self,
1707 num_keys: i32,
1708 km_uuid: &Uuid,
1709 ) -> Result<Vec<Vec<u8>>> {
1710 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1711 let mut stmt = tx
1712 .prepare(
1713 "SELECT data
1714 FROM persistent.keymetadata
1715 WHERE tag = ? AND keyentryid IN
1716 (SELECT id
1717 FROM persistent.keyentry
1718 WHERE
1719 alias IS NULL AND
1720 domain IS NULL AND
1721 namespace IS NULL AND
1722 key_type = ? AND
1723 km_uuid = ?
1724 LIMIT ?);",
1725 )
1726 .context("Failed to prepare statement")?;
1727 let rows = stmt
1728 .query_map(
1729 params![
1730 KeyMetaData::AttestationMacedPublicKey,
1731 KeyType::Attestation,
1732 km_uuid,
1733 num_keys
1734 ],
1735 |row| Ok(row.get(0)?),
1736 )?
1737 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1738 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001739 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001740 })
1741 .context("In fetch_unsigned_attestation_keys")
1742 }
1743
1744 /// Removes any keys that have expired as of the current time. Returns the number of keys
1745 /// marked unreferenced that are bound to be garbage collected.
1746 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
1747 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1748 let mut stmt = tx
1749 .prepare(
1750 "SELECT keyentryid, data
1751 FROM persistent.keymetadata
1752 WHERE tag = ? AND keyentryid IN
1753 (SELECT id
1754 FROM persistent.keyentry
1755 WHERE key_type = ?);",
1756 )
1757 .context("Failed to prepare query")?;
1758 let key_ids_to_check = stmt
1759 .query_map(
1760 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1761 |row| Ok((row.get(0)?, row.get(1)?)),
1762 )?
1763 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1764 .context("Failed to get date metadata")?;
1765 let curr_time = DateTime::from_millis_epoch(
1766 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1767 );
1768 let mut num_deleted = 0;
1769 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1770 if Self::mark_unreferenced(&tx, id)? {
1771 num_deleted += 1;
1772 }
1773 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001774 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001775 })
1776 .context("In delete_expired_attestation_keys: ")
1777 }
1778
1779 /// Counts the number of keys that will expire by the provided epoch date and the number of
1780 /// keys not currently assigned to a domain.
1781 pub fn get_attestation_pool_status(
1782 &mut self,
1783 date: i64,
1784 km_uuid: &Uuid,
1785 ) -> Result<AttestationPoolStatus> {
1786 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1787 let mut stmt = tx.prepare(
1788 "SELECT data
1789 FROM persistent.keymetadata
1790 WHERE tag = ? AND keyentryid IN
1791 (SELECT id
1792 FROM persistent.keyentry
1793 WHERE alias IS NOT NULL
1794 AND key_type = ?
1795 AND km_uuid = ?
1796 AND state = ?);",
1797 )?;
1798 let times = stmt
1799 .query_map(
1800 params![
1801 KeyMetaData::AttestationExpirationDate,
1802 KeyType::Attestation,
1803 km_uuid,
1804 KeyLifeCycle::Live
1805 ],
1806 |row| Ok(row.get(0)?),
1807 )?
1808 .collect::<rusqlite::Result<Vec<DateTime>>>()
1809 .context("Failed to execute metadata statement")?;
1810 let expiring =
1811 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1812 as i32;
1813 stmt = tx.prepare(
1814 "SELECT alias, domain
1815 FROM persistent.keyentry
1816 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1817 )?;
1818 let rows = stmt
1819 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1820 Ok((row.get(0)?, row.get(1)?))
1821 })?
1822 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
1823 .context("Failed to execute keyentry statement")?;
1824 let mut unassigned = 0i32;
1825 let mut attested = 0i32;
1826 let total = rows.len() as i32;
1827 for (alias, domain) in rows {
1828 match (alias, domain) {
1829 (Some(_alias), None) => {
1830 attested += 1;
1831 unassigned += 1;
1832 }
1833 (Some(_alias), Some(_domain)) => {
1834 attested += 1;
1835 }
1836 _ => {}
1837 }
1838 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001839 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001840 })
1841 .context("In get_attestation_pool_status: ")
1842 }
1843
1844 /// Fetches the private key and corresponding certificate chain assigned to a
1845 /// domain/namespace pair. Will either return nothing if the domain/namespace is
1846 /// not assigned, or one CertificateChain.
1847 pub fn retrieve_attestation_key_and_cert_chain(
1848 &mut self,
1849 domain: Domain,
1850 namespace: i64,
1851 km_uuid: &Uuid,
1852 ) -> Result<Option<CertificateChain>> {
1853 match domain {
1854 Domain::APP | Domain::SELINUX => {}
1855 _ => {
1856 return Err(KsError::sys())
1857 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1858 }
1859 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001860 self.with_transaction(TransactionBehavior::Deferred, |tx| {
1861 let mut stmt = tx.prepare(
1862 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07001863 FROM persistent.blobentry
1864 WHERE keyentryid IN
1865 (SELECT id
1866 FROM persistent.keyentry
1867 WHERE key_type = ?
1868 AND domain = ?
1869 AND namespace = ?
1870 AND state = ?
1871 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001872 )?;
1873 let rows = stmt
1874 .query_map(
1875 params![
1876 KeyType::Attestation,
1877 domain.0 as u32,
1878 namespace,
1879 KeyLifeCycle::Live,
1880 km_uuid
1881 ],
1882 |row| Ok((row.get(0)?, row.get(1)?)),
1883 )?
1884 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08001885 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001886 if rows.is_empty() {
1887 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08001888 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001889 return Err(KsError::sys()).context(format!(
1890 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08001891 "Expected to get a single attestation",
1892 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
1893 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001894 rows.len()
1895 ));
Max Bires2b2e6562020-09-22 11:22:36 -07001896 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001897 let mut km_blob: Vec<u8> = Vec::new();
1898 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08001899 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001900 for row in rows {
1901 let sub_type: SubComponentType = row.0;
1902 match sub_type {
1903 SubComponentType::KEY_BLOB => {
1904 km_blob = row.1;
1905 }
1906 SubComponentType::CERT_CHAIN => {
1907 cert_chain_blob = row.1;
1908 }
Max Biresb2e1d032021-02-08 21:35:05 -08001909 SubComponentType::CERT => {
1910 batch_cert_blob = row.1;
1911 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001912 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
1913 }
1914 }
1915 Ok(Some(CertificateChain {
1916 private_key: ZVec::try_from(km_blob)?,
Max Biresb2e1d032021-02-08 21:35:05 -08001917 batch_cert: ZVec::try_from(batch_cert_blob)?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001918 cert_chain: ZVec::try_from(cert_chain_blob)?,
1919 }))
1920 .no_gc()
1921 })
Max Biresb2e1d032021-02-08 21:35:05 -08001922 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07001923 }
1924
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001925 /// Updates the alias column of the given key id `newid` with the given alias,
1926 /// and atomically, removes the alias, domain, and namespace from another row
1927 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001928 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1929 /// collector.
1930 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001931 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001932 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001933 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001934 domain: &Domain,
1935 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001936 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001937 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001938 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001939 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001940 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001941 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001942 domain
1943 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001944 }
1945 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001946 let updated = tx
1947 .execute(
1948 "UPDATE persistent.keyentry
1949 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07001950 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001951 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
1952 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001953 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001954 let result = tx
1955 .execute(
1956 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001957 SET alias = ?, state = ?
1958 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
1959 params![
1960 alias,
1961 KeyLifeCycle::Live,
1962 newid.0,
1963 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001964 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001965 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001966 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001967 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001968 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001969 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07001970 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001971 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001972 result
1973 ));
1974 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001975 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001976 }
1977
1978 /// Store a new key in a single transaction.
1979 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1980 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001981 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1982 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001983 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001984 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001985 key: &KeyDescriptor,
1986 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001987 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08001988 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001989 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001990 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001991 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001992 let (alias, domain, namespace) = match key {
1993 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1994 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1995 (alias, key.domain, nspace)
1996 }
1997 _ => {
1998 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1999 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2000 }
2001 };
2002 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002003 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002004 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002005 let (blob, blob_metadata) = *blob_info;
2006 Self::set_blob_internal(
2007 tx,
2008 key_id.id(),
2009 SubComponentType::KEY_BLOB,
2010 Some(blob),
2011 Some(&blob_metadata),
2012 )
2013 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002014 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002015 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002016 .context("Trying to insert the certificate.")?;
2017 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002018 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002019 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002020 tx,
2021 key_id.id(),
2022 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002023 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002024 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002025 )
2026 .context("Trying to insert the certificate chain.")?;
2027 }
2028 Self::insert_keyparameter_internal(tx, &key_id, params)
2029 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002030 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002031 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002032 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002033 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002034 })
2035 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002036 }
2037
Janis Danisevskis377d1002021-01-27 19:07:48 -08002038 /// Store a new certificate
2039 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2040 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002041 pub fn store_new_certificate(
2042 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002043 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002044 cert: &[u8],
2045 km_uuid: &Uuid,
2046 ) -> Result<KeyIdGuard> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002047 let (alias, domain, namespace) = match key {
2048 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2049 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2050 (alias, key.domain, nspace)
2051 }
2052 _ => {
2053 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2054 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2055 )
2056 }
2057 };
2058 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002059 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002060 .context("Trying to create new key entry.")?;
2061
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002062 Self::set_blob_internal(
2063 tx,
2064 key_id.id(),
2065 SubComponentType::CERT_CHAIN,
2066 Some(cert),
2067 None,
2068 )
2069 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002070
2071 let mut metadata = KeyMetaData::new();
2072 metadata.add(KeyMetaEntry::CreationDate(
2073 DateTime::now().context("Trying to make creation time.")?,
2074 ));
2075
2076 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2077
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002078 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002079 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002080 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002081 })
2082 .context("In store_new_certificate.")
2083 }
2084
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002085 // Helper function loading the key_id given the key descriptor
2086 // tuple comprising domain, namespace, and alias.
2087 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002088 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002089 let alias = key
2090 .alias
2091 .as_ref()
2092 .map_or_else(|| Err(KsError::sys()), Ok)
2093 .context("In load_key_entry_id: Alias must be specified.")?;
2094 let mut stmt = tx
2095 .prepare(
2096 "SELECT id FROM persistent.keyentry
2097 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002098 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002099 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002100 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002101 AND alias = ?
2102 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002103 )
2104 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2105 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002106 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002107 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002108 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002109 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002110 .get(0)
2111 .context("Failed to unpack id.")
2112 })
2113 .context("In load_key_entry_id.")
2114 }
2115
2116 /// This helper function completes the access tuple of a key, which is required
2117 /// to perform access control. The strategy depends on the `domain` field in the
2118 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002119 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002120 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002121 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002122 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002123 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002124 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002125 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002126 /// `namespace`.
2127 /// In each case the information returned is sufficient to perform the access
2128 /// check and the key id can be used to load further key artifacts.
2129 fn load_access_tuple(
2130 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002131 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002132 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002133 caller_uid: u32,
2134 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2135 match key.domain {
2136 // Domain App or SELinux. In this case we load the key_id from
2137 // the keyentry database for further loading of key components.
2138 // We already have the full access tuple to perform access control.
2139 // The only distinction is that we use the caller_uid instead
2140 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002141 // Domain::APP.
2142 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002143 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002144 if access_key.domain == Domain::APP {
2145 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002146 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002147 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002148 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002149
2150 Ok((key_id, access_key, None))
2151 }
2152
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002153 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002154 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002155 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002156 let mut stmt = tx
2157 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002158 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002159 WHERE grantee = ? AND id = ?;",
2160 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002161 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002162 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002163 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002164 .context("Domain:Grant: query failed.")?;
2165 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002166 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002167 let r =
2168 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002169 Ok((
2170 r.get(0).context("Failed to unpack key_id.")?,
2171 r.get(1).context("Failed to unpack access_vector.")?,
2172 ))
2173 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002174 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002175 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002176 }
2177
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002178 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002179 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002180 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002181 let (domain, namespace): (Domain, i64) = {
2182 let mut stmt = tx
2183 .prepare(
2184 "SELECT domain, namespace FROM persistent.keyentry
2185 WHERE
2186 id = ?
2187 AND state = ?;",
2188 )
2189 .context("Domain::KEY_ID: prepare statement failed")?;
2190 let mut rows = stmt
2191 .query(params![key.nspace, KeyLifeCycle::Live])
2192 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002193 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002194 let r =
2195 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002196 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002197 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002198 r.get(1).context("Failed to unpack namespace.")?,
2199 ))
2200 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002201 .context("Domain::KEY_ID.")?
2202 };
2203
2204 // We may use a key by id after loading it by grant.
2205 // In this case we have to check if the caller has a grant for this particular
2206 // key. We can skip this if we already know that the caller is the owner.
2207 // But we cannot know this if domain is anything but App. E.g. in the case
2208 // of Domain::SELINUX we have to speculatively check for grants because we have to
2209 // consult the SEPolicy before we know if the caller is the owner.
2210 let access_vector: Option<KeyPermSet> =
2211 if domain != Domain::APP || namespace != caller_uid as i64 {
2212 let access_vector: Option<i32> = tx
2213 .query_row(
2214 "SELECT access_vector FROM persistent.grant
2215 WHERE grantee = ? AND keyentryid = ?;",
2216 params![caller_uid as i64, key.nspace],
2217 |row| row.get(0),
2218 )
2219 .optional()
2220 .context("Domain::KEY_ID: query grant failed.")?;
2221 access_vector.map(|p| p.into())
2222 } else {
2223 None
2224 };
2225
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002226 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002227 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002228 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002229 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002230
Janis Danisevskis45760022021-01-19 16:34:10 -08002231 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002232 }
2233 _ => Err(anyhow!(KsError::sys())),
2234 }
2235 }
2236
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002237 fn load_blob_components(
2238 key_id: i64,
2239 load_bits: KeyEntryLoadBits,
2240 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002241 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002242 let mut stmt = tx
2243 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002244 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002245 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2246 )
2247 .context("In load_blob_components: prepare statement failed.")?;
2248
2249 let mut rows =
2250 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2251
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002252 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002253 let mut cert_blob: Option<Vec<u8>> = None;
2254 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002255 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002256 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002257 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002258 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002259 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002260 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2261 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002262 key_blob = Some((
2263 row.get(0).context("Failed to extract key blob id.")?,
2264 row.get(2).context("Failed to extract key blob.")?,
2265 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002266 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002267 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002268 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002269 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002270 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002271 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002272 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002273 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002274 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002275 (SubComponentType::CERT, _, _)
2276 | (SubComponentType::CERT_CHAIN, _, _)
2277 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002278 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2279 }
2280 Ok(())
2281 })
2282 .context("In load_blob_components.")?;
2283
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002284 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2285 Ok(Some((
2286 blob,
2287 BlobMetaData::load_from_db(blob_id, tx)
2288 .context("In load_blob_components: Trying to load blob_metadata.")?,
2289 )))
2290 })?;
2291
2292 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002293 }
2294
2295 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2296 let mut stmt = tx
2297 .prepare(
2298 "SELECT tag, data, security_level from persistent.keyparameter
2299 WHERE keyentryid = ?;",
2300 )
2301 .context("In load_key_parameters: prepare statement failed.")?;
2302
2303 let mut parameters: Vec<KeyParameter> = Vec::new();
2304
2305 let mut rows =
2306 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002307 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002308 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2309 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002310 parameters.push(
2311 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2312 .context("Failed to read KeyParameter.")?,
2313 );
2314 Ok(())
2315 })
2316 .context("In load_key_parameters.")?;
2317
2318 Ok(parameters)
2319 }
2320
Qi Wub9433b52020-12-01 14:52:46 +08002321 /// Decrements the usage count of a limited use key. This function first checks whether the
2322 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2323 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2324 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002325 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Qi Wub9433b52020-12-01 14:52:46 +08002326 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2327 let limit: Option<i32> = tx
2328 .query_row(
2329 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2330 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2331 |row| row.get(0),
2332 )
2333 .optional()
2334 .context("Trying to load usage count")?;
2335
2336 let limit = limit
2337 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2338 .context("The Key no longer exists. Key is exhausted.")?;
2339
2340 tx.execute(
2341 "UPDATE persistent.keyparameter
2342 SET data = data - 1
2343 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2344 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2345 )
2346 .context("Failed to update key usage count.")?;
2347
2348 match limit {
2349 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002350 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002351 .context("Trying to mark limited use key for deletion."),
2352 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002353 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002354 }
2355 })
2356 .context("In check_and_update_key_usage_count.")
2357 }
2358
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002359 /// Load a key entry by the given key descriptor.
2360 /// It uses the `check_permission` callback to verify if the access is allowed
2361 /// given the key access tuple read from the database using `load_access_tuple`.
2362 /// With `load_bits` the caller may specify which blobs shall be loaded from
2363 /// the blob database.
2364 pub fn load_key_entry(
2365 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002366 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002367 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002368 load_bits: KeyEntryLoadBits,
2369 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002370 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2371 ) -> Result<(KeyIdGuard, KeyEntry)> {
2372 loop {
2373 match self.load_key_entry_internal(
2374 key,
2375 key_type,
2376 load_bits,
2377 caller_uid,
2378 &check_permission,
2379 ) {
2380 Ok(result) => break Ok(result),
2381 Err(e) => {
2382 if Self::is_locked_error(&e) {
2383 std::thread::sleep(std::time::Duration::from_micros(500));
2384 continue;
2385 } else {
2386 return Err(e).context("In load_key_entry.");
2387 }
2388 }
2389 }
2390 }
2391 }
2392
2393 fn load_key_entry_internal(
2394 &mut self,
2395 key: &KeyDescriptor,
2396 key_type: KeyType,
2397 load_bits: KeyEntryLoadBits,
2398 caller_uid: u32,
2399 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002400 ) -> Result<(KeyIdGuard, KeyEntry)> {
2401 // KEY ID LOCK 1/2
2402 // If we got a key descriptor with a key id we can get the lock right away.
2403 // Otherwise we have to defer it until we know the key id.
2404 let key_id_guard = match key.domain {
2405 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2406 _ => None,
2407 };
2408
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002409 let tx = self
2410 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002411 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002412 .context("In load_key_entry: Failed to initialize transaction.")?;
2413
2414 // Load the key_id and complete the access control tuple.
2415 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002416 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2417 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002418
2419 // Perform access control. It is vital that we return here if the permission is denied.
2420 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002421 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002422
Janis Danisevskisaec14592020-11-12 09:41:49 -08002423 // KEY ID LOCK 2/2
2424 // If we did not get a key id lock by now, it was because we got a key descriptor
2425 // without a key id. At this point we got the key id, so we can try and get a lock.
2426 // However, we cannot block here, because we are in the middle of the transaction.
2427 // So first we try to get the lock non blocking. If that fails, we roll back the
2428 // transaction and block until we get the lock. After we successfully got the lock,
2429 // we start a new transaction and load the access tuple again.
2430 //
2431 // We don't need to perform access control again, because we already established
2432 // that the caller had access to the given key. But we need to make sure that the
2433 // key id still exists. So we have to load the key entry by key id this time.
2434 let (key_id_guard, tx) = match key_id_guard {
2435 None => match KEY_ID_LOCK.try_get(key_id) {
2436 None => {
2437 // Roll back the transaction.
2438 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002439
Janis Danisevskisaec14592020-11-12 09:41:49 -08002440 // Block until we have a key id lock.
2441 let key_id_guard = KEY_ID_LOCK.get(key_id);
2442
2443 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002444 let tx = self
2445 .conn
2446 .unchecked_transaction()
2447 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002448
2449 Self::load_access_tuple(
2450 &tx,
2451 // This time we have to load the key by the retrieved key id, because the
2452 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002453 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002454 domain: Domain::KEY_ID,
2455 nspace: key_id,
2456 ..Default::default()
2457 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002458 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002459 caller_uid,
2460 )
2461 .context("In load_key_entry. (deferred key lock)")?;
2462 (key_id_guard, tx)
2463 }
2464 Some(l) => (l, tx),
2465 },
2466 Some(key_id_guard) => (key_id_guard, tx),
2467 };
2468
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002469 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2470 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002471
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002472 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2473
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002474 Ok((key_id_guard, key_entry))
2475 }
2476
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002477 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002478 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002479 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2480 .context("Trying to delete keyentry.")?;
2481 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2482 .context("Trying to delete keymetadata.")?;
2483 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2484 .context("Trying to delete keyparameters.")?;
2485 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2486 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002487 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002488 }
2489
2490 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002491 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002492 pub fn unbind_key(
2493 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002494 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002495 key_type: KeyType,
2496 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002497 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002498 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002499 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2500 let (key_id, access_key_descriptor, access_vector) =
2501 Self::load_access_tuple(tx, key, key_type, caller_uid)
2502 .context("Trying to get access tuple.")?;
2503
2504 // Perform access control. It is vital that we return here if the permission is denied.
2505 // So do not touch that '?' at the end.
2506 check_permission(&access_key_descriptor, access_vector)
2507 .context("While checking permission.")?;
2508
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002509 Self::mark_unreferenced(tx, key_id)
2510 .map(|need_gc| (need_gc, ()))
2511 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002512 })
2513 .context("In unbind_key.")
2514 }
2515
Max Bires8e93d2b2021-01-14 13:17:59 -08002516 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2517 tx.query_row(
2518 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2519 params![key_id],
2520 |row| row.get(0),
2521 )
2522 .context("In get_key_km_uuid.")
2523 }
2524
Hasini Gunasingheda895552021-01-27 19:34:37 +00002525 /// Delete the keys created on behalf of the user, denoted by the user id.
2526 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2527 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2528 /// The caller of this function should notify the gc if the returned value is true.
2529 pub fn unbind_keys_for_user(
2530 &mut self,
2531 user_id: u32,
2532 keep_non_super_encrypted_keys: bool,
2533 ) -> Result<()> {
2534 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2535 let mut stmt = tx
2536 .prepare(&format!(
2537 "SELECT id from persistent.keyentry
2538 WHERE (
2539 key_type = ?
2540 AND domain = ?
2541 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2542 AND state = ?
2543 ) OR (
2544 key_type = ?
2545 AND namespace = ?
2546 AND alias = ?
2547 AND state = ?
2548 );",
2549 aid_user_offset = AID_USER_OFFSET
2550 ))
2551 .context(concat!(
2552 "In unbind_keys_for_user. ",
2553 "Failed to prepare the query to find the keys created by apps."
2554 ))?;
2555
2556 let mut rows = stmt
2557 .query(params![
2558 // WHERE client key:
2559 KeyType::Client,
2560 Domain::APP.0 as u32,
2561 user_id,
2562 KeyLifeCycle::Live,
2563 // OR super key:
2564 KeyType::Super,
2565 user_id,
2566 Self::USER_SUPER_KEY_ALIAS,
2567 KeyLifeCycle::Live
2568 ])
2569 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2570
2571 let mut key_ids: Vec<i64> = Vec::new();
2572 db_utils::with_rows_extract_all(&mut rows, |row| {
2573 key_ids
2574 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2575 Ok(())
2576 })
2577 .context("In unbind_keys_for_user.")?;
2578
2579 let mut notify_gc = false;
2580 for key_id in key_ids {
2581 if keep_non_super_encrypted_keys {
2582 // Load metadata and filter out non-super-encrypted keys.
2583 if let (_, Some((_, blob_metadata)), _, _) =
2584 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2585 .context("In unbind_keys_for_user: Trying to load blob info.")?
2586 {
2587 if blob_metadata.encrypted_by().is_none() {
2588 continue;
2589 }
2590 }
2591 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002592 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002593 .context("In unbind_keys_for_user.")?
2594 || notify_gc;
2595 }
2596 Ok(()).do_gc(notify_gc)
2597 })
2598 .context("In unbind_keys_for_user.")
2599 }
2600
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002601 fn load_key_components(
2602 tx: &Transaction,
2603 load_bits: KeyEntryLoadBits,
2604 key_id: i64,
2605 ) -> Result<KeyEntry> {
2606 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2607
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002608 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002609 Self::load_blob_components(key_id, load_bits, &tx)
2610 .context("In load_key_components.")?;
2611
Max Bires8e93d2b2021-01-14 13:17:59 -08002612 let parameters = Self::load_key_parameters(key_id, &tx)
2613 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002614
Max Bires8e93d2b2021-01-14 13:17:59 -08002615 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2616 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002617
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002618 Ok(KeyEntry {
2619 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002620 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002621 cert: cert_blob,
2622 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002623 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002624 parameters,
2625 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002626 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002627 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002628 }
2629
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002630 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2631 /// The key descriptors will have the domain, nspace, and alias field set.
2632 /// Domain must be APP or SELINUX, the caller must make sure of that.
2633 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002634 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2635 let mut stmt = tx
2636 .prepare(
2637 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002638 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002639 )
2640 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002641
Janis Danisevskis66784c42021-01-27 08:40:25 -08002642 let mut rows = stmt
2643 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2644 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002645
Janis Danisevskis66784c42021-01-27 08:40:25 -08002646 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2647 db_utils::with_rows_extract_all(&mut rows, |row| {
2648 descriptors.push(KeyDescriptor {
2649 domain,
2650 nspace: namespace,
2651 alias: Some(row.get(0).context("Trying to extract alias.")?),
2652 blob: None,
2653 });
2654 Ok(())
2655 })
2656 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002657 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002658 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002659 }
2660
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002661 /// Adds a grant to the grant table.
2662 /// Like `load_key_entry` this function loads the access tuple before
2663 /// it uses the callback for a permission check. Upon success,
2664 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2665 /// grant table. The new row will have a randomized id, which is used as
2666 /// grant id in the namespace field of the resulting KeyDescriptor.
2667 pub fn grant(
2668 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002669 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002670 caller_uid: u32,
2671 grantee_uid: u32,
2672 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002673 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002674 ) -> Result<KeyDescriptor> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002675 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2676 // Load the key_id and complete the access control tuple.
2677 // We ignore the access vector here because grants cannot be granted.
2678 // The access vector returned here expresses the permissions the
2679 // grantee has if key.domain == Domain::GRANT. But this vector
2680 // cannot include the grant permission by design, so there is no way the
2681 // subsequent permission check can pass.
2682 // We could check key.domain == Domain::GRANT and fail early.
2683 // But even if we load the access tuple by grant here, the permission
2684 // check denies the attempt to create a grant by grant descriptor.
2685 let (key_id, access_key_descriptor, _) =
2686 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2687 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002688
Janis Danisevskis66784c42021-01-27 08:40:25 -08002689 // Perform access control. It is vital that we return here if the permission
2690 // was denied. So do not touch that '?' at the end of the line.
2691 // This permission check checks if the caller has the grant permission
2692 // for the given key and in addition to all of the permissions
2693 // expressed in `access_vector`.
2694 check_permission(&access_key_descriptor, &access_vector)
2695 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002696
Janis Danisevskis66784c42021-01-27 08:40:25 -08002697 let grant_id = if let Some(grant_id) = tx
2698 .query_row(
2699 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002700 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002701 params![key_id, grantee_uid],
2702 |row| row.get(0),
2703 )
2704 .optional()
2705 .context("In grant: Failed get optional existing grant id.")?
2706 {
2707 tx.execute(
2708 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002709 SET access_vector = ?
2710 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002711 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002712 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08002713 .context("In grant: Failed to update existing grant.")?;
2714 grant_id
2715 } else {
2716 Self::insert_with_retry(|id| {
2717 tx.execute(
2718 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2719 VALUES (?, ?, ?, ?);",
2720 params![id, grantee_uid, key_id, i32::from(access_vector)],
2721 )
2722 })
2723 .context("In grant")?
2724 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002725
Janis Danisevskis66784c42021-01-27 08:40:25 -08002726 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002727 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002728 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002729 }
2730
2731 /// This function checks permissions like `grant` and `load_key_entry`
2732 /// before removing a grant from the grant table.
2733 pub fn ungrant(
2734 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002735 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002736 caller_uid: u32,
2737 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002738 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002739 ) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002740 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2741 // Load the key_id and complete the access control tuple.
2742 // We ignore the access vector here because grants cannot be granted.
2743 let (key_id, access_key_descriptor, _) =
2744 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2745 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002746
Janis Danisevskis66784c42021-01-27 08:40:25 -08002747 // Perform access control. We must return here if the permission
2748 // was denied. So do not touch the '?' at the end of this line.
2749 check_permission(&access_key_descriptor)
2750 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002751
Janis Danisevskis66784c42021-01-27 08:40:25 -08002752 tx.execute(
2753 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002754 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002755 params![key_id, grantee_uid],
2756 )
2757 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002758
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002759 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002760 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002761 }
2762
Joel Galenson845f74b2020-09-09 14:11:55 -07002763 // Generates a random id and passes it to the given function, which will
2764 // try to insert it into a database. If that insertion fails, retry;
2765 // otherwise return the id.
2766 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2767 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002768 let newid: i64 = match random() {
2769 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2770 i => i,
2771 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002772 match inserter(newid) {
2773 // If the id already existed, try again.
2774 Err(rusqlite::Error::SqliteFailure(
2775 libsqlite3_sys::Error {
2776 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2777 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2778 },
2779 _,
2780 )) => (),
2781 Err(e) => {
2782 return Err(e).context("In insert_with_retry: failed to insert into database.")
2783 }
2784 _ => return Ok(newid),
2785 }
2786 }
2787 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002788
2789 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
2790 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002791 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2792 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002793 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
2794 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
2795 params![
2796 auth_token.challenge,
2797 auth_token.userId,
2798 auth_token.authenticatorId,
2799 auth_token.authenticatorType.0 as i32,
2800 auth_token.timestamp.milliSeconds as i64,
2801 auth_token.mac,
2802 MonotonicRawTime::now(),
2803 ],
2804 )
2805 .context("In insert_auth_token: failed to insert auth token into the database")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002806 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002807 })
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002808 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002809
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002810 /// Find the newest auth token matching the given predicate.
2811 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002812 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002813 p: F,
2814 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
2815 where
2816 F: Fn(&AuthTokenEntry) -> bool,
2817 {
2818 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2819 let mut stmt = tx
2820 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
2821 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002822
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002823 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002824
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002825 while let Some(row) = rows.next().context("Failed to get next row.")? {
2826 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002827 HardwareAuthToken {
2828 challenge: row.get(1)?,
2829 userId: row.get(2)?,
2830 authenticatorId: row.get(3)?,
2831 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
2832 timestamp: Timestamp { milliSeconds: row.get(5)? },
2833 mac: row.get(6)?,
2834 },
2835 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002836 );
2837 if p(&entry) {
2838 return Ok(Some((
2839 entry,
2840 Self::get_last_off_body(tx)
2841 .context("In find_auth_token_entry: Trying to get last off body")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002842 )))
2843 .no_gc();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002844 }
2845 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002846 Ok(None).no_gc()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002847 })
2848 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002849 }
2850
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002851 /// Insert last_off_body into the metadata table at the initialization of auth token table
Janis Danisevskis66784c42021-01-27 08:40:25 -08002852 pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
2853 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2854 tx.execute(
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002855 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
2856 params!["last_off_body", last_off_body],
2857 )
2858 .context("In insert_last_off_body: failed to insert.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002859 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002860 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002861 }
2862
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002863 /// Update last_off_body when on_device_off_body is called
Janis Danisevskis66784c42021-01-27 08:40:25 -08002864 pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
2865 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2866 tx.execute(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002867 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
2868 params![last_off_body, "last_off_body"],
2869 )
2870 .context("In update_last_off_body: failed to update.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002871 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002872 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002873 }
2874
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002875 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002876 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002877 tx.query_row(
2878 "SELECT value from perboot.metadata WHERE key = ?;",
2879 params!["last_off_body"],
2880 |row| Ok(row.get(0)?),
2881 )
2882 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002883 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002884}
2885
2886#[cfg(test)]
2887mod tests {
2888
2889 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002890 use crate::key_parameter::{
2891 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2892 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2893 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002894 use crate::key_perm_set;
2895 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00002896 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002897 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002898 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2899 HardwareAuthToken::HardwareAuthToken,
2900 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002901 };
2902 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002903 Timestamp::Timestamp,
2904 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002905 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002906 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07002907 use std::cell::RefCell;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002908 use std::sync::atomic::{AtomicU8, Ordering};
2909 use std::sync::Arc;
2910 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002911 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08002912 #[cfg(disabled)]
2913 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002914
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002915 fn new_test_db() -> Result<KeystoreDB> {
2916 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
2917
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002918 let mut db = KeystoreDB { conn, gc: None };
Janis Danisevskis66784c42021-01-27 08:40:25 -08002919 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002920 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002921 })?;
2922 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002923 }
2924
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002925 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
2926 where
2927 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
2928 {
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002929 let super_key = Arc::new(SuperKeyManager::new());
2930
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002931 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002932 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002933
2934 KeystoreDB::new(path, Some(gc))
2935 }
2936
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002937 fn rebind_alias(
2938 db: &mut KeystoreDB,
2939 newid: &KeyIdGuard,
2940 alias: &str,
2941 domain: Domain,
2942 namespace: i64,
2943 ) -> Result<bool> {
2944 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002945 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002946 })
2947 .context("In rebind_alias.")
2948 }
2949
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002950 #[test]
2951 fn datetime() -> Result<()> {
2952 let conn = Connection::open_in_memory()?;
2953 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
2954 let now = SystemTime::now();
2955 let duration = Duration::from_secs(1000);
2956 let then = now.checked_sub(duration).unwrap();
2957 let soon = now.checked_add(duration).unwrap();
2958 conn.execute(
2959 "INSERT INTO test (ts) VALUES (?), (?), (?);",
2960 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
2961 )?;
2962 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
2963 let mut rows = stmt.query(NO_PARAMS)?;
2964 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
2965 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
2966 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
2967 assert!(rows.next()?.is_none());
2968 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
2969 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
2970 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
2971 Ok(())
2972 }
2973
Joel Galenson0891bc12020-07-20 10:37:03 -07002974 // Ensure that we're using the "injected" random function, not the real one.
2975 #[test]
2976 fn test_mocked_random() {
2977 let rand1 = random();
2978 let rand2 = random();
2979 let rand3 = random();
2980 if rand1 == rand2 {
2981 assert_eq!(rand2 + 1, rand3);
2982 } else {
2983 assert_eq!(rand1 + 1, rand2);
2984 assert_eq!(rand2, rand3);
2985 }
2986 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002987
Joel Galenson26f4d012020-07-17 14:57:21 -07002988 // Test that we have the correct tables.
2989 #[test]
2990 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002991 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07002992 let tables = db
2993 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07002994 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07002995 .query_map(params![], |row| row.get(0))?
2996 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002997 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002998 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002999 assert_eq!(tables[1], "blobmetadata");
3000 assert_eq!(tables[2], "grant");
3001 assert_eq!(tables[3], "keyentry");
3002 assert_eq!(tables[4], "keymetadata");
3003 assert_eq!(tables[5], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003004 let tables = db
3005 .conn
3006 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
3007 .query_map(params![], |row| row.get(0))?
3008 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003009
3010 assert_eq!(tables.len(), 2);
3011 assert_eq!(tables[0], "authtoken");
3012 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07003013 Ok(())
3014 }
3015
3016 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003017 fn test_auth_token_table_invariant() -> Result<()> {
3018 let mut db = new_test_db()?;
3019 let auth_token1 = HardwareAuthToken {
3020 challenge: i64::MAX,
3021 userId: 200,
3022 authenticatorId: 200,
3023 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3024 timestamp: Timestamp { milliSeconds: 500 },
3025 mac: String::from("mac").into_bytes(),
3026 };
3027 db.insert_auth_token(&auth_token1)?;
3028 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3029 assert_eq!(auth_tokens_returned.len(), 1);
3030
3031 // insert another auth token with the same values for the columns in the UNIQUE constraint
3032 // of the auth token table and different value for timestamp
3033 let auth_token2 = HardwareAuthToken {
3034 challenge: i64::MAX,
3035 userId: 200,
3036 authenticatorId: 200,
3037 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3038 timestamp: Timestamp { milliSeconds: 600 },
3039 mac: String::from("mac").into_bytes(),
3040 };
3041
3042 db.insert_auth_token(&auth_token2)?;
3043 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
3044 assert_eq!(auth_tokens_returned.len(), 1);
3045
3046 if let Some(auth_token) = auth_tokens_returned.pop() {
3047 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3048 }
3049
3050 // insert another auth token with the different values for the columns in the UNIQUE
3051 // constraint of the auth token table
3052 let auth_token3 = HardwareAuthToken {
3053 challenge: i64::MAX,
3054 userId: 201,
3055 authenticatorId: 200,
3056 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3057 timestamp: Timestamp { milliSeconds: 600 },
3058 mac: String::from("mac").into_bytes(),
3059 };
3060
3061 db.insert_auth_token(&auth_token3)?;
3062 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3063 assert_eq!(auth_tokens_returned.len(), 2);
3064
3065 Ok(())
3066 }
3067
3068 // utility function for test_auth_token_table_invariant()
3069 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
3070 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
3071
3072 let auth_token_entries: Vec<AuthTokenEntry> = stmt
3073 .query_map(NO_PARAMS, |row| {
3074 Ok(AuthTokenEntry::new(
3075 HardwareAuthToken {
3076 challenge: row.get(1)?,
3077 userId: row.get(2)?,
3078 authenticatorId: row.get(3)?,
3079 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3080 timestamp: Timestamp { milliSeconds: row.get(5)? },
3081 mac: row.get(6)?,
3082 },
3083 row.get(7)?,
3084 ))
3085 })?
3086 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
3087 Ok(auth_token_entries)
3088 }
3089
3090 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003091 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003092 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003093 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003094
Janis Danisevskis66784c42021-01-27 08:40:25 -08003095 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003096 let entries = get_keyentry(&db)?;
3097 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003098
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003099 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003100
3101 let entries_new = get_keyentry(&db)?;
3102 assert_eq!(entries, entries_new);
3103 Ok(())
3104 }
3105
3106 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003107 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003108 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3109 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003110 }
3111
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003112 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003113
Janis Danisevskis66784c42021-01-27 08:40:25 -08003114 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3115 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003116
3117 let entries = get_keyentry(&db)?;
3118 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003119 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3120 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003121
3122 // Test that we must pass in a valid Domain.
3123 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003124 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003125 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003126 );
3127 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003128 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003129 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003130 );
3131 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003132 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003133 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003134 );
3135
3136 Ok(())
3137 }
3138
Joel Galenson33c04ad2020-08-03 11:04:38 -07003139 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003140 fn test_add_unsigned_key() -> Result<()> {
3141 let mut db = new_test_db()?;
3142 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3143 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3144 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3145 db.create_attestation_key_entry(
3146 &public_key,
3147 &raw_public_key,
3148 &private_key,
3149 &KEYSTORE_UUID,
3150 )?;
3151 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3152 assert_eq!(keys.len(), 1);
3153 assert_eq!(keys[0], public_key);
3154 Ok(())
3155 }
3156
3157 #[test]
3158 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3159 let mut db = new_test_db()?;
3160 let expiration_date: i64 = 20;
3161 let namespace: i64 = 30;
3162 let base_byte: u8 = 1;
3163 let loaded_values =
3164 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3165 let chain =
3166 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3167 assert_eq!(true, chain.is_some());
3168 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003169 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
3170 assert_eq!(cert_chain.batch_cert.to_vec(), loaded_values.batch_cert);
3171 assert_eq!(cert_chain.cert_chain.to_vec(), loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003172 Ok(())
3173 }
3174
3175 #[test]
3176 fn test_get_attestation_pool_status() -> Result<()> {
3177 let mut db = new_test_db()?;
3178 let namespace: i64 = 30;
3179 load_attestation_key_pool(
3180 &mut db, 10, /* expiration */
3181 namespace, 0x01, /* base_byte */
3182 )?;
3183 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3184 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3185 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3186 assert_eq!(status.expiring, 0);
3187 assert_eq!(status.attested, 3);
3188 assert_eq!(status.unassigned, 0);
3189 assert_eq!(status.total, 3);
3190 assert_eq!(
3191 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3192 1
3193 );
3194 assert_eq!(
3195 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3196 2
3197 );
3198 assert_eq!(
3199 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3200 3
3201 );
3202 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3203 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3204 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3205 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003206 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003207 db.create_attestation_key_entry(
3208 &public_key,
3209 &raw_public_key,
3210 &private_key,
3211 &KEYSTORE_UUID,
3212 )?;
3213 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3214 assert_eq!(status.attested, 3);
3215 assert_eq!(status.unassigned, 0);
3216 assert_eq!(status.total, 4);
3217 db.store_signed_attestation_certificate_chain(
3218 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003219 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003220 &cert_chain,
3221 20,
3222 &KEYSTORE_UUID,
3223 )?;
3224 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3225 assert_eq!(status.attested, 4);
3226 assert_eq!(status.unassigned, 1);
3227 assert_eq!(status.total, 4);
3228 Ok(())
3229 }
3230
3231 #[test]
3232 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003233 let temp_dir =
3234 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3235 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003236 let expiration_date: i64 =
3237 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3238 let namespace: i64 = 30;
3239 let namespace_del1: i64 = 45;
3240 let namespace_del2: i64 = 60;
3241 let entry_values = load_attestation_key_pool(
3242 &mut db,
3243 expiration_date,
3244 namespace,
3245 0x01, /* base_byte */
3246 )?;
3247 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3248 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003249
3250 let blob_entry_row_count: u32 = db
3251 .conn
3252 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3253 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003254 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3255 // one key, one certificate chain, and one certificate.
3256 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003257
Max Bires2b2e6562020-09-22 11:22:36 -07003258 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3259
3260 let mut cert_chain =
3261 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003262 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003263 let value = cert_chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003264 assert_eq!(entry_values.batch_cert, value.batch_cert.to_vec());
3265 assert_eq!(entry_values.cert_chain, value.cert_chain.to_vec());
3266 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003267
3268 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3269 Domain::APP,
3270 namespace_del1,
3271 &KEYSTORE_UUID,
3272 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003273 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003274 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3275 Domain::APP,
3276 namespace_del2,
3277 &KEYSTORE_UUID,
3278 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003279 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003280
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003281 // Give the garbage collector half a second to catch up.
3282 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003283
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003284 let blob_entry_row_count: u32 = db
3285 .conn
3286 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3287 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003288 // There shound be 3 blob entries left, because we deleted two of the attestation
3289 // key entries with three blobs each.
3290 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003291
Max Bires2b2e6562020-09-22 11:22:36 -07003292 Ok(())
3293 }
3294
3295 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003296 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003297 fn extractor(
3298 ke: &KeyEntryRow,
3299 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3300 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003301 }
3302
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003303 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003304 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3305 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003306 let entries = get_keyentry(&db)?;
3307 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003308 assert_eq!(
3309 extractor(&entries[0]),
3310 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3311 );
3312 assert_eq!(
3313 extractor(&entries[1]),
3314 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3315 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003316
3317 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003318 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003319 let entries = get_keyentry(&db)?;
3320 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003321 assert_eq!(
3322 extractor(&entries[0]),
3323 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3324 );
3325 assert_eq!(
3326 extractor(&entries[1]),
3327 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3328 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003329
3330 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003331 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003332 let entries = get_keyentry(&db)?;
3333 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003334 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3335 assert_eq!(
3336 extractor(&entries[1]),
3337 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3338 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003339
3340 // Test that we must pass in a valid Domain.
3341 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003342 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003343 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003344 );
3345 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003346 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003347 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003348 );
3349 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003350 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003351 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003352 );
3353
3354 // Test that we correctly handle setting an alias for something that does not exist.
3355 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003356 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003357 "Expected to update a single entry but instead updated 0",
3358 );
3359 // Test that we correctly abort the transaction in this case.
3360 let entries = get_keyentry(&db)?;
3361 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003362 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3363 assert_eq!(
3364 extractor(&entries[1]),
3365 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3366 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003367
3368 Ok(())
3369 }
3370
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003371 #[test]
3372 fn test_grant_ungrant() -> Result<()> {
3373 const CALLER_UID: u32 = 15;
3374 const GRANTEE_UID: u32 = 12;
3375 const SELINUX_NAMESPACE: i64 = 7;
3376
3377 let mut db = new_test_db()?;
3378 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003379 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3380 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3381 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003382 )?;
3383 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003384 domain: super::Domain::APP,
3385 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003386 alias: Some("key".to_string()),
3387 blob: None,
3388 };
3389 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3390 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3391
3392 // Reset totally predictable random number generator in case we
3393 // are not the first test running on this thread.
3394 reset_random();
3395 let next_random = 0i64;
3396
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003397 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003398 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003399 assert_eq!(*a, PVEC1);
3400 assert_eq!(
3401 *k,
3402 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003403 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003404 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003405 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003406 alias: Some("key".to_string()),
3407 blob: None,
3408 }
3409 );
3410 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003411 })
3412 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003413
3414 assert_eq!(
3415 app_granted_key,
3416 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003417 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003418 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003419 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003420 alias: None,
3421 blob: None,
3422 }
3423 );
3424
3425 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003426 domain: super::Domain::SELINUX,
3427 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003428 alias: Some("yek".to_string()),
3429 blob: None,
3430 };
3431
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003432 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003433 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003434 assert_eq!(*a, PVEC1);
3435 assert_eq!(
3436 *k,
3437 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003438 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003439 // namespace must be the supplied SELinux
3440 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003441 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003442 alias: Some("yek".to_string()),
3443 blob: None,
3444 }
3445 );
3446 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003447 })
3448 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003449
3450 assert_eq!(
3451 selinux_granted_key,
3452 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003453 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003454 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003455 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003456 alias: None,
3457 blob: None,
3458 }
3459 );
3460
3461 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003462 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003463 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003464 assert_eq!(*a, PVEC2);
3465 assert_eq!(
3466 *k,
3467 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003468 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003469 // namespace must be the supplied SELinux
3470 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003471 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003472 alias: Some("yek".to_string()),
3473 blob: None,
3474 }
3475 );
3476 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003477 })
3478 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003479
3480 assert_eq!(
3481 selinux_granted_key,
3482 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003483 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003484 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003485 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003486 alias: None,
3487 blob: None,
3488 }
3489 );
3490
3491 {
3492 // Limiting scope of stmt, because it borrows db.
3493 let mut stmt = db
3494 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003495 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003496 let mut rows =
3497 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3498 Ok((
3499 row.get(0)?,
3500 row.get(1)?,
3501 row.get(2)?,
3502 KeyPermSet::from(row.get::<_, i32>(3)?),
3503 ))
3504 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003505
3506 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003507 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003508 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003509 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003510 assert!(rows.next().is_none());
3511 }
3512
3513 debug_dump_keyentry_table(&mut db)?;
3514 println!("app_key {:?}", app_key);
3515 println!("selinux_key {:?}", selinux_key);
3516
Janis Danisevskis66784c42021-01-27 08:40:25 -08003517 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3518 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003519
3520 Ok(())
3521 }
3522
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003523 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003524 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3525 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3526
3527 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003528 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003529 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003530 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003531 let mut blob_metadata = BlobMetaData::new();
3532 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3533 db.set_blob(
3534 &key_id,
3535 SubComponentType::KEY_BLOB,
3536 Some(TEST_KEY_BLOB),
3537 Some(&blob_metadata),
3538 )?;
3539 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3540 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003541 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003542
3543 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003544 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003545 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003546 )?;
3547 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003548 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3549 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003550 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003551 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003552 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003553 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003554 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003555 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003556 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003557
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003558 drop(rows);
3559 drop(stmt);
3560
3561 assert_eq!(
3562 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3563 BlobMetaData::load_from_db(id, tx).no_gc()
3564 })
3565 .expect("Should find blob metadata."),
3566 blob_metadata
3567 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003568 Ok(())
3569 }
3570
3571 static TEST_ALIAS: &str = "my super duper key";
3572
3573 #[test]
3574 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3575 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003576 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003577 .context("test_insert_and_load_full_keyentry_domain_app")?
3578 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003579 let (_key_guard, key_entry) = db
3580 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003581 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003582 domain: Domain::APP,
3583 nspace: 0,
3584 alias: Some(TEST_ALIAS.to_string()),
3585 blob: None,
3586 },
3587 KeyType::Client,
3588 KeyEntryLoadBits::BOTH,
3589 1,
3590 |_k, _av| Ok(()),
3591 )
3592 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003593 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003594
3595 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003596 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003597 domain: Domain::APP,
3598 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003599 alias: Some(TEST_ALIAS.to_string()),
3600 blob: None,
3601 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003602 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003603 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003604 |_, _| Ok(()),
3605 )
3606 .unwrap();
3607
3608 assert_eq!(
3609 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3610 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003611 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003612 domain: Domain::APP,
3613 nspace: 0,
3614 alias: Some(TEST_ALIAS.to_string()),
3615 blob: None,
3616 },
3617 KeyType::Client,
3618 KeyEntryLoadBits::NONE,
3619 1,
3620 |_k, _av| Ok(()),
3621 )
3622 .unwrap_err()
3623 .root_cause()
3624 .downcast_ref::<KsError>()
3625 );
3626
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003627 Ok(())
3628 }
3629
3630 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003631 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3632 let mut db = new_test_db()?;
3633
3634 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003635 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003636 domain: Domain::APP,
3637 nspace: 1,
3638 alias: Some(TEST_ALIAS.to_string()),
3639 blob: None,
3640 },
3641 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003642 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003643 )
3644 .expect("Trying to insert cert.");
3645
3646 let (_key_guard, mut key_entry) = db
3647 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003648 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003649 domain: Domain::APP,
3650 nspace: 1,
3651 alias: Some(TEST_ALIAS.to_string()),
3652 blob: None,
3653 },
3654 KeyType::Client,
3655 KeyEntryLoadBits::PUBLIC,
3656 1,
3657 |_k, _av| Ok(()),
3658 )
3659 .expect("Trying to read certificate entry.");
3660
3661 assert!(key_entry.pure_cert());
3662 assert!(key_entry.cert().is_none());
3663 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3664
3665 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003666 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003667 domain: Domain::APP,
3668 nspace: 1,
3669 alias: Some(TEST_ALIAS.to_string()),
3670 blob: None,
3671 },
3672 KeyType::Client,
3673 1,
3674 |_, _| Ok(()),
3675 )
3676 .unwrap();
3677
3678 assert_eq!(
3679 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3680 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003681 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003682 domain: Domain::APP,
3683 nspace: 1,
3684 alias: Some(TEST_ALIAS.to_string()),
3685 blob: None,
3686 },
3687 KeyType::Client,
3688 KeyEntryLoadBits::NONE,
3689 1,
3690 |_k, _av| Ok(()),
3691 )
3692 .unwrap_err()
3693 .root_cause()
3694 .downcast_ref::<KsError>()
3695 );
3696
3697 Ok(())
3698 }
3699
3700 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003701 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3702 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003703 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003704 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3705 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003706 let (_key_guard, key_entry) = db
3707 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003708 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003709 domain: Domain::SELINUX,
3710 nspace: 1,
3711 alias: Some(TEST_ALIAS.to_string()),
3712 blob: None,
3713 },
3714 KeyType::Client,
3715 KeyEntryLoadBits::BOTH,
3716 1,
3717 |_k, _av| Ok(()),
3718 )
3719 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003720 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003721
3722 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003723 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003724 domain: Domain::SELINUX,
3725 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003726 alias: Some(TEST_ALIAS.to_string()),
3727 blob: None,
3728 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003729 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003730 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003731 |_, _| Ok(()),
3732 )
3733 .unwrap();
3734
3735 assert_eq!(
3736 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3737 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003738 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003739 domain: Domain::SELINUX,
3740 nspace: 1,
3741 alias: Some(TEST_ALIAS.to_string()),
3742 blob: None,
3743 },
3744 KeyType::Client,
3745 KeyEntryLoadBits::NONE,
3746 1,
3747 |_k, _av| Ok(()),
3748 )
3749 .unwrap_err()
3750 .root_cause()
3751 .downcast_ref::<KsError>()
3752 );
3753
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003754 Ok(())
3755 }
3756
3757 #[test]
3758 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3759 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003760 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003761 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3762 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003763 let (_, key_entry) = db
3764 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003765 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003766 KeyType::Client,
3767 KeyEntryLoadBits::BOTH,
3768 1,
3769 |_k, _av| Ok(()),
3770 )
3771 .unwrap();
3772
Qi Wub9433b52020-12-01 14:52:46 +08003773 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003774
3775 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003776 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003777 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003778 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003779 |_, _| Ok(()),
3780 )
3781 .unwrap();
3782
3783 assert_eq!(
3784 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3785 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003786 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003787 KeyType::Client,
3788 KeyEntryLoadBits::NONE,
3789 1,
3790 |_k, _av| Ok(()),
3791 )
3792 .unwrap_err()
3793 .root_cause()
3794 .downcast_ref::<KsError>()
3795 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003796
3797 Ok(())
3798 }
3799
3800 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003801 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3802 let mut db = new_test_db()?;
3803 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3804 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3805 .0;
3806 // Update the usage count of the limited use key.
3807 db.check_and_update_key_usage_count(key_id)?;
3808
3809 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003810 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003811 KeyType::Client,
3812 KeyEntryLoadBits::BOTH,
3813 1,
3814 |_k, _av| Ok(()),
3815 )?;
3816
3817 // The usage count is decremented now.
3818 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3819
3820 Ok(())
3821 }
3822
3823 #[test]
3824 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3825 let mut db = new_test_db()?;
3826 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3827 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3828 .0;
3829 // Update the usage count of the limited use key.
3830 db.check_and_update_key_usage_count(key_id).expect(concat!(
3831 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3832 "This should succeed."
3833 ));
3834
3835 // Try to update the exhausted limited use key.
3836 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3837 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3838 "This should fail."
3839 ));
3840 assert_eq!(
3841 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3842 e.root_cause().downcast_ref::<KsError>().unwrap()
3843 );
3844
3845 Ok(())
3846 }
3847
3848 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003849 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3850 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003851 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003852 .context("test_insert_and_load_full_keyentry_from_grant")?
3853 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003854
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003855 let granted_key = db
3856 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003857 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003858 domain: Domain::APP,
3859 nspace: 0,
3860 alias: Some(TEST_ALIAS.to_string()),
3861 blob: None,
3862 },
3863 1,
3864 2,
3865 key_perm_set![KeyPerm::use_()],
3866 |_k, _av| Ok(()),
3867 )
3868 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003869
3870 debug_dump_grant_table(&mut db)?;
3871
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003872 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003873 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3874 assert_eq!(Domain::GRANT, k.domain);
3875 assert!(av.unwrap().includes(KeyPerm::use_()));
3876 Ok(())
3877 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003878 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003879
Qi Wub9433b52020-12-01 14:52:46 +08003880 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003881
Janis Danisevskis66784c42021-01-27 08:40:25 -08003882 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003883
3884 assert_eq!(
3885 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3886 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003887 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003888 KeyType::Client,
3889 KeyEntryLoadBits::NONE,
3890 2,
3891 |_k, _av| Ok(()),
3892 )
3893 .unwrap_err()
3894 .root_cause()
3895 .downcast_ref::<KsError>()
3896 );
3897
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003898 Ok(())
3899 }
3900
Janis Danisevskis45760022021-01-19 16:34:10 -08003901 // This test attempts to load a key by key id while the caller is not the owner
3902 // but a grant exists for the given key and the caller.
3903 #[test]
3904 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3905 let mut db = new_test_db()?;
3906 const OWNER_UID: u32 = 1u32;
3907 const GRANTEE_UID: u32 = 2u32;
3908 const SOMEONE_ELSE_UID: u32 = 3u32;
3909 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3910 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3911 .0;
3912
3913 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003914 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003915 domain: Domain::APP,
3916 nspace: 0,
3917 alias: Some(TEST_ALIAS.to_string()),
3918 blob: None,
3919 },
3920 OWNER_UID,
3921 GRANTEE_UID,
3922 key_perm_set![KeyPerm::use_()],
3923 |_k, _av| Ok(()),
3924 )
3925 .unwrap();
3926
3927 debug_dump_grant_table(&mut db)?;
3928
3929 let id_descriptor =
3930 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3931
3932 let (_, key_entry) = db
3933 .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::BOTH,
3937 GRANTEE_UID,
3938 |k, av| {
3939 assert_eq!(Domain::APP, k.domain);
3940 assert_eq!(OWNER_UID as i64, k.nspace);
3941 assert!(av.unwrap().includes(KeyPerm::use_()));
3942 Ok(())
3943 },
3944 )
3945 .unwrap();
3946
3947 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3948
3949 let (_, key_entry) = db
3950 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003951 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003952 KeyType::Client,
3953 KeyEntryLoadBits::BOTH,
3954 SOMEONE_ELSE_UID,
3955 |k, av| {
3956 assert_eq!(Domain::APP, k.domain);
3957 assert_eq!(OWNER_UID as i64, k.nspace);
3958 assert!(av.is_none());
3959 Ok(())
3960 },
3961 )
3962 .unwrap();
3963
3964 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3965
Janis Danisevskis66784c42021-01-27 08:40:25 -08003966 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003967
3968 assert_eq!(
3969 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3970 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003971 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003972 KeyType::Client,
3973 KeyEntryLoadBits::NONE,
3974 GRANTEE_UID,
3975 |_k, _av| Ok(()),
3976 )
3977 .unwrap_err()
3978 .root_cause()
3979 .downcast_ref::<KsError>()
3980 );
3981
3982 Ok(())
3983 }
3984
Janis Danisevskisaec14592020-11-12 09:41:49 -08003985 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
3986
Janis Danisevskisaec14592020-11-12 09:41:49 -08003987 #[test]
3988 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
3989 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003990 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
3991 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003992 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08003993 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003994 .context("test_insert_and_load_full_keyentry_domain_app")?
3995 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003996 let (_key_guard, key_entry) = db
3997 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003998 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003999 domain: Domain::APP,
4000 nspace: 0,
4001 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4002 blob: None,
4003 },
4004 KeyType::Client,
4005 KeyEntryLoadBits::BOTH,
4006 33,
4007 |_k, _av| Ok(()),
4008 )
4009 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004010 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004011 let state = Arc::new(AtomicU8::new(1));
4012 let state2 = state.clone();
4013
4014 // Spawning a second thread that attempts to acquire the key id lock
4015 // for the same key as the primary thread. The primary thread then
4016 // waits, thereby forcing the secondary thread into the second stage
4017 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4018 // The test succeeds if the secondary thread observes the transition
4019 // of `state` from 1 to 2, despite having a whole second to overtake
4020 // the primary thread.
4021 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004022 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004023 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004024 assert!(db
4025 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004026 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004027 domain: Domain::APP,
4028 nspace: 0,
4029 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4030 blob: None,
4031 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004032 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004033 KeyEntryLoadBits::BOTH,
4034 33,
4035 |_k, _av| Ok(()),
4036 )
4037 .is_ok());
4038 // We should only see a 2 here because we can only return
4039 // from load_key_entry when the `_key_guard` expires,
4040 // which happens at the end of the scope.
4041 assert_eq!(2, state2.load(Ordering::Relaxed));
4042 });
4043
4044 thread::sleep(std::time::Duration::from_millis(1000));
4045
4046 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4047
4048 // Return the handle from this scope so we can join with the
4049 // secondary thread after the key id lock has expired.
4050 handle
4051 // This is where the `_key_guard` goes out of scope,
4052 // which is the reason for concurrent load_key_entry on the same key
4053 // to unblock.
4054 };
4055 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4056 // main test thread. We will not see failing asserts in secondary threads otherwise.
4057 handle.join().unwrap();
4058 Ok(())
4059 }
4060
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004061 #[test]
Janis Danisevskis66784c42021-01-27 08:40:25 -08004062 fn teset_database_busy_error_code() {
4063 let temp_dir =
4064 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4065
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004066 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4067 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004068
4069 let _tx1 = db1
4070 .conn
4071 .transaction_with_behavior(TransactionBehavior::Immediate)
4072 .expect("Failed to create first transaction.");
4073
4074 let error = db2
4075 .conn
4076 .transaction_with_behavior(TransactionBehavior::Immediate)
4077 .context("Transaction begin failed.")
4078 .expect_err("This should fail.");
4079 let root_cause = error.root_cause();
4080 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4081 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4082 {
4083 return;
4084 }
4085 panic!(
4086 "Unexpected error {:?} \n{:?} \n{:?}",
4087 error,
4088 root_cause,
4089 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4090 )
4091 }
4092
4093 #[cfg(disabled)]
4094 #[test]
4095 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4096 let temp_dir = Arc::new(
4097 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4098 .expect("Failed to create temp dir."),
4099 );
4100
4101 let test_begin = Instant::now();
4102
4103 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4104 const KEY_COUNT: u32 = 500u32;
4105 const OPEN_DB_COUNT: u32 = 50u32;
4106
4107 let mut actual_key_count = KEY_COUNT;
4108 // First insert KEY_COUNT keys.
4109 for count in 0..KEY_COUNT {
4110 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4111 actual_key_count = count;
4112 break;
4113 }
4114 let alias = format!("test_alias_{}", count);
4115 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4116 .expect("Failed to make key entry.");
4117 }
4118
4119 // Insert more keys from a different thread and into a different namespace.
4120 let temp_dir1 = temp_dir.clone();
4121 let handle1 = thread::spawn(move || {
4122 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4123
4124 for count in 0..actual_key_count {
4125 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4126 return;
4127 }
4128 let alias = format!("test_alias_{}", count);
4129 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4130 .expect("Failed to make key entry.");
4131 }
4132
4133 // then unbind them again.
4134 for count in 0..actual_key_count {
4135 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4136 return;
4137 }
4138 let key = KeyDescriptor {
4139 domain: Domain::APP,
4140 nspace: -1,
4141 alias: Some(format!("test_alias_{}", count)),
4142 blob: None,
4143 };
4144 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4145 }
4146 });
4147
4148 // And start unbinding the first set of keys.
4149 let temp_dir2 = temp_dir.clone();
4150 let handle2 = thread::spawn(move || {
4151 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4152
4153 for count in 0..actual_key_count {
4154 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4155 return;
4156 }
4157 let key = KeyDescriptor {
4158 domain: Domain::APP,
4159 nspace: -1,
4160 alias: Some(format!("test_alias_{}", count)),
4161 blob: None,
4162 };
4163 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4164 }
4165 });
4166
4167 let stop_deleting = Arc::new(AtomicU8::new(0));
4168 let stop_deleting2 = stop_deleting.clone();
4169
4170 // And delete anything that is unreferenced keys.
4171 let temp_dir3 = temp_dir.clone();
4172 let handle3 = thread::spawn(move || {
4173 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4174
4175 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4176 while let Some((key_guard, _key)) =
4177 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4178 {
4179 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4180 return;
4181 }
4182 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4183 }
4184 std::thread::sleep(std::time::Duration::from_millis(100));
4185 }
4186 });
4187
4188 // While a lot of inserting and deleting is going on we have to open database connections
4189 // successfully and use them.
4190 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4191 // out of scope.
4192 #[allow(clippy::redundant_clone)]
4193 let temp_dir4 = temp_dir.clone();
4194 let handle4 = thread::spawn(move || {
4195 for count in 0..OPEN_DB_COUNT {
4196 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4197 return;
4198 }
4199 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4200
4201 let alias = format!("test_alias_{}", count);
4202 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4203 .expect("Failed to make key entry.");
4204 let key = KeyDescriptor {
4205 domain: Domain::APP,
4206 nspace: -1,
4207 alias: Some(alias),
4208 blob: None,
4209 };
4210 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4211 }
4212 });
4213
4214 handle1.join().expect("Thread 1 panicked.");
4215 handle2.join().expect("Thread 2 panicked.");
4216 handle4.join().expect("Thread 4 panicked.");
4217
4218 stop_deleting.store(1, Ordering::Relaxed);
4219 handle3.join().expect("Thread 3 panicked.");
4220
4221 Ok(())
4222 }
4223
4224 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004225 fn list() -> Result<()> {
4226 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004227 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004228 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4229 (Domain::APP, 1, "test1"),
4230 (Domain::APP, 1, "test2"),
4231 (Domain::APP, 1, "test3"),
4232 (Domain::APP, 1, "test4"),
4233 (Domain::APP, 1, "test5"),
4234 (Domain::APP, 1, "test6"),
4235 (Domain::APP, 1, "test7"),
4236 (Domain::APP, 2, "test1"),
4237 (Domain::APP, 2, "test2"),
4238 (Domain::APP, 2, "test3"),
4239 (Domain::APP, 2, "test4"),
4240 (Domain::APP, 2, "test5"),
4241 (Domain::APP, 2, "test6"),
4242 (Domain::APP, 2, "test8"),
4243 (Domain::SELINUX, 100, "test1"),
4244 (Domain::SELINUX, 100, "test2"),
4245 (Domain::SELINUX, 100, "test3"),
4246 (Domain::SELINUX, 100, "test4"),
4247 (Domain::SELINUX, 100, "test5"),
4248 (Domain::SELINUX, 100, "test6"),
4249 (Domain::SELINUX, 100, "test9"),
4250 ];
4251
4252 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4253 .iter()
4254 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004255 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4256 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004257 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4258 });
4259 (entry.id(), *ns)
4260 })
4261 .collect();
4262
4263 for (domain, namespace) in
4264 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4265 {
4266 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4267 .iter()
4268 .filter_map(|(domain, ns, alias)| match ns {
4269 ns if *ns == *namespace => Some(KeyDescriptor {
4270 domain: *domain,
4271 nspace: *ns,
4272 alias: Some(alias.to_string()),
4273 blob: None,
4274 }),
4275 _ => None,
4276 })
4277 .collect();
4278 list_o_descriptors.sort();
4279 let mut list_result = db.list(*domain, *namespace)?;
4280 list_result.sort();
4281 assert_eq!(list_o_descriptors, list_result);
4282
4283 let mut list_o_ids: Vec<i64> = list_o_descriptors
4284 .into_iter()
4285 .map(|d| {
4286 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004287 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004288 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004289 KeyType::Client,
4290 KeyEntryLoadBits::NONE,
4291 *namespace as u32,
4292 |_, _| Ok(()),
4293 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004294 .unwrap();
4295 entry.id()
4296 })
4297 .collect();
4298 list_o_ids.sort_unstable();
4299 let mut loaded_entries: Vec<i64> = list_o_keys
4300 .iter()
4301 .filter_map(|(id, ns)| match ns {
4302 ns if *ns == *namespace => Some(*id),
4303 _ => None,
4304 })
4305 .collect();
4306 loaded_entries.sort_unstable();
4307 assert_eq!(list_o_ids, loaded_entries);
4308 }
4309 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4310
4311 Ok(())
4312 }
4313
Joel Galenson0891bc12020-07-20 10:37:03 -07004314 // Helpers
4315
4316 // Checks that the given result is an error containing the given string.
4317 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4318 let error_str = format!(
4319 "{:#?}",
4320 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4321 );
4322 assert!(
4323 error_str.contains(target),
4324 "The string \"{}\" should contain \"{}\"",
4325 error_str,
4326 target
4327 );
4328 }
4329
Joel Galenson2aab4432020-07-22 15:27:57 -07004330 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004331 #[allow(dead_code)]
4332 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004333 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004334 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004335 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004336 namespace: Option<i64>,
4337 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004338 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004339 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004340 }
4341
4342 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4343 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004344 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004345 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004346 Ok(KeyEntryRow {
4347 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004348 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004349 domain: match row.get(2)? {
4350 Some(i) => Some(Domain(i)),
4351 None => None,
4352 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004353 namespace: row.get(3)?,
4354 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004355 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004356 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004357 })
4358 })?
4359 .map(|r| r.context("Could not read keyentry row."))
4360 .collect::<Result<Vec<_>>>()
4361 }
4362
Max Biresb2e1d032021-02-08 21:35:05 -08004363 struct RemoteProvValues {
4364 cert_chain: Vec<u8>,
4365 priv_key: Vec<u8>,
4366 batch_cert: Vec<u8>,
4367 }
4368
Max Bires2b2e6562020-09-22 11:22:36 -07004369 fn load_attestation_key_pool(
4370 db: &mut KeystoreDB,
4371 expiration_date: i64,
4372 namespace: i64,
4373 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004374 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004375 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4376 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4377 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4378 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004379 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004380 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4381 db.store_signed_attestation_certificate_chain(
4382 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004383 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004384 &cert_chain,
4385 expiration_date,
4386 &KEYSTORE_UUID,
4387 )?;
4388 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004389 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004390 }
4391
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004392 // Note: The parameters and SecurityLevel associations are nonsensical. This
4393 // collection is only used to check if the parameters are preserved as expected by the
4394 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004395 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4396 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004397 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4398 KeyParameter::new(
4399 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4400 SecurityLevel::TRUSTED_ENVIRONMENT,
4401 ),
4402 KeyParameter::new(
4403 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4404 SecurityLevel::TRUSTED_ENVIRONMENT,
4405 ),
4406 KeyParameter::new(
4407 KeyParameterValue::Algorithm(Algorithm::RSA),
4408 SecurityLevel::TRUSTED_ENVIRONMENT,
4409 ),
4410 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4411 KeyParameter::new(
4412 KeyParameterValue::BlockMode(BlockMode::ECB),
4413 SecurityLevel::TRUSTED_ENVIRONMENT,
4414 ),
4415 KeyParameter::new(
4416 KeyParameterValue::BlockMode(BlockMode::GCM),
4417 SecurityLevel::TRUSTED_ENVIRONMENT,
4418 ),
4419 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4420 KeyParameter::new(
4421 KeyParameterValue::Digest(Digest::MD5),
4422 SecurityLevel::TRUSTED_ENVIRONMENT,
4423 ),
4424 KeyParameter::new(
4425 KeyParameterValue::Digest(Digest::SHA_2_224),
4426 SecurityLevel::TRUSTED_ENVIRONMENT,
4427 ),
4428 KeyParameter::new(
4429 KeyParameterValue::Digest(Digest::SHA_2_256),
4430 SecurityLevel::STRONGBOX,
4431 ),
4432 KeyParameter::new(
4433 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4434 SecurityLevel::TRUSTED_ENVIRONMENT,
4435 ),
4436 KeyParameter::new(
4437 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4438 SecurityLevel::TRUSTED_ENVIRONMENT,
4439 ),
4440 KeyParameter::new(
4441 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4442 SecurityLevel::STRONGBOX,
4443 ),
4444 KeyParameter::new(
4445 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4446 SecurityLevel::TRUSTED_ENVIRONMENT,
4447 ),
4448 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4449 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4450 KeyParameter::new(
4451 KeyParameterValue::EcCurve(EcCurve::P_224),
4452 SecurityLevel::TRUSTED_ENVIRONMENT,
4453 ),
4454 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4455 KeyParameter::new(
4456 KeyParameterValue::EcCurve(EcCurve::P_384),
4457 SecurityLevel::TRUSTED_ENVIRONMENT,
4458 ),
4459 KeyParameter::new(
4460 KeyParameterValue::EcCurve(EcCurve::P_521),
4461 SecurityLevel::TRUSTED_ENVIRONMENT,
4462 ),
4463 KeyParameter::new(
4464 KeyParameterValue::RSAPublicExponent(3),
4465 SecurityLevel::TRUSTED_ENVIRONMENT,
4466 ),
4467 KeyParameter::new(
4468 KeyParameterValue::IncludeUniqueID,
4469 SecurityLevel::TRUSTED_ENVIRONMENT,
4470 ),
4471 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4472 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4473 KeyParameter::new(
4474 KeyParameterValue::ActiveDateTime(1234567890),
4475 SecurityLevel::STRONGBOX,
4476 ),
4477 KeyParameter::new(
4478 KeyParameterValue::OriginationExpireDateTime(1234567890),
4479 SecurityLevel::TRUSTED_ENVIRONMENT,
4480 ),
4481 KeyParameter::new(
4482 KeyParameterValue::UsageExpireDateTime(1234567890),
4483 SecurityLevel::TRUSTED_ENVIRONMENT,
4484 ),
4485 KeyParameter::new(
4486 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4487 SecurityLevel::TRUSTED_ENVIRONMENT,
4488 ),
4489 KeyParameter::new(
4490 KeyParameterValue::MaxUsesPerBoot(1234567890),
4491 SecurityLevel::TRUSTED_ENVIRONMENT,
4492 ),
4493 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4494 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4495 KeyParameter::new(
4496 KeyParameterValue::NoAuthRequired,
4497 SecurityLevel::TRUSTED_ENVIRONMENT,
4498 ),
4499 KeyParameter::new(
4500 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4501 SecurityLevel::TRUSTED_ENVIRONMENT,
4502 ),
4503 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4504 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4505 KeyParameter::new(
4506 KeyParameterValue::TrustedUserPresenceRequired,
4507 SecurityLevel::TRUSTED_ENVIRONMENT,
4508 ),
4509 KeyParameter::new(
4510 KeyParameterValue::TrustedConfirmationRequired,
4511 SecurityLevel::TRUSTED_ENVIRONMENT,
4512 ),
4513 KeyParameter::new(
4514 KeyParameterValue::UnlockedDeviceRequired,
4515 SecurityLevel::TRUSTED_ENVIRONMENT,
4516 ),
4517 KeyParameter::new(
4518 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4519 SecurityLevel::SOFTWARE,
4520 ),
4521 KeyParameter::new(
4522 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4523 SecurityLevel::SOFTWARE,
4524 ),
4525 KeyParameter::new(
4526 KeyParameterValue::CreationDateTime(12345677890),
4527 SecurityLevel::SOFTWARE,
4528 ),
4529 KeyParameter::new(
4530 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4531 SecurityLevel::TRUSTED_ENVIRONMENT,
4532 ),
4533 KeyParameter::new(
4534 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4535 SecurityLevel::TRUSTED_ENVIRONMENT,
4536 ),
4537 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4538 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4539 KeyParameter::new(
4540 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4541 SecurityLevel::SOFTWARE,
4542 ),
4543 KeyParameter::new(
4544 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4545 SecurityLevel::TRUSTED_ENVIRONMENT,
4546 ),
4547 KeyParameter::new(
4548 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4549 SecurityLevel::TRUSTED_ENVIRONMENT,
4550 ),
4551 KeyParameter::new(
4552 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4553 SecurityLevel::TRUSTED_ENVIRONMENT,
4554 ),
4555 KeyParameter::new(
4556 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4557 SecurityLevel::TRUSTED_ENVIRONMENT,
4558 ),
4559 KeyParameter::new(
4560 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4561 SecurityLevel::TRUSTED_ENVIRONMENT,
4562 ),
4563 KeyParameter::new(
4564 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4565 SecurityLevel::TRUSTED_ENVIRONMENT,
4566 ),
4567 KeyParameter::new(
4568 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4569 SecurityLevel::TRUSTED_ENVIRONMENT,
4570 ),
4571 KeyParameter::new(
4572 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4573 SecurityLevel::TRUSTED_ENVIRONMENT,
4574 ),
4575 KeyParameter::new(
4576 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4577 SecurityLevel::TRUSTED_ENVIRONMENT,
4578 ),
4579 KeyParameter::new(
4580 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4581 SecurityLevel::TRUSTED_ENVIRONMENT,
4582 ),
4583 KeyParameter::new(
4584 KeyParameterValue::VendorPatchLevel(3),
4585 SecurityLevel::TRUSTED_ENVIRONMENT,
4586 ),
4587 KeyParameter::new(
4588 KeyParameterValue::BootPatchLevel(4),
4589 SecurityLevel::TRUSTED_ENVIRONMENT,
4590 ),
4591 KeyParameter::new(
4592 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4593 SecurityLevel::TRUSTED_ENVIRONMENT,
4594 ),
4595 KeyParameter::new(
4596 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4597 SecurityLevel::TRUSTED_ENVIRONMENT,
4598 ),
4599 KeyParameter::new(
4600 KeyParameterValue::MacLength(256),
4601 SecurityLevel::TRUSTED_ENVIRONMENT,
4602 ),
4603 KeyParameter::new(
4604 KeyParameterValue::ResetSinceIdRotation,
4605 SecurityLevel::TRUSTED_ENVIRONMENT,
4606 ),
4607 KeyParameter::new(
4608 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4609 SecurityLevel::TRUSTED_ENVIRONMENT,
4610 ),
Qi Wub9433b52020-12-01 14:52:46 +08004611 ];
4612 if let Some(value) = max_usage_count {
4613 params.push(KeyParameter::new(
4614 KeyParameterValue::UsageCountLimit(value),
4615 SecurityLevel::SOFTWARE,
4616 ));
4617 }
4618 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004619 }
4620
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004621 fn make_test_key_entry(
4622 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004623 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004624 namespace: i64,
4625 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004626 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004627 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004628 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004629 let mut blob_metadata = BlobMetaData::new();
4630 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4631 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4632 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4633 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4634 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4635
4636 db.set_blob(
4637 &key_id,
4638 SubComponentType::KEY_BLOB,
4639 Some(TEST_KEY_BLOB),
4640 Some(&blob_metadata),
4641 )?;
4642 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4643 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004644
4645 let params = make_test_params(max_usage_count);
4646 db.insert_keyparameter(&key_id, &params)?;
4647
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004648 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004649 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004650 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004651 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004652 Ok(key_id)
4653 }
4654
Qi Wub9433b52020-12-01 14:52:46 +08004655 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4656 let params = make_test_params(max_usage_count);
4657
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004658 let mut blob_metadata = BlobMetaData::new();
4659 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4660 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4661 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4662 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4663 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4664
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004665 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004666 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004667
4668 KeyEntry {
4669 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004670 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004671 cert: Some(TEST_CERT_BLOB.to_vec()),
4672 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004673 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004674 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004675 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004676 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004677 }
4678 }
4679
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004680 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004681 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004682 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004683 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004684 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004685 NO_PARAMS,
4686 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004687 Ok((
4688 row.get(0)?,
4689 row.get(1)?,
4690 row.get(2)?,
4691 row.get(3)?,
4692 row.get(4)?,
4693 row.get(5)?,
4694 row.get(6)?,
4695 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004696 },
4697 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004698
4699 println!("Key entry table rows:");
4700 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004701 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004702 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004703 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4704 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004705 );
4706 }
4707 Ok(())
4708 }
4709
4710 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004711 let mut stmt = db
4712 .conn
4713 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004714 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
4715 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
4716 })?;
4717
4718 println!("Grant table rows:");
4719 for r in rows {
4720 let (id, gt, ki, av) = r.unwrap();
4721 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
4722 }
4723 Ok(())
4724 }
4725
Joel Galenson0891bc12020-07-20 10:37:03 -07004726 // Use a custom random number generator that repeats each number once.
4727 // This allows us to test repeated elements.
4728
4729 thread_local! {
4730 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
4731 }
4732
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004733 fn reset_random() {
4734 RANDOM_COUNTER.with(|counter| {
4735 *counter.borrow_mut() = 0;
4736 })
4737 }
4738
Joel Galenson0891bc12020-07-20 10:37:03 -07004739 pub fn random() -> i64 {
4740 RANDOM_COUNTER.with(|counter| {
4741 let result = *counter.borrow() / 2;
4742 *counter.borrow_mut() += 1;
4743 result
4744 })
4745 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004746
4747 #[test]
4748 fn test_last_off_body() -> Result<()> {
4749 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08004750 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004751 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
4752 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
4753 tx.commit()?;
4754 let one_second = Duration::from_secs(1);
4755 thread::sleep(one_second);
4756 db.update_last_off_body(MonotonicRawTime::now())?;
4757 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
4758 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
4759 tx2.commit()?;
4760 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
4761 Ok(())
4762 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00004763
4764 #[test]
4765 fn test_unbind_keys_for_user() -> Result<()> {
4766 let mut db = new_test_db()?;
4767 db.unbind_keys_for_user(1, false)?;
4768
4769 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
4770 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
4771 db.unbind_keys_for_user(2, false)?;
4772
4773 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
4774 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
4775
4776 db.unbind_keys_for_user(1, true)?;
4777 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
4778
4779 Ok(())
4780 }
4781
4782 #[test]
4783 fn test_store_super_key() -> Result<()> {
4784 let mut db = new_test_db()?;
4785 let pw = "xyzabc".as_bytes();
4786 let super_key = keystore2_crypto::generate_aes256_key()?;
4787 let secret = String::from("keystore2 is great.");
4788 let secret_bytes = secret.into_bytes();
4789 let (encrypted_secret, iv, tag) =
4790 keystore2_crypto::aes_gcm_encrypt(&secret_bytes, &super_key)?;
4791
4792 let (encrypted_super_key, metadata) =
4793 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
4794 db.store_super_key(1, &(&encrypted_super_key, &metadata))?;
4795
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00004796 //check if super key exists
4797 assert!(db.key_exists(Domain::APP, 1, "USER_SUPER_KEY", KeyType::Super)?);
4798
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00004799 let (_, key_entry) = db.load_super_key(1)?.unwrap();
Hasini Gunasingheda895552021-01-27 19:34:37 +00004800 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(key_entry, &pw)?;
4801
4802 let decrypted_secret_bytes = keystore2_crypto::aes_gcm_decrypt(
4803 &encrypted_secret,
4804 &iv,
4805 &tag,
4806 &loaded_super_key.get_key(),
4807 )?;
4808 let decrypted_secret = String::from_utf8((&decrypted_secret_bytes).to_vec())?;
4809 assert_eq!(String::from("keystore2 is great."), decrypted_secret);
4810 Ok(())
4811 }
Joel Galenson26f4d012020-07-17 14:57:21 -07004812}