blob: 785847db745a722410316453cfb10753b25aa236 [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
Janis Danisevskis4507f3b2021-01-13 16:34:39 -080044use crate::db_utils::{self, SqlField};
Qi Wub9433b52020-12-01 14:52:46 +080045use crate::error::{Error as KsError, ErrorCode, ResponseCode};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080046use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080047use crate::key_parameter::{KeyParameter, Tag};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070048use crate::permission::KeyPermSet;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +000049use crate::utils::get_current_time_in_seconds;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080050use anyhow::{anyhow, Context, Result};
51use std::{convert::TryFrom, convert::TryInto, time::SystemTimeError};
Janis Danisevskis60400fe2020-08-26 15:24:42 -070052
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000053use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080054 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000055 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080056};
57use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000058 Timestamp::Timestamp,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000059};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070060use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070061 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070062};
Janis Danisevskisaec14592020-11-12 09:41:49 -080063use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000064use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070065#[cfg(not(test))]
66use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070067use rusqlite::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080068 params,
69 types::FromSql,
70 types::FromSqlResult,
71 types::ToSqlOutput,
72 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080073 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070074};
Janis Danisevskisaec14592020-11-12 09:41:49 -080075use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080076 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080077 path::Path,
78 sync::{Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080079 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080080};
Joel Galenson0891bc12020-07-20 10:37:03 -070081#[cfg(test)]
82use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070083
Janis Danisevskisb42fc182020-12-15 08:41:27 -080084impl_metadata!(
85 /// A set of metadata for key entries.
86 #[derive(Debug, Default, Eq, PartialEq)]
87 pub struct KeyMetaData;
88 /// A metadata entry for key entries.
89 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
90 pub enum KeyMetaEntry {
91 /// If present, indicates that the sensitive part of key
92 /// is encrypted with another key or a key derived from a password.
93 EncryptedBy(EncryptedBy) with accessor encrypted_by,
94 /// If the blob is password encrypted this field is set to the
95 /// salt used for the key derivation.
96 Salt(Vec<u8>) with accessor salt,
97 /// If the blob is encrypted, this field is set to the initialization vector.
98 Iv(Vec<u8>) with accessor iv,
99 /// If the blob is encrypted, this field holds the AEAD TAG.
100 AeadTag(Vec<u8>) with accessor aead_tag,
101 /// Creation date of a the key entry.
102 CreationDate(DateTime) with accessor creation_date,
103 /// Expiration date for attestation keys.
104 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
105 // --- ADD NEW META DATA FIELDS HERE ---
106 // For backwards compatibility add new entries only to
107 // end of this list and above this comment.
108 };
109);
110
111impl KeyMetaData {
112 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
113 let mut stmt = tx
114 .prepare(
115 "SELECT tag, data from persistent.keymetadata
116 WHERE keyentryid = ?;",
117 )
118 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
119
120 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
121
122 let mut rows =
123 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
124 db_utils::with_rows_extract_all(&mut rows, |row| {
125 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
126 metadata.insert(
127 db_tag,
128 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
129 .context("Failed to read KeyMetaEntry.")?,
130 );
131 Ok(())
132 })
133 .context("In KeyMetaData::load_from_db.")?;
134
135 Ok(Self { data: metadata })
136 }
137
138 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
139 let mut stmt = tx
140 .prepare(
141 "INSERT into persistent.keymetadata (keyentryid, tag, data)
142 VALUES (?, ?, ?);",
143 )
144 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
145
146 let iter = self.data.iter();
147 for (tag, entry) in iter {
148 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
149 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
150 })?;
151 }
152 Ok(())
153 }
154}
155
156/// Indicates the type of the keyentry.
157#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
158pub enum KeyType {
159 /// This is a client key type. These keys are created or imported through the Keystore 2.0
160 /// AIDL interface android.system.keystore2.
161 Client,
162 /// This is a super key type. These keys are created by keystore itself and used to encrypt
163 /// other key blobs to provide LSKF binding.
164 Super,
165 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
166 Attestation,
167}
168
169impl ToSql for KeyType {
170 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
171 Ok(ToSqlOutput::Owned(Value::Integer(match self {
172 KeyType::Client => 0,
173 KeyType::Super => 1,
174 KeyType::Attestation => 2,
175 })))
176 }
177}
178
179impl FromSql for KeyType {
180 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
181 match i64::column_result(value)? {
182 0 => Ok(KeyType::Client),
183 1 => Ok(KeyType::Super),
184 2 => Ok(KeyType::Attestation),
185 v => Err(FromSqlError::OutOfRange(v)),
186 }
187 }
188}
189
190/// Indicates how the sensitive part of this key blob is encrypted.
191#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
192pub enum EncryptedBy {
193 /// The keyblob is encrypted by a user password.
194 /// In the database this variant is represented as NULL.
195 Password,
196 /// The keyblob is encrypted by another key with wrapped key id.
197 /// In the database this variant is represented as non NULL value
198 /// that is convertible to i64, typically NUMERIC.
199 KeyId(i64),
200}
201
202impl ToSql for EncryptedBy {
203 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
204 match self {
205 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
206 Self::KeyId(id) => id.to_sql(),
207 }
208 }
209}
210
211impl FromSql for EncryptedBy {
212 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
213 match value {
214 ValueRef::Null => Ok(Self::Password),
215 _ => Ok(Self::KeyId(i64::column_result(value)?)),
216 }
217 }
218}
219
220/// A database representation of wall clock time. DateTime stores unix epoch time as
221/// i64 in milliseconds.
222#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
223pub struct DateTime(i64);
224
225/// Error type returned when creating DateTime or converting it from and to
226/// SystemTime.
227#[derive(thiserror::Error, Debug)]
228pub enum DateTimeError {
229 /// This is returned when SystemTime and Duration computations fail.
230 #[error(transparent)]
231 SystemTimeError(#[from] SystemTimeError),
232
233 /// This is returned when type conversions fail.
234 #[error(transparent)]
235 TypeConversion(#[from] std::num::TryFromIntError),
236
237 /// This is returned when checked time arithmetic failed.
238 #[error("Time arithmetic failed.")]
239 TimeArithmetic,
240}
241
242impl DateTime {
243 /// Constructs a new DateTime object denoting the current time. This may fail during
244 /// conversion to unix epoch time and during conversion to the internal i64 representation.
245 pub fn now() -> Result<Self, DateTimeError> {
246 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
247 }
248
249 /// Constructs a new DateTime object from milliseconds.
250 pub fn from_millis_epoch(millis: i64) -> Self {
251 Self(millis)
252 }
253
254 /// Returns unix epoch time in milliseconds.
255 pub fn to_millis_epoch(&self) -> i64 {
256 self.0
257 }
258
259 /// Returns unix epoch time in seconds.
260 pub fn to_secs_epoch(&self) -> i64 {
261 self.0 / 1000
262 }
263}
264
265impl ToSql for DateTime {
266 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
267 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
268 }
269}
270
271impl FromSql for DateTime {
272 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
273 Ok(Self(i64::column_result(value)?))
274 }
275}
276
277impl TryInto<SystemTime> for DateTime {
278 type Error = DateTimeError;
279
280 fn try_into(self) -> Result<SystemTime, Self::Error> {
281 // We want to construct a SystemTime representation equivalent to self, denoting
282 // a point in time THEN, but we cannot set the time directly. We can only construct
283 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
284 // and between EPOCH and THEN. With this common reference we can construct the
285 // duration between NOW and THEN which we can add to our SystemTime representation
286 // of NOW to get a SystemTime representation of THEN.
287 // Durations can only be positive, thus the if statement below.
288 let now = SystemTime::now();
289 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
290 let then_epoch = Duration::from_millis(self.0.try_into()?);
291 Ok(if now_epoch > then_epoch {
292 // then = now - (now_epoch - then_epoch)
293 now_epoch
294 .checked_sub(then_epoch)
295 .and_then(|d| now.checked_sub(d))
296 .ok_or(DateTimeError::TimeArithmetic)?
297 } else {
298 // then = now + (then_epoch - now_epoch)
299 then_epoch
300 .checked_sub(now_epoch)
301 .and_then(|d| now.checked_add(d))
302 .ok_or(DateTimeError::TimeArithmetic)?
303 })
304 }
305}
306
307impl TryFrom<SystemTime> for DateTime {
308 type Error = DateTimeError;
309
310 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
311 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
312 }
313}
314
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800315#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
316enum KeyLifeCycle {
317 /// Existing keys have a key ID but are not fully populated yet.
318 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
319 /// them to Unreferenced for garbage collection.
320 Existing,
321 /// A live key is fully populated and usable by clients.
322 Live,
323 /// An unreferenced key is scheduled for garbage collection.
324 Unreferenced,
325}
326
327impl ToSql for KeyLifeCycle {
328 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
329 match self {
330 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
331 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
332 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
333 }
334 }
335}
336
337impl FromSql for KeyLifeCycle {
338 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
339 match i64::column_result(value)? {
340 0 => Ok(KeyLifeCycle::Existing),
341 1 => Ok(KeyLifeCycle::Live),
342 2 => Ok(KeyLifeCycle::Unreferenced),
343 v => Err(FromSqlError::OutOfRange(v)),
344 }
345 }
346}
347
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700348/// Keys have a KeyMint blob component and optional public certificate and
349/// certificate chain components.
350/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
351/// which components shall be loaded from the database if present.
352#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
353pub struct KeyEntryLoadBits(u32);
354
355impl KeyEntryLoadBits {
356 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
357 pub const NONE: KeyEntryLoadBits = Self(0);
358 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
359 pub const KM: KeyEntryLoadBits = Self(1);
360 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
361 pub const PUBLIC: KeyEntryLoadBits = Self(2);
362 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
363 pub const BOTH: KeyEntryLoadBits = Self(3);
364
365 /// Returns true if this object indicates that the public components shall be loaded.
366 pub const fn load_public(&self) -> bool {
367 self.0 & Self::PUBLIC.0 != 0
368 }
369
370 /// Returns true if the object indicates that the KeyMint component shall be loaded.
371 pub const fn load_km(&self) -> bool {
372 self.0 & Self::KM.0 != 0
373 }
374}
375
Janis Danisevskisaec14592020-11-12 09:41:49 -0800376lazy_static! {
377 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
378}
379
380struct KeyIdLockDb {
381 locked_keys: Mutex<HashSet<i64>>,
382 cond_var: Condvar,
383}
384
385/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
386/// from the database a second time. Most functions manipulating the key blob database
387/// require a KeyIdGuard.
388#[derive(Debug)]
389pub struct KeyIdGuard(i64);
390
391impl KeyIdLockDb {
392 fn new() -> Self {
393 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
394 }
395
396 /// This function blocks until an exclusive lock for the given key entry id can
397 /// be acquired. It returns a guard object, that represents the lifecycle of the
398 /// acquired lock.
399 pub fn get(&self, key_id: i64) -> KeyIdGuard {
400 let mut locked_keys = self.locked_keys.lock().unwrap();
401 while locked_keys.contains(&key_id) {
402 locked_keys = self.cond_var.wait(locked_keys).unwrap();
403 }
404 locked_keys.insert(key_id);
405 KeyIdGuard(key_id)
406 }
407
408 /// This function attempts to acquire an exclusive lock on a given key id. If the
409 /// given key id is already taken the function returns None immediately. If a lock
410 /// can be acquired this function returns a guard object, that represents the
411 /// lifecycle of the acquired lock.
412 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
413 let mut locked_keys = self.locked_keys.lock().unwrap();
414 if locked_keys.insert(key_id) {
415 Some(KeyIdGuard(key_id))
416 } else {
417 None
418 }
419 }
420}
421
422impl KeyIdGuard {
423 /// Get the numeric key id of the locked key.
424 pub fn id(&self) -> i64 {
425 self.0
426 }
427}
428
429impl Drop for KeyIdGuard {
430 fn drop(&mut self) {
431 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
432 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800433 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800434 KEY_ID_LOCK.cond_var.notify_all();
435 }
436}
437
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700438/// This type represents a Keystore 2.0 key entry.
439/// An entry has a unique `id` by which it can be found in the database.
440/// It has a security level field, key parameters, and three optional fields
441/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800442#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700443pub struct KeyEntry {
444 id: i64,
445 km_blob: Option<Vec<u8>>,
446 cert: Option<Vec<u8>>,
447 cert_chain: Option<Vec<u8>>,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700448 sec_level: SecurityLevel,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700449 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800450 metadata: KeyMetaData,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700451}
452
453impl KeyEntry {
454 /// Returns the unique id of the Key entry.
455 pub fn id(&self) -> i64 {
456 self.id
457 }
458 /// Exposes the optional KeyMint blob.
459 pub fn km_blob(&self) -> &Option<Vec<u8>> {
460 &self.km_blob
461 }
462 /// Extracts the Optional KeyMint blob.
463 pub fn take_km_blob(&mut self) -> Option<Vec<u8>> {
464 self.km_blob.take()
465 }
466 /// Exposes the optional public certificate.
467 pub fn cert(&self) -> &Option<Vec<u8>> {
468 &self.cert
469 }
470 /// Extracts the optional public certificate.
471 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
472 self.cert.take()
473 }
474 /// Exposes the optional public certificate chain.
475 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
476 &self.cert_chain
477 }
478 /// Extracts the optional public certificate_chain.
479 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
480 self.cert_chain.take()
481 }
482 /// Returns the security level of the key entry.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700483 pub fn sec_level(&self) -> SecurityLevel {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700484 self.sec_level
485 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700486 /// Exposes the key parameters of this key entry.
487 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
488 &self.parameters
489 }
490 /// Consumes this key entry and extracts the keyparameters from it.
491 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
492 self.parameters
493 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800494 /// Exposes the key metadata of this key entry.
495 pub fn metadata(&self) -> &KeyMetaData {
496 &self.metadata
497 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700498}
499
500/// Indicates the sub component of a key entry for persistent storage.
501#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
502pub struct SubComponentType(u32);
503impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800504 /// Persistent identifier for a key blob.
505 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700506 /// Persistent identifier for a certificate blob.
507 pub const CERT: SubComponentType = Self(1);
508 /// Persistent identifier for a certificate chain blob.
509 pub const CERT_CHAIN: SubComponentType = Self(2);
510}
511
512impl ToSql for SubComponentType {
513 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
514 self.0.to_sql()
515 }
516}
517
518impl FromSql for SubComponentType {
519 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
520 Ok(Self(u32::column_result(value)?))
521 }
522}
523
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700524/// KeystoreDB wraps a connection to an SQLite database and tracks its
525/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700526pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700527 conn: Connection,
528}
529
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000530/// Database representation of the monotonic time retrieved from the system call clock_gettime with
531/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds.
532#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
533pub struct MonotonicRawTime(i64);
534
535impl MonotonicRawTime {
536 /// Constructs a new MonotonicRawTime
537 pub fn now() -> Self {
538 Self(get_current_time_in_seconds())
539 }
540
541 /// Returns the integer value of MonotonicRawTime as i64
542 pub fn seconds(&self) -> i64 {
543 self.0
544 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800545
546 /// Like i64::checked_sub.
547 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
548 self.0.checked_sub(other.0).map(Self)
549 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000550}
551
552impl ToSql for MonotonicRawTime {
553 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
554 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
555 }
556}
557
558impl FromSql for MonotonicRawTime {
559 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
560 Ok(Self(i64::column_result(value)?))
561 }
562}
563
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000564/// This struct encapsulates the information to be stored in the database about the auth tokens
565/// received by keystore.
566pub struct AuthTokenEntry {
567 auth_token: HardwareAuthToken,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000568 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000569}
570
571impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000572 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000573 AuthTokenEntry { auth_token, time_received }
574 }
575
576 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800577 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000578 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800579 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
580 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000581 })
582 }
583
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000584 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800585 pub fn auth_token(&self) -> &HardwareAuthToken {
586 &self.auth_token
587 }
588
589 /// Returns the auth token wrapped by the AuthTokenEntry
590 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000591 self.auth_token
592 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800593
594 /// Returns the time that this auth token was received.
595 pub fn time_received(&self) -> MonotonicRawTime {
596 self.time_received
597 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000598}
599
Joel Galenson26f4d012020-07-17 14:57:21 -0700600impl KeystoreDB {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700601 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800602 /// files persistent.sqlite and perboot.sqlite in the given directory.
603 /// It also attempts to initialize all of the tables.
604 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700605 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800606 pub fn new(db_root: &Path) -> Result<Self> {
607 // Build the path to the sqlite files.
608 let mut persistent_path = db_root.to_path_buf();
609 persistent_path.push("persistent.sqlite");
610 let mut perboot_path = db_root.to_path_buf();
611 perboot_path.push("perboot.sqlite");
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700612
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800613 // Now convert them to strings prefixed with "file:"
614 let mut persistent_path_str = "file:".to_owned();
615 persistent_path_str.push_str(&persistent_path.to_string_lossy());
616 let mut perboot_path_str = "file:".to_owned();
617 perboot_path_str.push_str(&perboot_path.to_string_lossy());
618
619 let conn = Self::make_connection(&persistent_path_str, &perboot_path_str)?;
620
621 Self::init_tables(&conn)?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700622 Ok(Self { conn })
Joel Galenson2aab4432020-07-22 15:27:57 -0700623 }
624
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700625 fn init_tables(conn: &Connection) -> Result<()> {
626 conn.execute(
627 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700628 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800629 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700630 domain INTEGER,
631 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800632 alias BLOB,
633 state INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700634 NO_PARAMS,
635 )
636 .context("Failed to initialize \"keyentry\" table.")?;
637
638 conn.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700639 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
640 id INTEGER PRIMARY KEY,
641 subcomponent_type INTEGER,
642 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800643 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700644 NO_PARAMS,
645 )
646 .context("Failed to initialize \"blobentry\" table.")?;
647
648 conn.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700649 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000650 keyentryid INTEGER,
651 tag INTEGER,
652 data ANY,
653 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700654 NO_PARAMS,
655 )
656 .context("Failed to initialize \"keyparameter\" table.")?;
657
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700658 conn.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800659 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
660 keyentryid INTEGER,
661 tag INTEGER,
662 data ANY);",
663 NO_PARAMS,
664 )
665 .context("Failed to initialize \"keymetadata\" table.")?;
666
667 conn.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800668 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700669 id INTEGER UNIQUE,
670 grantee INTEGER,
671 keyentryid INTEGER,
672 access_vector INTEGER);",
673 NO_PARAMS,
674 )
675 .context("Failed to initialize \"grant\" table.")?;
676
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000677 //TODO: only drop the following two perboot tables if this is the first start up
678 //during the boot (b/175716626).
679 // conn.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS)
680 // .context("Failed to drop perboot.authtoken table")?;
681 conn.execute(
682 "CREATE TABLE IF NOT EXISTS perboot.authtoken (
683 id INTEGER PRIMARY KEY,
684 challenge INTEGER,
685 user_id INTEGER,
686 auth_id INTEGER,
687 authenticator_type INTEGER,
688 timestamp INTEGER,
689 mac BLOB,
690 time_received INTEGER,
691 UNIQUE(user_id, auth_id, authenticator_type));",
692 NO_PARAMS,
693 )
694 .context("Failed to initialize \"authtoken\" table.")?;
695
696 // conn.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS)
697 // .context("Failed to drop perboot.metadata table")?;
698 // metadata table stores certain miscellaneous information required for keystore functioning
699 // during a boot cycle, as key-value pairs.
700 conn.execute(
701 "CREATE TABLE IF NOT EXISTS perboot.metadata (
702 key TEXT,
703 value BLOB,
704 UNIQUE(key));",
705 NO_PARAMS,
706 )
707 .context("Failed to initialize \"metadata\" table.")?;
Joel Galenson0891bc12020-07-20 10:37:03 -0700708 Ok(())
709 }
710
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700711 fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> {
712 let conn =
713 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
714
715 conn.execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
716 .context("Failed to attach database persistent.")?;
717 conn.execute("ATTACH DATABASE ? as perboot;", params![perboot_file])
718 .context("Failed to attach database perboot.")?;
719
720 Ok(conn)
721 }
722
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800723 /// Get one unreferenced key. There is no particular order in which the keys are returned.
724 fn get_unreferenced_key_id(tx: &Transaction) -> Result<Option<i64>> {
725 tx.query_row(
726 "SELECT id FROM persistent.keyentry WHERE state = ?",
727 params![KeyLifeCycle::Unreferenced],
728 |row| row.get(0),
729 )
730 .optional()
731 .context("In get_unreferenced_key_id: Trying to get unreferenced key id.")
732 }
733
734 /// Returns a key id guard and key entry for one unreferenced key entry. Of the optional
735 /// fields of the key entry only the km_blob field will be populated. This is required
736 /// to subject the blob to its KeyMint instance for deletion.
737 pub fn get_unreferenced_key(&mut self) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
738 self.with_transaction(TransactionBehavior::Deferred, |tx| {
739 let key_id = match Self::get_unreferenced_key_id(tx)
740 .context("Trying to get unreferenced key id")?
741 {
742 None => return Ok(None),
743 Some(id) => KEY_ID_LOCK.try_get(id).ok_or_else(KsError::sys).context(concat!(
744 "A key id lock was held for an unreferenced key. ",
745 "This should never happen."
746 ))?,
747 };
748 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id.id())
749 .context("Trying to get key components.")?;
750 Ok(Some((key_id, key_entry)))
751 })
752 .context("In get_unreferenced_key.")
753 }
754
755 /// This function purges all remnants of a key entry from the database.
756 /// Important: This does not check if the key was unreferenced, nor does it
757 /// subject the key to its KeyMint instance for permanent invalidation.
758 /// This function should only be called by the garbage collector.
759 /// To delete a key call `mark_unreferenced`, which transitions the key to the unreferenced
760 /// state, deletes all grants to the key, and notifies the garbage collector.
761 /// The garbage collector will:
762 /// 1. Call get_unreferenced_key.
763 /// 2. Determine the proper way to dispose of sensitive key material, e.g., call
764 /// `KeyMintDevice::delete()`.
765 /// 3. Call `purge_key_entry`.
766 pub fn purge_key_entry(&mut self, key_id: KeyIdGuard) -> Result<()> {
767 self.with_transaction(TransactionBehavior::Immediate, |tx| {
768 tx.execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id.id()])
769 .context("Trying to delete keyentry.")?;
770 tx.execute(
771 "DELETE FROM persistent.blobentry WHERE keyentryid = ?;",
772 params![key_id.id()],
773 )
774 .context("Trying to delete blobentries.")?;
775 tx.execute(
776 "DELETE FROM persistent.keymetadata WHERE keyentryid = ?;",
777 params![key_id.id()],
778 )
779 .context("Trying to delete keymetadata.")?;
780 tx.execute(
781 "DELETE FROM persistent.keyparameter WHERE keyentryid = ?;",
782 params![key_id.id()],
783 )
784 .context("Trying to delete keyparameters.")?;
785 let grants_deleted = tx
786 .execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id.id()])
787 .context("Trying to delete grants.")?;
788 if grants_deleted != 0 {
789 log::error!("Purged key that still had grants. This should not happen.");
790 }
791 Ok(())
792 })
793 .context("In purge_key_entry.")
794 }
795
796 /// This maintenance function should be called only once before the database is used for the
797 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
798 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
799 /// returns the number of rows affected. If this returns a value greater than 0, it means that
800 /// Keystore crashed at some point during key generation. Callers may want to log such
801 /// occurrences.
802 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
803 /// it to `KeyLifeCycle::Live` may have grants.
804 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
805 self.conn
806 .execute(
807 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
808 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
809 )
810 .context("In cleanup_leftovers.")
811 }
812
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800813 /// Atomically loads a key entry and associated metadata or creates it using the
814 /// callback create_new_key callback. The callback is called during a database
815 /// transaction. This means that implementers should be mindful about using
816 /// blocking operations such as IPC or grabbing mutexes.
817 pub fn get_or_create_key_with<F>(
818 &mut self,
819 domain: Domain,
820 namespace: i64,
821 alias: &str,
822 create_new_key: F,
823 ) -> Result<(KeyIdGuard, KeyEntry)>
824 where
825 F: FnOnce() -> Result<(Vec<u8>, KeyMetaData)>,
826 {
827 let tx = self
828 .conn
829 .transaction_with_behavior(TransactionBehavior::Immediate)
830 .context("In get_or_create_key_with: Failed to initialize transaction.")?;
831
832 let id = {
833 let mut stmt = tx
834 .prepare(
835 "SELECT id FROM persistent.keyentry
836 WHERE
837 key_type = ?
838 AND domain = ?
839 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800840 AND alias = ?
841 AND state = ?;",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800842 )
843 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
844 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800845 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800846 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
847
848 db_utils::with_rows_extract_one(&mut rows, |row| {
849 Ok(match row {
850 Some(r) => r.get(0).context("Failed to unpack id.")?,
851 None => None,
852 })
853 })
854 .context("In get_or_create_key_with.")?
855 };
856
857 let (id, entry) = match id {
858 Some(id) => (
859 id,
860 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
861 .context("In get_or_create_key_with.")?,
862 ),
863
864 None => {
865 let id = Self::insert_with_retry(|id| {
866 tx.execute(
867 "INSERT into persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800868 (id, key_type, domain, namespace, alias, state)
869 VALUES(?, ?, ?, ?, ?, ?);",
870 params![id, KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live],
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800871 )
872 })
873 .context("In get_or_create_key_with.")?;
874
875 let (blob, metadata) = create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800876 Self::insert_blob_internal(&tx, id, SubComponentType::KEY_BLOB, &blob)
877 .context("In get_of_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800878 metadata.store_in_db(id, &tx).context("In get_or_create_key_with.")?;
879 (id, KeyEntry { id, km_blob: Some(blob), metadata, ..Default::default() })
880 }
881 };
882 tx.commit().context("In get_or_create_key_with: Failed to commit transaction.")?;
883 Ok((KEY_ID_LOCK.get(id), entry))
884 }
885
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800886 /// Creates a transaction with the given behavior and executes f with the new transaction.
887 /// The transaction is committed only if f returns Ok.
888 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
889 where
890 F: FnOnce(&Transaction) -> Result<T>,
891 {
892 let tx = self
893 .conn
894 .transaction_with_behavior(behavior)
895 .context("In with_transaction: Failed to initialize transaction.")?;
896 f(&tx).and_then(|result| {
897 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
898 Ok(result)
899 })
900 }
901
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700902 /// Creates a new key entry and allocates a new randomized id for the new key.
903 /// The key id gets associated with a domain and namespace but not with an alias.
904 /// To complete key generation `rebind_alias` should be called after all of the
905 /// key artifacts, i.e., blobs and parameters have been associated with the new
906 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
907 /// atomic even if key generation is not.
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800908 pub fn create_key_entry(&mut self, domain: Domain, namespace: i64) -> Result<KeyIdGuard> {
909 self.with_transaction(TransactionBehavior::Immediate, |tx| {
910 Self::create_key_entry_internal(tx, domain, namespace)
911 })
912 .context("In create_key_entry.")
913 }
914
915 fn create_key_entry_internal(
916 tx: &Transaction,
917 domain: Domain,
918 namespace: i64,
919 ) -> Result<KeyIdGuard> {
Joel Galenson0891bc12020-07-20 10:37:03 -0700920 match domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -0700921 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -0700922 _ => {
923 return Err(KsError::sys())
924 .context(format!("Domain {:?} must be either App or SELinux.", domain));
925 }
926 }
Janis Danisevskisaec14592020-11-12 09:41:49 -0800927 Ok(KEY_ID_LOCK.get(
928 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800929 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800930 "INSERT into persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800931 (id, key_type, domain, namespace, alias, state)
932 VALUES(?, ?, ?, ?, NULL, ?);",
933 params![
934 id,
935 KeyType::Client,
936 domain.0 as u32,
937 namespace,
938 KeyLifeCycle::Existing
939 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -0800940 )
941 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800942 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800943 ))
Joel Galenson26f4d012020-07-17 14:57:21 -0700944 }
Joel Galenson33c04ad2020-08-03 11:04:38 -0700945
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700946 /// Inserts a new blob and associates it with the given key id. Each blob
947 /// has a sub component type and a security level.
948 /// Each key can have one of each sub component type associated. If more
949 /// are added only the most recent can be retrieved, and superseded blobs
950 /// will get garbage collected. The security level field of components
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800951 /// other than `SubComponentType::KEY_BLOB` are ignored.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700952 pub fn insert_blob(
953 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800954 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700955 sc_type: SubComponentType,
956 blob: &[u8],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700957 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800958 self.with_transaction(TransactionBehavior::Immediate, |tx| {
959 Self::insert_blob_internal(&tx, key_id.0, sc_type, blob)
960 })
961 .context("In insert_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800962 }
963
964 fn insert_blob_internal(
965 tx: &Transaction,
966 key_id: i64,
967 sc_type: SubComponentType,
968 blob: &[u8],
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800969 ) -> Result<()> {
970 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800971 "INSERT into persistent.blobentry (subcomponent_type, keyentryid, blob)
972 VALUES (?, ?, ?);",
973 params![sc_type, key_id, blob],
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800974 )
975 .context("In insert_blob_internal: Failed to insert blob.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700976 Ok(())
977 }
978
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700979 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
980 /// and associates them with the given `key_id`.
981 pub fn insert_keyparameter<'a>(
982 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -0800983 key_id: &KeyIdGuard,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700984 params: impl IntoIterator<Item = &'a KeyParameter>,
985 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800986 self.with_transaction(TransactionBehavior::Immediate, |tx| {
987 Self::insert_keyparameter_internal(tx, key_id, params)
988 })
989 .context("In insert_keyparameter.")
990 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700991
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800992 fn insert_keyparameter_internal<'a>(
993 tx: &Transaction,
994 key_id: &KeyIdGuard,
995 params: impl IntoIterator<Item = &'a KeyParameter>,
996 ) -> Result<()> {
997 let mut stmt = tx
998 .prepare(
999 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1000 VALUES (?, ?, ?, ?);",
1001 )
1002 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1003
1004 let iter = params.into_iter();
1005 for p in iter {
1006 stmt.insert(params![
1007 key_id.0,
1008 p.get_tag().0,
1009 p.key_parameter_value(),
1010 p.security_level().0
1011 ])
1012 .with_context(|| {
1013 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1014 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001015 }
1016 Ok(())
1017 }
1018
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001019 /// Insert a set of key entry specific metadata into the database.
1020 pub fn insert_key_metadata(
1021 &mut self,
1022 key_id: &KeyIdGuard,
1023 metadata: &KeyMetaData,
1024 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001025 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1026 metadata.store_in_db(key_id.0, &tx)
1027 })
1028 .context("In insert_key_metadata.")
1029 }
1030
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001031 /// Updates the alias column of the given key id `newid` with the given alias,
1032 /// and atomically, removes the alias, domain, and namespace from another row
1033 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001034 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1035 /// collector.
1036 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001037 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001038 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001039 alias: &str,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001040 domain: Domain,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001041 namespace: i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001042 ) -> Result<bool> {
Joel Galenson33c04ad2020-08-03 11:04:38 -07001043 match domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001044 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001045 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001046 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001047 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001048 domain
1049 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001050 }
1051 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001052 let updated = tx
1053 .execute(
1054 "UPDATE persistent.keyentry
1055 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07001056 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001057 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
1058 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001059 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001060 let result = tx
1061 .execute(
1062 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001063 SET alias = ?, state = ?
1064 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
1065 params![
1066 alias,
1067 KeyLifeCycle::Live,
1068 newid.0,
1069 domain.0 as u32,
1070 namespace,
1071 KeyLifeCycle::Existing
1072 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001073 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001074 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001075 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07001076 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001077 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001078 result
1079 ));
1080 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001081 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001082 }
1083
1084 /// Store a new key in a single transaction.
1085 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1086 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001087 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1088 /// is now unreferenced and needs to be collected.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001089 pub fn store_new_key<'a>(
1090 &mut self,
1091 key: KeyDescriptor,
1092 params: impl IntoIterator<Item = &'a KeyParameter>,
1093 blob: &[u8],
1094 cert: Option<&[u8]>,
1095 cert_chain: Option<&[u8]>,
1096 metadata: &KeyMetaData,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001097 ) -> Result<(bool, KeyIdGuard)> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001098 let (alias, domain, namespace) = match key {
1099 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1100 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1101 (alias, key.domain, nspace)
1102 }
1103 _ => {
1104 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1105 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
1106 }
1107 };
1108 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1109 let key_id = Self::create_key_entry_internal(tx, domain, namespace)
1110 .context("Trying to create new key entry.")?;
1111 Self::insert_blob_internal(tx, key_id.id(), SubComponentType::KEY_BLOB, blob)
1112 .context("Trying to insert the key blob.")?;
1113 if let Some(cert) = cert {
1114 Self::insert_blob_internal(tx, key_id.id(), SubComponentType::CERT, cert)
1115 .context("Trying to insert the certificate.")?;
1116 }
1117 if let Some(cert_chain) = cert_chain {
1118 Self::insert_blob_internal(
1119 tx,
1120 key_id.id(),
1121 SubComponentType::CERT_CHAIN,
1122 cert_chain,
1123 )
1124 .context("Trying to insert the certificate chain.")?;
1125 }
1126 Self::insert_keyparameter_internal(tx, &key_id, params)
1127 .context("Trying to insert key parameters.")?;
1128 metadata.store_in_db(key_id.id(), tx).context("Tryin to insert key metadata.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001129 let need_gc = Self::rebind_alias(tx, &key_id, &alias, domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001130 .context("Trying to rebind alias.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001131 Ok((need_gc, key_id))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001132 })
1133 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001134 }
1135
1136 // Helper function loading the key_id given the key descriptor
1137 // tuple comprising domain, namespace, and alias.
1138 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001139 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001140 let alias = key
1141 .alias
1142 .as_ref()
1143 .map_or_else(|| Err(KsError::sys()), Ok)
1144 .context("In load_key_entry_id: Alias must be specified.")?;
1145 let mut stmt = tx
1146 .prepare(
1147 "SELECT id FROM persistent.keyentry
1148 WHERE
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001149 key_type = ?
1150 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001151 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001152 AND alias = ?
1153 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001154 )
1155 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1156 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001157 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001158 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001159 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001160 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001161 .get(0)
1162 .context("Failed to unpack id.")
1163 })
1164 .context("In load_key_entry_id.")
1165 }
1166
1167 /// This helper function completes the access tuple of a key, which is required
1168 /// to perform access control. The strategy depends on the `domain` field in the
1169 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001170 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001171 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001172 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001173 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001174 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001175 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001176 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001177 /// `namespace`.
1178 /// In each case the information returned is sufficient to perform the access
1179 /// check and the key id can be used to load further key artifacts.
1180 fn load_access_tuple(
1181 tx: &Transaction,
1182 key: KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001183 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001184 caller_uid: u32,
1185 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
1186 match key.domain {
1187 // Domain App or SELinux. In this case we load the key_id from
1188 // the keyentry database for further loading of key components.
1189 // We already have the full access tuple to perform access control.
1190 // The only distinction is that we use the caller_uid instead
1191 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001192 // Domain::APP.
1193 Domain::APP | Domain::SELINUX => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001194 let mut access_key = key;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001195 if access_key.domain == Domain::APP {
1196 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001197 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001198 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001199 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001200
1201 Ok((key_id, access_key, None))
1202 }
1203
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001204 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001205 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001206 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001207 let mut stmt = tx
1208 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001209 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001210 WHERE grantee = ? AND id = ?;",
1211 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001212 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001213 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001214 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001215 .context("Domain:Grant: query failed.")?;
1216 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001217 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001218 let r =
1219 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001220 Ok((
1221 r.get(0).context("Failed to unpack key_id.")?,
1222 r.get(1).context("Failed to unpack access_vector.")?,
1223 ))
1224 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001225 .context("Domain::GRANT.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001226 Ok((key_id, key, Some(access_vector.into())))
1227 }
1228
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001229 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001230 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001231 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08001232 let (domain, namespace): (Domain, i64) = {
1233 let mut stmt = tx
1234 .prepare(
1235 "SELECT domain, namespace FROM persistent.keyentry
1236 WHERE
1237 id = ?
1238 AND state = ?;",
1239 )
1240 .context("Domain::KEY_ID: prepare statement failed")?;
1241 let mut rows = stmt
1242 .query(params![key.nspace, KeyLifeCycle::Live])
1243 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001244 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001245 let r =
1246 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001247 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001248 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001249 r.get(1).context("Failed to unpack namespace.")?,
1250 ))
1251 })
Janis Danisevskis45760022021-01-19 16:34:10 -08001252 .context("Domain::KEY_ID.")?
1253 };
1254
1255 // We may use a key by id after loading it by grant.
1256 // In this case we have to check if the caller has a grant for this particular
1257 // key. We can skip this if we already know that the caller is the owner.
1258 // But we cannot know this if domain is anything but App. E.g. in the case
1259 // of Domain::SELINUX we have to speculatively check for grants because we have to
1260 // consult the SEPolicy before we know if the caller is the owner.
1261 let access_vector: Option<KeyPermSet> =
1262 if domain != Domain::APP || namespace != caller_uid as i64 {
1263 let access_vector: Option<i32> = tx
1264 .query_row(
1265 "SELECT access_vector FROM persistent.grant
1266 WHERE grantee = ? AND keyentryid = ?;",
1267 params![caller_uid as i64, key.nspace],
1268 |row| row.get(0),
1269 )
1270 .optional()
1271 .context("Domain::KEY_ID: query grant failed.")?;
1272 access_vector.map(|p| p.into())
1273 } else {
1274 None
1275 };
1276
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001277 let key_id = key.nspace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001278 let mut access_key = key;
1279 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001280 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001281
Janis Danisevskis45760022021-01-19 16:34:10 -08001282 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001283 }
1284 _ => Err(anyhow!(KsError::sys())),
1285 }
1286 }
1287
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001288 fn load_blob_components(
1289 key_id: i64,
1290 load_bits: KeyEntryLoadBits,
1291 tx: &Transaction,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001292 ) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001293 let mut stmt = tx
1294 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001295 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001296 WHERE keyentryid = ? GROUP BY subcomponent_type;",
1297 )
1298 .context("In load_blob_components: prepare statement failed.")?;
1299
1300 let mut rows =
1301 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
1302
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001303 let mut km_blob: Option<Vec<u8>> = None;
1304 let mut cert_blob: Option<Vec<u8>> = None;
1305 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001306 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001307 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001308 row.get(1).context("Failed to extract subcomponent_type.")?;
1309 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
1310 (SubComponentType::KEY_BLOB, _, true) => {
1311 km_blob = Some(row.get(2).context("Failed to extract KM blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001312 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001313 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001314 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001315 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001316 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001317 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001318 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001319 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001320 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001321 (SubComponentType::CERT, _, _)
1322 | (SubComponentType::CERT_CHAIN, _, _)
1323 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001324 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
1325 }
1326 Ok(())
1327 })
1328 .context("In load_blob_components.")?;
1329
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001330 Ok((km_blob, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001331 }
1332
1333 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
1334 let mut stmt = tx
1335 .prepare(
1336 "SELECT tag, data, security_level from persistent.keyparameter
1337 WHERE keyentryid = ?;",
1338 )
1339 .context("In load_key_parameters: prepare statement failed.")?;
1340
1341 let mut parameters: Vec<KeyParameter> = Vec::new();
1342
1343 let mut rows =
1344 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001345 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001346 let tag = Tag(row.get(0).context("Failed to read tag.")?);
1347 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001348 parameters.push(
1349 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
1350 .context("Failed to read KeyParameter.")?,
1351 );
1352 Ok(())
1353 })
1354 .context("In load_key_parameters.")?;
1355
1356 Ok(parameters)
1357 }
1358
Qi Wub9433b52020-12-01 14:52:46 +08001359 /// Decrements the usage count of a limited use key. This function first checks whether the
1360 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
1361 /// zero, the key also gets marked unreferenced and scheduled for deletion.
1362 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
1363 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<bool> {
1364 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1365 let limit: Option<i32> = tx
1366 .query_row(
1367 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
1368 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
1369 |row| row.get(0),
1370 )
1371 .optional()
1372 .context("Trying to load usage count")?;
1373
1374 let limit = limit
1375 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
1376 .context("The Key no longer exists. Key is exhausted.")?;
1377
1378 tx.execute(
1379 "UPDATE persistent.keyparameter
1380 SET data = data - 1
1381 WHERE keyentryid = ? AND tag = ? AND data > 0;",
1382 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
1383 )
1384 .context("Failed to update key usage count.")?;
1385
1386 match limit {
1387 1 => Self::mark_unreferenced(tx, key_id)
1388 .context("Trying to mark limited use key for deletion."),
1389 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
1390 _ => Ok(false),
1391 }
1392 })
1393 .context("In check_and_update_key_usage_count.")
1394 }
1395
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001396 /// Load a key entry by the given key descriptor.
1397 /// It uses the `check_permission` callback to verify if the access is allowed
1398 /// given the key access tuple read from the database using `load_access_tuple`.
1399 /// With `load_bits` the caller may specify which blobs shall be loaded from
1400 /// the blob database.
1401 pub fn load_key_entry(
1402 &mut self,
1403 key: KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001404 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001405 load_bits: KeyEntryLoadBits,
1406 caller_uid: u32,
1407 check_permission: impl FnOnce(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001408 ) -> Result<(KeyIdGuard, KeyEntry)> {
1409 // KEY ID LOCK 1/2
1410 // If we got a key descriptor with a key id we can get the lock right away.
1411 // Otherwise we have to defer it until we know the key id.
1412 let key_id_guard = match key.domain {
1413 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
1414 _ => None,
1415 };
1416
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001417 let tx = self
1418 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08001419 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001420 .context("In load_key_entry: Failed to initialize transaction.")?;
1421
1422 // Load the key_id and complete the access control tuple.
1423 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001424 Self::load_access_tuple(&tx, key, key_type, caller_uid)
1425 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001426
1427 // Perform access control. It is vital that we return here if the permission is denied.
1428 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001429 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001430
Janis Danisevskisaec14592020-11-12 09:41:49 -08001431 // KEY ID LOCK 2/2
1432 // If we did not get a key id lock by now, it was because we got a key descriptor
1433 // without a key id. At this point we got the key id, so we can try and get a lock.
1434 // However, we cannot block here, because we are in the middle of the transaction.
1435 // So first we try to get the lock non blocking. If that fails, we roll back the
1436 // transaction and block until we get the lock. After we successfully got the lock,
1437 // we start a new transaction and load the access tuple again.
1438 //
1439 // We don't need to perform access control again, because we already established
1440 // that the caller had access to the given key. But we need to make sure that the
1441 // key id still exists. So we have to load the key entry by key id this time.
1442 let (key_id_guard, tx) = match key_id_guard {
1443 None => match KEY_ID_LOCK.try_get(key_id) {
1444 None => {
1445 // Roll back the transaction.
1446 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001447
Janis Danisevskisaec14592020-11-12 09:41:49 -08001448 // Block until we have a key id lock.
1449 let key_id_guard = KEY_ID_LOCK.get(key_id);
1450
1451 // Create a new transaction.
1452 let tx = self.conn.unchecked_transaction().context(
1453 "In load_key_entry: Failed to initialize transaction. (deferred key lock)",
1454 )?;
1455
1456 Self::load_access_tuple(
1457 &tx,
1458 // This time we have to load the key by the retrieved key id, because the
1459 // alias may have been rebound after we rolled back the transaction.
1460 KeyDescriptor {
1461 domain: Domain::KEY_ID,
1462 nspace: key_id,
1463 ..Default::default()
1464 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001465 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001466 caller_uid,
1467 )
1468 .context("In load_key_entry. (deferred key lock)")?;
1469 (key_id_guard, tx)
1470 }
1471 Some(l) => (l, tx),
1472 },
1473 Some(key_id_guard) => (key_id_guard, tx),
1474 };
1475
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001476 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
1477 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001478
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001479 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
1480
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001481 Ok((key_id_guard, key_entry))
1482 }
1483
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001484 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001485 let updated = tx
1486 .execute(
1487 "UPDATE persistent.keyentry SET state = ? WHERE id = ?;",
1488 params![KeyLifeCycle::Unreferenced, key_id],
1489 )
1490 .context("In mark_unreferenced: Failed to update state of key entry.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001491 tx.execute("DELETE from persistent.grant WHERE keyentryid = ?;", params![key_id])
1492 .context("In mark_unreferenced: Failed to drop grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001493 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001494 }
1495
1496 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001497 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001498 pub fn unbind_key(
1499 &mut self,
1500 key: KeyDescriptor,
1501 key_type: KeyType,
1502 caller_uid: u32,
1503 check_permission: impl FnOnce(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001504 ) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001505 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1506 let (key_id, access_key_descriptor, access_vector) =
1507 Self::load_access_tuple(tx, key, key_type, caller_uid)
1508 .context("Trying to get access tuple.")?;
1509
1510 // Perform access control. It is vital that we return here if the permission is denied.
1511 // So do not touch that '?' at the end.
1512 check_permission(&access_key_descriptor, access_vector)
1513 .context("While checking permission.")?;
1514
1515 Self::mark_unreferenced(tx, key_id).context("Trying to mark the key unreferenced.")
1516 })
1517 .context("In unbind_key.")
1518 }
1519
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001520 fn load_key_components(
1521 tx: &Transaction,
1522 load_bits: KeyEntryLoadBits,
1523 key_id: i64,
1524 ) -> Result<KeyEntry> {
1525 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
1526
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001527 let (km_blob, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001528 Self::load_blob_components(key_id, load_bits, &tx)
1529 .context("In load_key_components.")?;
1530
1531 let parameters =
1532 Self::load_key_parameters(key_id, &tx).context("In load_key_components.")?;
1533
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001534 // Extract the security level by checking the security level of the origin tag.
1535 // Super keys don't have key parameters so we use security_level software by default.
1536 let sec_level = parameters
1537 .iter()
1538 .find_map(|k| match k.get_tag() {
1539 Tag::ORIGIN => Some(*k.security_level()),
1540 _ => None,
1541 })
1542 .unwrap_or(SecurityLevel::SOFTWARE);
1543
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001544 Ok(KeyEntry {
1545 id: key_id,
1546 km_blob,
1547 cert: cert_blob,
1548 cert_chain: cert_chain_blob,
1549 sec_level,
1550 parameters,
1551 metadata,
1552 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001553 }
1554
Janis Danisevskise92a5e62020-12-02 12:57:41 -08001555 /// Returns a list of KeyDescriptors in the selected domain/namespace.
1556 /// The key descriptors will have the domain, nspace, and alias field set.
1557 /// Domain must be APP or SELINUX, the caller must make sure of that.
1558 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
1559 let mut stmt = self
1560 .conn
1561 .prepare(
1562 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001563 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskise92a5e62020-12-02 12:57:41 -08001564 )
1565 .context("In list: Failed to prepare.")?;
1566
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001567 let mut rows = stmt
1568 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
1569 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08001570
1571 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
1572 db_utils::with_rows_extract_all(&mut rows, |row| {
1573 descriptors.push(KeyDescriptor {
1574 domain,
1575 nspace: namespace,
1576 alias: Some(row.get(0).context("Trying to extract alias.")?),
1577 blob: None,
1578 });
1579 Ok(())
1580 })
1581 .context("In list.")?;
1582 Ok(descriptors)
1583 }
1584
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001585 /// Adds a grant to the grant table.
1586 /// Like `load_key_entry` this function loads the access tuple before
1587 /// it uses the callback for a permission check. Upon success,
1588 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
1589 /// grant table. The new row will have a randomized id, which is used as
1590 /// grant id in the namespace field of the resulting KeyDescriptor.
1591 pub fn grant(
1592 &mut self,
1593 key: KeyDescriptor,
1594 caller_uid: u32,
1595 grantee_uid: u32,
1596 access_vector: KeyPermSet,
1597 check_permission: impl FnOnce(&KeyDescriptor, &KeyPermSet) -> Result<()>,
1598 ) -> Result<KeyDescriptor> {
1599 let tx = self
1600 .conn
1601 .transaction_with_behavior(TransactionBehavior::Immediate)
1602 .context("In grant: Failed to initialize transaction.")?;
1603
1604 // Load the key_id and complete the access control tuple.
1605 // We ignore the access vector here because grants cannot be granted.
1606 // The access vector returned here expresses the permissions the
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001607 // grantee has if key.domain == Domain::GRANT. But this vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001608 // cannot include the grant permission by design, so there is no way the
1609 // subsequent permission check can pass.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001610 // We could check key.domain == Domain::GRANT and fail early.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001611 // But even if we load the access tuple by grant here, the permission
1612 // check denies the attempt to create a grant by grant descriptor.
1613 let (key_id, access_key_descriptor, _) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001614 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid).context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001615
1616 // Perform access control. It is vital that we return here if the permission
1617 // was denied. So do not touch that '?' at the end of the line.
1618 // This permission check checks if the caller has the grant permission
1619 // for the given key and in addition to all of the permissions
1620 // expressed in `access_vector`.
1621 check_permission(&access_key_descriptor, &access_vector)
1622 .context("In grant: check_permission failed.")?;
1623
1624 let grant_id = if let Some(grant_id) = tx
1625 .query_row(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001626 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001627 WHERE keyentryid = ? AND grantee = ?;",
1628 params![key_id, grantee_uid],
1629 |row| row.get(0),
1630 )
1631 .optional()
1632 .context("In grant: Failed get optional existing grant id.")?
1633 {
1634 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001635 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001636 SET access_vector = ?
1637 WHERE id = ?;",
1638 params![i32::from(access_vector), grant_id],
1639 )
1640 .context("In grant: Failed to update existing grant.")?;
1641 grant_id
1642 } else {
Joel Galenson845f74b2020-09-09 14:11:55 -07001643 Self::insert_with_retry(|id| {
1644 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001645 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001646 VALUES (?, ?, ?, ?);",
Joel Galenson845f74b2020-09-09 14:11:55 -07001647 params![id, grantee_uid, key_id, i32::from(access_vector)],
1648 )
1649 })
1650 .context("In grant")?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001651 };
1652 tx.commit().context("In grant: failed to commit transaction.")?;
1653
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001654 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001655 }
1656
1657 /// This function checks permissions like `grant` and `load_key_entry`
1658 /// before removing a grant from the grant table.
1659 pub fn ungrant(
1660 &mut self,
1661 key: KeyDescriptor,
1662 caller_uid: u32,
1663 grantee_uid: u32,
1664 check_permission: impl FnOnce(&KeyDescriptor) -> Result<()>,
1665 ) -> Result<()> {
1666 let tx = self
1667 .conn
1668 .transaction_with_behavior(TransactionBehavior::Immediate)
1669 .context("In ungrant: Failed to initialize transaction.")?;
1670
1671 // Load the key_id and complete the access control tuple.
1672 // We ignore the access vector here because grants cannot be granted.
1673 let (key_id, access_key_descriptor, _) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001674 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
1675 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001676
1677 // Perform access control. We must return here if the permission
1678 // was denied. So do not touch the '?' at the end of this line.
1679 check_permission(&access_key_descriptor).context("In grant: check_permission failed.")?;
1680
1681 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001682 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001683 WHERE keyentryid = ? AND grantee = ?;",
1684 params![key_id, grantee_uid],
1685 )
1686 .context("Failed to delete grant.")?;
1687
1688 tx.commit().context("In ungrant: failed to commit transaction.")?;
1689
1690 Ok(())
1691 }
1692
Joel Galenson845f74b2020-09-09 14:11:55 -07001693 // Generates a random id and passes it to the given function, which will
1694 // try to insert it into a database. If that insertion fails, retry;
1695 // otherwise return the id.
1696 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
1697 loop {
1698 let newid: i64 = random();
1699 match inserter(newid) {
1700 // If the id already existed, try again.
1701 Err(rusqlite::Error::SqliteFailure(
1702 libsqlite3_sys::Error {
1703 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
1704 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
1705 },
1706 _,
1707 )) => (),
1708 Err(e) => {
1709 return Err(e).context("In insert_with_retry: failed to insert into database.")
1710 }
1711 _ => return Ok(newid),
1712 }
1713 }
1714 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001715
1716 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
1717 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
1718 self.conn
1719 .execute(
1720 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
1721 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
1722 params![
1723 auth_token.challenge,
1724 auth_token.userId,
1725 auth_token.authenticatorId,
1726 auth_token.authenticatorType.0 as i32,
1727 auth_token.timestamp.milliSeconds as i64,
1728 auth_token.mac,
1729 MonotonicRawTime::now(),
1730 ],
1731 )
1732 .context("In insert_auth_token: failed to insert auth token into the database")?;
1733 Ok(())
1734 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001735
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001736 /// Find the newest auth token matching the given predicate.
1737 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001738 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001739 p: F,
1740 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
1741 where
1742 F: Fn(&AuthTokenEntry) -> bool,
1743 {
1744 self.with_transaction(TransactionBehavior::Deferred, |tx| {
1745 let mut stmt = tx
1746 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
1747 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001748
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001749 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001750
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001751 while let Some(row) = rows.next().context("Failed to get next row.")? {
1752 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001753 HardwareAuthToken {
1754 challenge: row.get(1)?,
1755 userId: row.get(2)?,
1756 authenticatorId: row.get(3)?,
1757 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
1758 timestamp: Timestamp { milliSeconds: row.get(5)? },
1759 mac: row.get(6)?,
1760 },
1761 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001762 );
1763 if p(&entry) {
1764 return Ok(Some((
1765 entry,
1766 Self::get_last_off_body(tx)
1767 .context("In find_auth_token_entry: Trying to get last off body")?,
1768 )));
1769 }
1770 }
1771 Ok(None)
1772 })
1773 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001774 }
1775
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001776 /// Insert last_off_body into the metadata table at the initialization of auth token table
1777 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) -> Result<()> {
1778 self.conn
1779 .execute(
1780 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
1781 params!["last_off_body", last_off_body],
1782 )
1783 .context("In insert_last_off_body: failed to insert.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001784 Ok(())
1785 }
1786
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001787 /// Update last_off_body when on_device_off_body is called
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001788 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) -> Result<()> {
1789 self.conn
1790 .execute(
1791 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
1792 params![last_off_body, "last_off_body"],
1793 )
1794 .context("In update_last_off_body: failed to update.")?;
1795 Ok(())
1796 }
1797
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001798 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001799 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001800 tx.query_row(
1801 "SELECT value from perboot.metadata WHERE key = ?;",
1802 params!["last_off_body"],
1803 |row| Ok(row.get(0)?),
1804 )
1805 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001806 }
Joel Galenson26f4d012020-07-17 14:57:21 -07001807}
1808
1809#[cfg(test)]
1810mod tests {
1811
1812 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001813 use crate::key_parameter::{
1814 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
1815 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
1816 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001817 use crate::key_perm_set;
1818 use crate::permission::{KeyPerm, KeyPermSet};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08001819 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001820 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
1821 HardwareAuthToken::HardwareAuthToken,
1822 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08001823 };
1824 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001825 Timestamp::Timestamp,
1826 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001827 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001828 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07001829 use std::cell::RefCell;
Janis Danisevskisaec14592020-11-12 09:41:49 -08001830 use std::sync::atomic::{AtomicU8, Ordering};
1831 use std::sync::Arc;
1832 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001833 use std::time::{Duration, SystemTime};
Joel Galenson0891bc12020-07-20 10:37:03 -07001834
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001835 fn new_test_db() -> Result<KeystoreDB> {
1836 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
1837
1838 KeystoreDB::init_tables(&conn).context("Failed to initialize tables.")?;
1839 Ok(KeystoreDB { conn })
1840 }
1841
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001842 fn rebind_alias(
1843 db: &mut KeystoreDB,
1844 newid: &KeyIdGuard,
1845 alias: &str,
1846 domain: Domain,
1847 namespace: i64,
1848 ) -> Result<bool> {
1849 db.with_transaction(TransactionBehavior::Immediate, |tx| {
1850 KeystoreDB::rebind_alias(tx, newid, alias, domain, namespace)
1851 })
1852 .context("In rebind_alias.")
1853 }
1854
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001855 #[test]
1856 fn datetime() -> Result<()> {
1857 let conn = Connection::open_in_memory()?;
1858 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
1859 let now = SystemTime::now();
1860 let duration = Duration::from_secs(1000);
1861 let then = now.checked_sub(duration).unwrap();
1862 let soon = now.checked_add(duration).unwrap();
1863 conn.execute(
1864 "INSERT INTO test (ts) VALUES (?), (?), (?);",
1865 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
1866 )?;
1867 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
1868 let mut rows = stmt.query(NO_PARAMS)?;
1869 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
1870 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
1871 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
1872 assert!(rows.next()?.is_none());
1873 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
1874 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
1875 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
1876 Ok(())
1877 }
1878
Joel Galenson0891bc12020-07-20 10:37:03 -07001879 // Ensure that we're using the "injected" random function, not the real one.
1880 #[test]
1881 fn test_mocked_random() {
1882 let rand1 = random();
1883 let rand2 = random();
1884 let rand3 = random();
1885 if rand1 == rand2 {
1886 assert_eq!(rand2 + 1, rand3);
1887 } else {
1888 assert_eq!(rand1 + 1, rand2);
1889 assert_eq!(rand2, rand3);
1890 }
1891 }
Joel Galenson26f4d012020-07-17 14:57:21 -07001892
Joel Galenson26f4d012020-07-17 14:57:21 -07001893 // Test that we have the correct tables.
1894 #[test]
1895 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001896 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07001897 let tables = db
1898 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07001899 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07001900 .query_map(params![], |row| row.get(0))?
1901 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001902 assert_eq!(tables.len(), 5);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001903 assert_eq!(tables[0], "blobentry");
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001904 assert_eq!(tables[1], "grant");
1905 assert_eq!(tables[2], "keyentry");
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001906 assert_eq!(tables[3], "keymetadata");
1907 assert_eq!(tables[4], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001908 let tables = db
1909 .conn
1910 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
1911 .query_map(params![], |row| row.get(0))?
1912 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001913
1914 assert_eq!(tables.len(), 2);
1915 assert_eq!(tables[0], "authtoken");
1916 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07001917 Ok(())
1918 }
1919
1920 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001921 fn test_auth_token_table_invariant() -> Result<()> {
1922 let mut db = new_test_db()?;
1923 let auth_token1 = HardwareAuthToken {
1924 challenge: i64::MAX,
1925 userId: 200,
1926 authenticatorId: 200,
1927 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
1928 timestamp: Timestamp { milliSeconds: 500 },
1929 mac: String::from("mac").into_bytes(),
1930 };
1931 db.insert_auth_token(&auth_token1)?;
1932 let auth_tokens_returned = get_auth_tokens(&mut db)?;
1933 assert_eq!(auth_tokens_returned.len(), 1);
1934
1935 // insert another auth token with the same values for the columns in the UNIQUE constraint
1936 // of the auth token table and different value for timestamp
1937 let auth_token2 = HardwareAuthToken {
1938 challenge: i64::MAX,
1939 userId: 200,
1940 authenticatorId: 200,
1941 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
1942 timestamp: Timestamp { milliSeconds: 600 },
1943 mac: String::from("mac").into_bytes(),
1944 };
1945
1946 db.insert_auth_token(&auth_token2)?;
1947 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
1948 assert_eq!(auth_tokens_returned.len(), 1);
1949
1950 if let Some(auth_token) = auth_tokens_returned.pop() {
1951 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
1952 }
1953
1954 // insert another auth token with the different values for the columns in the UNIQUE
1955 // constraint of the auth token table
1956 let auth_token3 = HardwareAuthToken {
1957 challenge: i64::MAX,
1958 userId: 201,
1959 authenticatorId: 200,
1960 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
1961 timestamp: Timestamp { milliSeconds: 600 },
1962 mac: String::from("mac").into_bytes(),
1963 };
1964
1965 db.insert_auth_token(&auth_token3)?;
1966 let auth_tokens_returned = get_auth_tokens(&mut db)?;
1967 assert_eq!(auth_tokens_returned.len(), 2);
1968
1969 Ok(())
1970 }
1971
1972 // utility function for test_auth_token_table_invariant()
1973 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
1974 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
1975
1976 let auth_token_entries: Vec<AuthTokenEntry> = stmt
1977 .query_map(NO_PARAMS, |row| {
1978 Ok(AuthTokenEntry::new(
1979 HardwareAuthToken {
1980 challenge: row.get(1)?,
1981 userId: row.get(2)?,
1982 authenticatorId: row.get(3)?,
1983 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
1984 timestamp: Timestamp { milliSeconds: row.get(5)? },
1985 mac: row.get(6)?,
1986 },
1987 row.get(7)?,
1988 ))
1989 })?
1990 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
1991 Ok(auth_token_entries)
1992 }
1993
1994 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07001995 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001996 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001997 let mut db = KeystoreDB::new(temp_dir.path())?;
Joel Galenson2aab4432020-07-22 15:27:57 -07001998
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001999 db.create_key_entry(Domain::APP, 100)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07002000 let entries = get_keyentry(&db)?;
2001 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002002
2003 let db = KeystoreDB::new(temp_dir.path())?;
Joel Galenson2aab4432020-07-22 15:27:57 -07002004
2005 let entries_new = get_keyentry(&db)?;
2006 assert_eq!(entries, entries_new);
2007 Ok(())
2008 }
2009
2010 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07002011 fn test_create_key_entry() -> Result<()> {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002012 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>) {
Joel Galenson0891bc12020-07-20 10:37:03 -07002013 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref())
2014 }
2015
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002016 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07002017
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002018 db.create_key_entry(Domain::APP, 100)?;
2019 db.create_key_entry(Domain::SELINUX, 101)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07002020
2021 let entries = get_keyentry(&db)?;
2022 assert_eq!(entries.len(), 2);
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002023 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None));
2024 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None));
Joel Galenson0891bc12020-07-20 10:37:03 -07002025
2026 // Test that we must pass in a valid Domain.
2027 check_result_is_error_containing_string(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002028 db.create_key_entry(Domain::GRANT, 102),
2029 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07002030 );
2031 check_result_is_error_containing_string(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002032 db.create_key_entry(Domain::BLOB, 103),
2033 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07002034 );
2035 check_result_is_error_containing_string(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002036 db.create_key_entry(Domain::KEY_ID, 104),
2037 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07002038 );
2039
2040 Ok(())
2041 }
2042
Joel Galenson33c04ad2020-08-03 11:04:38 -07002043 #[test]
2044 fn test_rebind_alias() -> Result<()> {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002045 fn extractor(ke: &KeyEntryRow) -> (Option<Domain>, Option<i64>, Option<&str>) {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002046 (ke.domain, ke.namespace, ke.alias.as_deref())
2047 }
2048
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002049 let mut db = new_test_db()?;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002050 db.create_key_entry(Domain::APP, 42)?;
2051 db.create_key_entry(Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002052 let entries = get_keyentry(&db)?;
2053 assert_eq!(entries.len(), 2);
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002054 assert_eq!(extractor(&entries[0]), (Some(Domain::APP), Some(42), None));
2055 assert_eq!(extractor(&entries[1]), (Some(Domain::APP), Some(42), None));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002056
2057 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002058 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002059 let entries = get_keyentry(&db)?;
2060 assert_eq!(entries.len(), 2);
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002061 assert_eq!(extractor(&entries[0]), (Some(Domain::APP), Some(42), Some("foo")));
2062 assert_eq!(extractor(&entries[1]), (Some(Domain::APP), Some(42), None));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002063
2064 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002065 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002066 let entries = get_keyentry(&db)?;
2067 assert_eq!(entries.len(), 2);
Joel Galenson7fa5c412020-11-19 10:56:54 -08002068 assert_eq!(extractor(&entries[0]), (None, None, None));
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002069 assert_eq!(extractor(&entries[1]), (Some(Domain::APP), Some(42), Some("foo")));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002070
2071 // Test that we must pass in a valid Domain.
2072 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002073 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002074 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002075 );
2076 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002077 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002078 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002079 );
2080 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002081 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002082 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002083 );
2084
2085 // Test that we correctly handle setting an alias for something that does not exist.
2086 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002087 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07002088 "Expected to update a single entry but instead updated 0",
2089 );
2090 // Test that we correctly abort the transaction in this case.
2091 let entries = get_keyentry(&db)?;
2092 assert_eq!(entries.len(), 2);
Joel Galenson7fa5c412020-11-19 10:56:54 -08002093 assert_eq!(extractor(&entries[0]), (None, None, None));
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002094 assert_eq!(extractor(&entries[1]), (Some(Domain::APP), Some(42), Some("foo")));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002095
2096 Ok(())
2097 }
2098
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002099 #[test]
2100 fn test_grant_ungrant() -> Result<()> {
2101 const CALLER_UID: u32 = 15;
2102 const GRANTEE_UID: u32 = 12;
2103 const SELINUX_NAMESPACE: i64 = 7;
2104
2105 let mut db = new_test_db()?;
2106 db.conn.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002107 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state)
2108 VALUES (1, 0, 0, 15, 'key', 1), (2, 0, 2, 7, 'yek', 1);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002109 NO_PARAMS,
2110 )?;
2111 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002112 domain: super::Domain::APP,
2113 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002114 alias: Some("key".to_string()),
2115 blob: None,
2116 };
2117 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
2118 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
2119
2120 // Reset totally predictable random number generator in case we
2121 // are not the first test running on this thread.
2122 reset_random();
2123 let next_random = 0i64;
2124
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002125 let app_granted_key = db
2126 .grant(app_key.clone(), CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002127 assert_eq!(*a, PVEC1);
2128 assert_eq!(
2129 *k,
2130 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002131 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002132 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002133 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002134 alias: Some("key".to_string()),
2135 blob: None,
2136 }
2137 );
2138 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002139 })
2140 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002141
2142 assert_eq!(
2143 app_granted_key,
2144 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002145 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002146 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002147 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002148 alias: None,
2149 blob: None,
2150 }
2151 );
2152
2153 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002154 domain: super::Domain::SELINUX,
2155 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002156 alias: Some("yek".to_string()),
2157 blob: None,
2158 };
2159
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002160 let selinux_granted_key = db
2161 .grant(selinux_key.clone(), CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002162 assert_eq!(*a, PVEC1);
2163 assert_eq!(
2164 *k,
2165 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002166 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002167 // namespace must be the supplied SELinux
2168 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002169 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002170 alias: Some("yek".to_string()),
2171 blob: None,
2172 }
2173 );
2174 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002175 })
2176 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002177
2178 assert_eq!(
2179 selinux_granted_key,
2180 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002181 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002182 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002183 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002184 alias: None,
2185 blob: None,
2186 }
2187 );
2188
2189 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002190 let selinux_granted_key = db
2191 .grant(selinux_key.clone(), CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002192 assert_eq!(*a, PVEC2);
2193 assert_eq!(
2194 *k,
2195 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002196 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002197 // namespace must be the supplied SELinux
2198 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002199 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002200 alias: Some("yek".to_string()),
2201 blob: None,
2202 }
2203 );
2204 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002205 })
2206 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002207
2208 assert_eq!(
2209 selinux_granted_key,
2210 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002211 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002212 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002213 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002214 alias: None,
2215 blob: None,
2216 }
2217 );
2218
2219 {
2220 // Limiting scope of stmt, because it borrows db.
2221 let mut stmt = db
2222 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002223 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07002224 let mut rows =
2225 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
2226 Ok((
2227 row.get(0)?,
2228 row.get(1)?,
2229 row.get(2)?,
2230 KeyPermSet::from(row.get::<_, i32>(3)?),
2231 ))
2232 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002233
2234 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07002235 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002236 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07002237 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002238 assert!(rows.next().is_none());
2239 }
2240
2241 debug_dump_keyentry_table(&mut db)?;
2242 println!("app_key {:?}", app_key);
2243 println!("selinux_key {:?}", selinux_key);
2244
2245 db.ungrant(app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
2246 db.ungrant(selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
2247
2248 Ok(())
2249 }
2250
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002251 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002252 static TEST_CERT_BLOB: &[u8] = b"my test cert";
2253 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
2254
2255 #[test]
2256 fn test_insert_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002257 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002258 let mut db = new_test_db()?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002259 db.insert_blob(&key_id, SubComponentType::KEY_BLOB, TEST_KEY_BLOB)?;
2260 db.insert_blob(&key_id, SubComponentType::CERT, TEST_CERT_BLOB)?;
2261 db.insert_blob(&key_id, SubComponentType::CERT_CHAIN, TEST_CERT_CHAIN_BLOB)?;
2262 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002263
2264 let mut stmt = db.conn.prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002265 "SELECT subcomponent_type, keyentryid, blob FROM persistent.blobentry
2266 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002267 )?;
2268 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002269 .query_map::<(SubComponentType, i64, Vec<u8>), _, _>(NO_PARAMS, |row| {
2270 Ok((row.get(0)?, row.get(1)?, row.get(2)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002271 })?;
2272 let r = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002273 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002274 let r = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002275 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002276 let r = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002277 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002278
2279 Ok(())
2280 }
2281
2282 static TEST_ALIAS: &str = "my super duper key";
2283
2284 #[test]
2285 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
2286 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08002287 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08002288 .context("test_insert_and_load_full_keyentry_domain_app")?
2289 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002290 let (_key_guard, key_entry) = db
2291 .load_key_entry(
2292 KeyDescriptor {
2293 domain: Domain::APP,
2294 nspace: 0,
2295 alias: Some(TEST_ALIAS.to_string()),
2296 blob: None,
2297 },
2298 KeyType::Client,
2299 KeyEntryLoadBits::BOTH,
2300 1,
2301 |_k, _av| Ok(()),
2302 )
2303 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08002304 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002305
2306 db.unbind_key(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002307 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002308 domain: Domain::APP,
2309 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002310 alias: Some(TEST_ALIAS.to_string()),
2311 blob: None,
2312 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002313 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002314 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002315 |_, _| Ok(()),
2316 )
2317 .unwrap();
2318
2319 assert_eq!(
2320 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
2321 db.load_key_entry(
2322 KeyDescriptor {
2323 domain: Domain::APP,
2324 nspace: 0,
2325 alias: Some(TEST_ALIAS.to_string()),
2326 blob: None,
2327 },
2328 KeyType::Client,
2329 KeyEntryLoadBits::NONE,
2330 1,
2331 |_k, _av| Ok(()),
2332 )
2333 .unwrap_err()
2334 .root_cause()
2335 .downcast_ref::<KsError>()
2336 );
2337
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002338 Ok(())
2339 }
2340
2341 #[test]
2342 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
2343 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08002344 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08002345 .context("test_insert_and_load_full_keyentry_domain_selinux")?
2346 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002347 let (_key_guard, key_entry) = db
2348 .load_key_entry(
2349 KeyDescriptor {
2350 domain: Domain::SELINUX,
2351 nspace: 1,
2352 alias: Some(TEST_ALIAS.to_string()),
2353 blob: None,
2354 },
2355 KeyType::Client,
2356 KeyEntryLoadBits::BOTH,
2357 1,
2358 |_k, _av| Ok(()),
2359 )
2360 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08002361 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002362
2363 db.unbind_key(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002364 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002365 domain: Domain::SELINUX,
2366 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002367 alias: Some(TEST_ALIAS.to_string()),
2368 blob: None,
2369 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002370 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002371 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002372 |_, _| Ok(()),
2373 )
2374 .unwrap();
2375
2376 assert_eq!(
2377 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
2378 db.load_key_entry(
2379 KeyDescriptor {
2380 domain: Domain::SELINUX,
2381 nspace: 1,
2382 alias: Some(TEST_ALIAS.to_string()),
2383 blob: None,
2384 },
2385 KeyType::Client,
2386 KeyEntryLoadBits::NONE,
2387 1,
2388 |_k, _av| Ok(()),
2389 )
2390 .unwrap_err()
2391 .root_cause()
2392 .downcast_ref::<KsError>()
2393 );
2394
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002395 Ok(())
2396 }
2397
2398 #[test]
2399 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
2400 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08002401 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08002402 .context("test_insert_and_load_full_keyentry_domain_key_id")?
2403 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002404 let (_, key_entry) = db
2405 .load_key_entry(
2406 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
2407 KeyType::Client,
2408 KeyEntryLoadBits::BOTH,
2409 1,
2410 |_k, _av| Ok(()),
2411 )
2412 .unwrap();
2413
Qi Wub9433b52020-12-01 14:52:46 +08002414 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002415
2416 db.unbind_key(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002417 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002418 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002419 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002420 |_, _| Ok(()),
2421 )
2422 .unwrap();
2423
2424 assert_eq!(
2425 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
2426 db.load_key_entry(
2427 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
2428 KeyType::Client,
2429 KeyEntryLoadBits::NONE,
2430 1,
2431 |_k, _av| Ok(()),
2432 )
2433 .unwrap_err()
2434 .root_cause()
2435 .downcast_ref::<KsError>()
2436 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002437
2438 Ok(())
2439 }
2440
2441 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08002442 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
2443 let mut db = new_test_db()?;
2444 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
2445 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
2446 .0;
2447 // Update the usage count of the limited use key.
2448 db.check_and_update_key_usage_count(key_id)?;
2449
2450 let (_key_guard, key_entry) = db.load_key_entry(
2451 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
2452 KeyType::Client,
2453 KeyEntryLoadBits::BOTH,
2454 1,
2455 |_k, _av| Ok(()),
2456 )?;
2457
2458 // The usage count is decremented now.
2459 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
2460
2461 Ok(())
2462 }
2463
2464 #[test]
2465 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
2466 let mut db = new_test_db()?;
2467 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
2468 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
2469 .0;
2470 // Update the usage count of the limited use key.
2471 db.check_and_update_key_usage_count(key_id).expect(concat!(
2472 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
2473 "This should succeed."
2474 ));
2475
2476 // Try to update the exhausted limited use key.
2477 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
2478 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
2479 "This should fail."
2480 ));
2481 assert_eq!(
2482 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
2483 e.root_cause().downcast_ref::<KsError>().unwrap()
2484 );
2485
2486 Ok(())
2487 }
2488
2489 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002490 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
2491 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08002492 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08002493 .context("test_insert_and_load_full_keyentry_from_grant")?
2494 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002495
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002496 let granted_key = db
2497 .grant(
2498 KeyDescriptor {
2499 domain: Domain::APP,
2500 nspace: 0,
2501 alias: Some(TEST_ALIAS.to_string()),
2502 blob: None,
2503 },
2504 1,
2505 2,
2506 key_perm_set![KeyPerm::use_()],
2507 |_k, _av| Ok(()),
2508 )
2509 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002510
2511 debug_dump_grant_table(&mut db)?;
2512
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002513 let (_key_guard, key_entry) = db
2514 .load_key_entry(
2515 granted_key.clone(),
2516 KeyType::Client,
2517 KeyEntryLoadBits::BOTH,
2518 2,
2519 |k, av| {
2520 assert_eq!(Domain::GRANT, k.domain);
2521 assert!(av.unwrap().includes(KeyPerm::use_()));
2522 Ok(())
2523 },
2524 )
2525 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002526
Qi Wub9433b52020-12-01 14:52:46 +08002527 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002528
2529 db.unbind_key(granted_key.clone(), KeyType::Client, 2, |_, _| Ok(())).unwrap();
2530
2531 assert_eq!(
2532 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
2533 db.load_key_entry(
2534 granted_key,
2535 KeyType::Client,
2536 KeyEntryLoadBits::NONE,
2537 2,
2538 |_k, _av| Ok(()),
2539 )
2540 .unwrap_err()
2541 .root_cause()
2542 .downcast_ref::<KsError>()
2543 );
2544
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002545 Ok(())
2546 }
2547
Janis Danisevskis45760022021-01-19 16:34:10 -08002548 // This test attempts to load a key by key id while the caller is not the owner
2549 // but a grant exists for the given key and the caller.
2550 #[test]
2551 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
2552 let mut db = new_test_db()?;
2553 const OWNER_UID: u32 = 1u32;
2554 const GRANTEE_UID: u32 = 2u32;
2555 const SOMEONE_ELSE_UID: u32 = 3u32;
2556 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
2557 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
2558 .0;
2559
2560 db.grant(
2561 KeyDescriptor {
2562 domain: Domain::APP,
2563 nspace: 0,
2564 alias: Some(TEST_ALIAS.to_string()),
2565 blob: None,
2566 },
2567 OWNER_UID,
2568 GRANTEE_UID,
2569 key_perm_set![KeyPerm::use_()],
2570 |_k, _av| Ok(()),
2571 )
2572 .unwrap();
2573
2574 debug_dump_grant_table(&mut db)?;
2575
2576 let id_descriptor =
2577 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
2578
2579 let (_, key_entry) = db
2580 .load_key_entry(
2581 id_descriptor.clone(),
2582 KeyType::Client,
2583 KeyEntryLoadBits::BOTH,
2584 GRANTEE_UID,
2585 |k, av| {
2586 assert_eq!(Domain::APP, k.domain);
2587 assert_eq!(OWNER_UID as i64, k.nspace);
2588 assert!(av.unwrap().includes(KeyPerm::use_()));
2589 Ok(())
2590 },
2591 )
2592 .unwrap();
2593
2594 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
2595
2596 let (_, key_entry) = db
2597 .load_key_entry(
2598 id_descriptor.clone(),
2599 KeyType::Client,
2600 KeyEntryLoadBits::BOTH,
2601 SOMEONE_ELSE_UID,
2602 |k, av| {
2603 assert_eq!(Domain::APP, k.domain);
2604 assert_eq!(OWNER_UID as i64, k.nspace);
2605 assert!(av.is_none());
2606 Ok(())
2607 },
2608 )
2609 .unwrap();
2610
2611 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
2612
2613 db.unbind_key(id_descriptor.clone(), KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
2614
2615 assert_eq!(
2616 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
2617 db.load_key_entry(
2618 id_descriptor,
2619 KeyType::Client,
2620 KeyEntryLoadBits::NONE,
2621 GRANTEE_UID,
2622 |_k, _av| Ok(()),
2623 )
2624 .unwrap_err()
2625 .root_cause()
2626 .downcast_ref::<KsError>()
2627 );
2628
2629 Ok(())
2630 }
2631
Janis Danisevskisaec14592020-11-12 09:41:49 -08002632 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
2633
Janis Danisevskisaec14592020-11-12 09:41:49 -08002634 #[test]
2635 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
2636 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002637 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
2638 let temp_dir_clone = temp_dir.clone();
2639 let mut db = KeystoreDB::new(temp_dir.path())?;
Qi Wub9433b52020-12-01 14:52:46 +08002640 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08002641 .context("test_insert_and_load_full_keyentry_domain_app")?
2642 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002643 let (_key_guard, key_entry) = db
2644 .load_key_entry(
2645 KeyDescriptor {
2646 domain: Domain::APP,
2647 nspace: 0,
2648 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
2649 blob: None,
2650 },
2651 KeyType::Client,
2652 KeyEntryLoadBits::BOTH,
2653 33,
2654 |_k, _av| Ok(()),
2655 )
2656 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08002657 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08002658 let state = Arc::new(AtomicU8::new(1));
2659 let state2 = state.clone();
2660
2661 // Spawning a second thread that attempts to acquire the key id lock
2662 // for the same key as the primary thread. The primary thread then
2663 // waits, thereby forcing the secondary thread into the second stage
2664 // of acquiring the lock (see KEY ID LOCK 2/2 above).
2665 // The test succeeds if the secondary thread observes the transition
2666 // of `state` from 1 to 2, despite having a whole second to overtake
2667 // the primary thread.
2668 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002669 let temp_dir = temp_dir_clone;
2670 let mut db = KeystoreDB::new(temp_dir.path()).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08002671 assert!(db
2672 .load_key_entry(
2673 KeyDescriptor {
2674 domain: Domain::APP,
2675 nspace: 0,
2676 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
2677 blob: None,
2678 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002679 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002680 KeyEntryLoadBits::BOTH,
2681 33,
2682 |_k, _av| Ok(()),
2683 )
2684 .is_ok());
2685 // We should only see a 2 here because we can only return
2686 // from load_key_entry when the `_key_guard` expires,
2687 // which happens at the end of the scope.
2688 assert_eq!(2, state2.load(Ordering::Relaxed));
2689 });
2690
2691 thread::sleep(std::time::Duration::from_millis(1000));
2692
2693 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
2694
2695 // Return the handle from this scope so we can join with the
2696 // secondary thread after the key id lock has expired.
2697 handle
2698 // This is where the `_key_guard` goes out of scope,
2699 // which is the reason for concurrent load_key_entry on the same key
2700 // to unblock.
2701 };
2702 // Join with the secondary thread and unwrap, to propagate failing asserts to the
2703 // main test thread. We will not see failing asserts in secondary threads otherwise.
2704 handle.join().unwrap();
2705 Ok(())
2706 }
2707
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002708 #[test]
2709 fn list() -> Result<()> {
2710 let temp_dir = TempDir::new("list_test")?;
2711 let mut db = KeystoreDB::new(temp_dir.path())?;
2712 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
2713 (Domain::APP, 1, "test1"),
2714 (Domain::APP, 1, "test2"),
2715 (Domain::APP, 1, "test3"),
2716 (Domain::APP, 1, "test4"),
2717 (Domain::APP, 1, "test5"),
2718 (Domain::APP, 1, "test6"),
2719 (Domain::APP, 1, "test7"),
2720 (Domain::APP, 2, "test1"),
2721 (Domain::APP, 2, "test2"),
2722 (Domain::APP, 2, "test3"),
2723 (Domain::APP, 2, "test4"),
2724 (Domain::APP, 2, "test5"),
2725 (Domain::APP, 2, "test6"),
2726 (Domain::APP, 2, "test8"),
2727 (Domain::SELINUX, 100, "test1"),
2728 (Domain::SELINUX, 100, "test2"),
2729 (Domain::SELINUX, 100, "test3"),
2730 (Domain::SELINUX, 100, "test4"),
2731 (Domain::SELINUX, 100, "test5"),
2732 (Domain::SELINUX, 100, "test6"),
2733 (Domain::SELINUX, 100, "test9"),
2734 ];
2735
2736 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
2737 .iter()
2738 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08002739 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
2740 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002741 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
2742 });
2743 (entry.id(), *ns)
2744 })
2745 .collect();
2746
2747 for (domain, namespace) in
2748 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
2749 {
2750 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
2751 .iter()
2752 .filter_map(|(domain, ns, alias)| match ns {
2753 ns if *ns == *namespace => Some(KeyDescriptor {
2754 domain: *domain,
2755 nspace: *ns,
2756 alias: Some(alias.to_string()),
2757 blob: None,
2758 }),
2759 _ => None,
2760 })
2761 .collect();
2762 list_o_descriptors.sort();
2763 let mut list_result = db.list(*domain, *namespace)?;
2764 list_result.sort();
2765 assert_eq!(list_o_descriptors, list_result);
2766
2767 let mut list_o_ids: Vec<i64> = list_o_descriptors
2768 .into_iter()
2769 .map(|d| {
2770 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002771 .load_key_entry(
2772 d,
2773 KeyType::Client,
2774 KeyEntryLoadBits::NONE,
2775 *namespace as u32,
2776 |_, _| Ok(()),
2777 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002778 .unwrap();
2779 entry.id()
2780 })
2781 .collect();
2782 list_o_ids.sort_unstable();
2783 let mut loaded_entries: Vec<i64> = list_o_keys
2784 .iter()
2785 .filter_map(|(id, ns)| match ns {
2786 ns if *ns == *namespace => Some(*id),
2787 _ => None,
2788 })
2789 .collect();
2790 loaded_entries.sort_unstable();
2791 assert_eq!(list_o_ids, loaded_entries);
2792 }
2793 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
2794
2795 Ok(())
2796 }
2797
Joel Galenson0891bc12020-07-20 10:37:03 -07002798 // Helpers
2799
2800 // Checks that the given result is an error containing the given string.
2801 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
2802 let error_str = format!(
2803 "{:#?}",
2804 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
2805 );
2806 assert!(
2807 error_str.contains(target),
2808 "The string \"{}\" should contain \"{}\"",
2809 error_str,
2810 target
2811 );
2812 }
2813
Joel Galenson2aab4432020-07-22 15:27:57 -07002814 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07002815 #[allow(dead_code)]
2816 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002817 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002818 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002819 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07002820 namespace: Option<i64>,
2821 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002822 state: KeyLifeCycle,
Joel Galenson0891bc12020-07-20 10:37:03 -07002823 }
2824
2825 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
2826 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07002827 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07002828 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07002829 Ok(KeyEntryRow {
2830 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002831 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002832 domain: match row.get(2)? {
2833 Some(i) => Some(Domain(i)),
2834 None => None,
2835 },
Joel Galenson0891bc12020-07-20 10:37:03 -07002836 namespace: row.get(3)?,
2837 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002838 state: row.get(5)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07002839 })
2840 })?
2841 .map(|r| r.context("Could not read keyentry row."))
2842 .collect::<Result<Vec<_>>>()
2843 }
2844
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002845 // Note: The parameters and SecurityLevel associations are nonsensical. This
2846 // collection is only used to check if the parameters are preserved as expected by the
2847 // database.
Qi Wub9433b52020-12-01 14:52:46 +08002848 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
2849 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002850 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
2851 KeyParameter::new(
2852 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
2853 SecurityLevel::TRUSTED_ENVIRONMENT,
2854 ),
2855 KeyParameter::new(
2856 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
2857 SecurityLevel::TRUSTED_ENVIRONMENT,
2858 ),
2859 KeyParameter::new(
2860 KeyParameterValue::Algorithm(Algorithm::RSA),
2861 SecurityLevel::TRUSTED_ENVIRONMENT,
2862 ),
2863 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
2864 KeyParameter::new(
2865 KeyParameterValue::BlockMode(BlockMode::ECB),
2866 SecurityLevel::TRUSTED_ENVIRONMENT,
2867 ),
2868 KeyParameter::new(
2869 KeyParameterValue::BlockMode(BlockMode::GCM),
2870 SecurityLevel::TRUSTED_ENVIRONMENT,
2871 ),
2872 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
2873 KeyParameter::new(
2874 KeyParameterValue::Digest(Digest::MD5),
2875 SecurityLevel::TRUSTED_ENVIRONMENT,
2876 ),
2877 KeyParameter::new(
2878 KeyParameterValue::Digest(Digest::SHA_2_224),
2879 SecurityLevel::TRUSTED_ENVIRONMENT,
2880 ),
2881 KeyParameter::new(
2882 KeyParameterValue::Digest(Digest::SHA_2_256),
2883 SecurityLevel::STRONGBOX,
2884 ),
2885 KeyParameter::new(
2886 KeyParameterValue::PaddingMode(PaddingMode::NONE),
2887 SecurityLevel::TRUSTED_ENVIRONMENT,
2888 ),
2889 KeyParameter::new(
2890 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
2891 SecurityLevel::TRUSTED_ENVIRONMENT,
2892 ),
2893 KeyParameter::new(
2894 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
2895 SecurityLevel::STRONGBOX,
2896 ),
2897 KeyParameter::new(
2898 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
2899 SecurityLevel::TRUSTED_ENVIRONMENT,
2900 ),
2901 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
2902 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
2903 KeyParameter::new(
2904 KeyParameterValue::EcCurve(EcCurve::P_224),
2905 SecurityLevel::TRUSTED_ENVIRONMENT,
2906 ),
2907 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
2908 KeyParameter::new(
2909 KeyParameterValue::EcCurve(EcCurve::P_384),
2910 SecurityLevel::TRUSTED_ENVIRONMENT,
2911 ),
2912 KeyParameter::new(
2913 KeyParameterValue::EcCurve(EcCurve::P_521),
2914 SecurityLevel::TRUSTED_ENVIRONMENT,
2915 ),
2916 KeyParameter::new(
2917 KeyParameterValue::RSAPublicExponent(3),
2918 SecurityLevel::TRUSTED_ENVIRONMENT,
2919 ),
2920 KeyParameter::new(
2921 KeyParameterValue::IncludeUniqueID,
2922 SecurityLevel::TRUSTED_ENVIRONMENT,
2923 ),
2924 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
2925 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
2926 KeyParameter::new(
2927 KeyParameterValue::ActiveDateTime(1234567890),
2928 SecurityLevel::STRONGBOX,
2929 ),
2930 KeyParameter::new(
2931 KeyParameterValue::OriginationExpireDateTime(1234567890),
2932 SecurityLevel::TRUSTED_ENVIRONMENT,
2933 ),
2934 KeyParameter::new(
2935 KeyParameterValue::UsageExpireDateTime(1234567890),
2936 SecurityLevel::TRUSTED_ENVIRONMENT,
2937 ),
2938 KeyParameter::new(
2939 KeyParameterValue::MinSecondsBetweenOps(1234567890),
2940 SecurityLevel::TRUSTED_ENVIRONMENT,
2941 ),
2942 KeyParameter::new(
2943 KeyParameterValue::MaxUsesPerBoot(1234567890),
2944 SecurityLevel::TRUSTED_ENVIRONMENT,
2945 ),
2946 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
2947 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
2948 KeyParameter::new(
2949 KeyParameterValue::NoAuthRequired,
2950 SecurityLevel::TRUSTED_ENVIRONMENT,
2951 ),
2952 KeyParameter::new(
2953 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
2954 SecurityLevel::TRUSTED_ENVIRONMENT,
2955 ),
2956 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
2957 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
2958 KeyParameter::new(
2959 KeyParameterValue::TrustedUserPresenceRequired,
2960 SecurityLevel::TRUSTED_ENVIRONMENT,
2961 ),
2962 KeyParameter::new(
2963 KeyParameterValue::TrustedConfirmationRequired,
2964 SecurityLevel::TRUSTED_ENVIRONMENT,
2965 ),
2966 KeyParameter::new(
2967 KeyParameterValue::UnlockedDeviceRequired,
2968 SecurityLevel::TRUSTED_ENVIRONMENT,
2969 ),
2970 KeyParameter::new(
2971 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
2972 SecurityLevel::SOFTWARE,
2973 ),
2974 KeyParameter::new(
2975 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
2976 SecurityLevel::SOFTWARE,
2977 ),
2978 KeyParameter::new(
2979 KeyParameterValue::CreationDateTime(12345677890),
2980 SecurityLevel::SOFTWARE,
2981 ),
2982 KeyParameter::new(
2983 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
2984 SecurityLevel::TRUSTED_ENVIRONMENT,
2985 ),
2986 KeyParameter::new(
2987 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
2988 SecurityLevel::TRUSTED_ENVIRONMENT,
2989 ),
2990 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
2991 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
2992 KeyParameter::new(
2993 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
2994 SecurityLevel::SOFTWARE,
2995 ),
2996 KeyParameter::new(
2997 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
2998 SecurityLevel::TRUSTED_ENVIRONMENT,
2999 ),
3000 KeyParameter::new(
3001 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
3002 SecurityLevel::TRUSTED_ENVIRONMENT,
3003 ),
3004 KeyParameter::new(
3005 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
3006 SecurityLevel::TRUSTED_ENVIRONMENT,
3007 ),
3008 KeyParameter::new(
3009 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
3010 SecurityLevel::TRUSTED_ENVIRONMENT,
3011 ),
3012 KeyParameter::new(
3013 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
3014 SecurityLevel::TRUSTED_ENVIRONMENT,
3015 ),
3016 KeyParameter::new(
3017 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
3018 SecurityLevel::TRUSTED_ENVIRONMENT,
3019 ),
3020 KeyParameter::new(
3021 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
3022 SecurityLevel::TRUSTED_ENVIRONMENT,
3023 ),
3024 KeyParameter::new(
3025 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
3026 SecurityLevel::TRUSTED_ENVIRONMENT,
3027 ),
3028 KeyParameter::new(
3029 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
3030 SecurityLevel::TRUSTED_ENVIRONMENT,
3031 ),
3032 KeyParameter::new(
3033 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
3034 SecurityLevel::TRUSTED_ENVIRONMENT,
3035 ),
3036 KeyParameter::new(
3037 KeyParameterValue::VendorPatchLevel(3),
3038 SecurityLevel::TRUSTED_ENVIRONMENT,
3039 ),
3040 KeyParameter::new(
3041 KeyParameterValue::BootPatchLevel(4),
3042 SecurityLevel::TRUSTED_ENVIRONMENT,
3043 ),
3044 KeyParameter::new(
3045 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
3046 SecurityLevel::TRUSTED_ENVIRONMENT,
3047 ),
3048 KeyParameter::new(
3049 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
3050 SecurityLevel::TRUSTED_ENVIRONMENT,
3051 ),
3052 KeyParameter::new(
3053 KeyParameterValue::MacLength(256),
3054 SecurityLevel::TRUSTED_ENVIRONMENT,
3055 ),
3056 KeyParameter::new(
3057 KeyParameterValue::ResetSinceIdRotation,
3058 SecurityLevel::TRUSTED_ENVIRONMENT,
3059 ),
3060 KeyParameter::new(
3061 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
3062 SecurityLevel::TRUSTED_ENVIRONMENT,
3063 ),
Qi Wub9433b52020-12-01 14:52:46 +08003064 ];
3065 if let Some(value) = max_usage_count {
3066 params.push(KeyParameter::new(
3067 KeyParameterValue::UsageCountLimit(value),
3068 SecurityLevel::SOFTWARE,
3069 ));
3070 }
3071 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003072 }
3073
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003074 fn make_test_key_entry(
3075 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003076 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003077 namespace: i64,
3078 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08003079 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08003080 ) -> Result<KeyIdGuard> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003081 let key_id = db.create_key_entry(domain, namespace)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003082 db.insert_blob(&key_id, SubComponentType::KEY_BLOB, TEST_KEY_BLOB)?;
3083 db.insert_blob(&key_id, SubComponentType::CERT, TEST_CERT_BLOB)?;
3084 db.insert_blob(&key_id, SubComponentType::CERT_CHAIN, TEST_CERT_CHAIN_BLOB)?;
Qi Wub9433b52020-12-01 14:52:46 +08003085
3086 let params = make_test_params(max_usage_count);
3087 db.insert_keyparameter(&key_id, &params)?;
3088
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003089 let mut metadata = KeyMetaData::new();
3090 metadata.add(KeyMetaEntry::EncryptedBy(EncryptedBy::Password));
3091 metadata.add(KeyMetaEntry::Salt(vec![1, 2, 3]));
3092 metadata.add(KeyMetaEntry::Iv(vec![2, 3, 1]));
3093 metadata.add(KeyMetaEntry::AeadTag(vec![3, 1, 2]));
3094 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003095 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003096 Ok(key_id)
3097 }
3098
Qi Wub9433b52020-12-01 14:52:46 +08003099 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
3100 let params = make_test_params(max_usage_count);
3101
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003102 let mut metadata = KeyMetaData::new();
3103 metadata.add(KeyMetaEntry::EncryptedBy(EncryptedBy::Password));
3104 metadata.add(KeyMetaEntry::Salt(vec![1, 2, 3]));
3105 metadata.add(KeyMetaEntry::Iv(vec![2, 3, 1]));
3106 metadata.add(KeyMetaEntry::AeadTag(vec![3, 1, 2]));
3107
3108 KeyEntry {
3109 id: key_id,
3110 km_blob: Some(TEST_KEY_BLOB.to_vec()),
3111 cert: Some(TEST_CERT_BLOB.to_vec()),
3112 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
3113 sec_level: SecurityLevel::TRUSTED_ENVIRONMENT,
Qi Wub9433b52020-12-01 14:52:46 +08003114 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003115 metadata,
3116 }
3117 }
3118
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003119 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003120 let mut stmt = db.conn.prepare(
3121 "SELECT id, key_type, domain, namespace, alias, state FROM persistent.keyentry;",
3122 )?;
3123 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle), _, _>(
3124 NO_PARAMS,
3125 |row| {
3126 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?, row.get(5)?))
3127 },
3128 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003129
3130 println!("Key entry table rows:");
3131 for r in rows {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003132 let (id, key_type, domain, namespace, alias, state) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003133 println!(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003134 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?}",
3135 id, key_type, domain, namespace, alias, state
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003136 );
3137 }
3138 Ok(())
3139 }
3140
3141 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003142 let mut stmt = db
3143 .conn
3144 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003145 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
3146 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
3147 })?;
3148
3149 println!("Grant table rows:");
3150 for r in rows {
3151 let (id, gt, ki, av) = r.unwrap();
3152 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
3153 }
3154 Ok(())
3155 }
3156
Joel Galenson0891bc12020-07-20 10:37:03 -07003157 // Use a custom random number generator that repeats each number once.
3158 // This allows us to test repeated elements.
3159
3160 thread_local! {
3161 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
3162 }
3163
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003164 fn reset_random() {
3165 RANDOM_COUNTER.with(|counter| {
3166 *counter.borrow_mut() = 0;
3167 })
3168 }
3169
Joel Galenson0891bc12020-07-20 10:37:03 -07003170 pub fn random() -> i64 {
3171 RANDOM_COUNTER.with(|counter| {
3172 let result = *counter.borrow() / 2;
3173 *counter.borrow_mut() += 1;
3174 result
3175 })
3176 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003177
3178 #[test]
3179 fn test_last_off_body() -> Result<()> {
3180 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003181 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003182 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
3183 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
3184 tx.commit()?;
3185 let one_second = Duration::from_secs(1);
3186 thread::sleep(one_second);
3187 db.update_last_off_body(MonotonicRawTime::now())?;
3188 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
3189 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
3190 tx2.commit()?;
3191 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
3192 Ok(())
3193 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003194}