blob: 0e7a2d24d4f7393c28d87aaa443ee1a05f6cc164 [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};
Max Bires8e93d2b2021-01-14 13:17:59 -080051use std::{convert::TryFrom, convert::TryInto, ops::Deref, 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
Max Bires8e93d2b2021-01-14 13:17:59 -0800190/// Uuid representation that can be stored in the database.
191/// Right now it can only be initialized from SecurityLevel.
192/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
193#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
194pub struct Uuid([u8; 16]);
195
196impl Deref for Uuid {
197 type Target = [u8; 16];
198
199 fn deref(&self) -> &Self::Target {
200 &self.0
201 }
202}
203
204impl From<SecurityLevel> for Uuid {
205 fn from(sec_level: SecurityLevel) -> Self {
206 Self((sec_level.0 as u128).to_be_bytes())
207 }
208}
209
210impl ToSql for Uuid {
211 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
212 self.0.to_sql()
213 }
214}
215
216impl FromSql for Uuid {
217 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
218 let blob = Vec::<u8>::column_result(value)?;
219 if blob.len() != 16 {
220 return Err(FromSqlError::OutOfRange(blob.len() as i64));
221 }
222 let mut arr = [0u8; 16];
223 arr.copy_from_slice(&blob);
224 Ok(Self(arr))
225 }
226}
227
228/// Key entries that are not associated with any KeyMint instance, such as pure certificate
229/// entries are associated with this UUID.
230pub static KEYSTORE_UUID: Uuid = Uuid([
231 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
232]);
233
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800234/// Indicates how the sensitive part of this key blob is encrypted.
235#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
236pub enum EncryptedBy {
237 /// The keyblob is encrypted by a user password.
238 /// In the database this variant is represented as NULL.
239 Password,
240 /// The keyblob is encrypted by another key with wrapped key id.
241 /// In the database this variant is represented as non NULL value
242 /// that is convertible to i64, typically NUMERIC.
243 KeyId(i64),
244}
245
246impl ToSql for EncryptedBy {
247 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
248 match self {
249 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
250 Self::KeyId(id) => id.to_sql(),
251 }
252 }
253}
254
255impl FromSql for EncryptedBy {
256 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
257 match value {
258 ValueRef::Null => Ok(Self::Password),
259 _ => Ok(Self::KeyId(i64::column_result(value)?)),
260 }
261 }
262}
263
264/// A database representation of wall clock time. DateTime stores unix epoch time as
265/// i64 in milliseconds.
266#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
267pub struct DateTime(i64);
268
269/// Error type returned when creating DateTime or converting it from and to
270/// SystemTime.
271#[derive(thiserror::Error, Debug)]
272pub enum DateTimeError {
273 /// This is returned when SystemTime and Duration computations fail.
274 #[error(transparent)]
275 SystemTimeError(#[from] SystemTimeError),
276
277 /// This is returned when type conversions fail.
278 #[error(transparent)]
279 TypeConversion(#[from] std::num::TryFromIntError),
280
281 /// This is returned when checked time arithmetic failed.
282 #[error("Time arithmetic failed.")]
283 TimeArithmetic,
284}
285
286impl DateTime {
287 /// Constructs a new DateTime object denoting the current time. This may fail during
288 /// conversion to unix epoch time and during conversion to the internal i64 representation.
289 pub fn now() -> Result<Self, DateTimeError> {
290 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
291 }
292
293 /// Constructs a new DateTime object from milliseconds.
294 pub fn from_millis_epoch(millis: i64) -> Self {
295 Self(millis)
296 }
297
298 /// Returns unix epoch time in milliseconds.
299 pub fn to_millis_epoch(&self) -> i64 {
300 self.0
301 }
302
303 /// Returns unix epoch time in seconds.
304 pub fn to_secs_epoch(&self) -> i64 {
305 self.0 / 1000
306 }
307}
308
309impl ToSql for DateTime {
310 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
311 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
312 }
313}
314
315impl FromSql for DateTime {
316 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
317 Ok(Self(i64::column_result(value)?))
318 }
319}
320
321impl TryInto<SystemTime> for DateTime {
322 type Error = DateTimeError;
323
324 fn try_into(self) -> Result<SystemTime, Self::Error> {
325 // We want to construct a SystemTime representation equivalent to self, denoting
326 // a point in time THEN, but we cannot set the time directly. We can only construct
327 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
328 // and between EPOCH and THEN. With this common reference we can construct the
329 // duration between NOW and THEN which we can add to our SystemTime representation
330 // of NOW to get a SystemTime representation of THEN.
331 // Durations can only be positive, thus the if statement below.
332 let now = SystemTime::now();
333 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
334 let then_epoch = Duration::from_millis(self.0.try_into()?);
335 Ok(if now_epoch > then_epoch {
336 // then = now - (now_epoch - then_epoch)
337 now_epoch
338 .checked_sub(then_epoch)
339 .and_then(|d| now.checked_sub(d))
340 .ok_or(DateTimeError::TimeArithmetic)?
341 } else {
342 // then = now + (then_epoch - now_epoch)
343 then_epoch
344 .checked_sub(now_epoch)
345 .and_then(|d| now.checked_add(d))
346 .ok_or(DateTimeError::TimeArithmetic)?
347 })
348 }
349}
350
351impl TryFrom<SystemTime> for DateTime {
352 type Error = DateTimeError;
353
354 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
355 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
356 }
357}
358
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800359#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
360enum KeyLifeCycle {
361 /// Existing keys have a key ID but are not fully populated yet.
362 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
363 /// them to Unreferenced for garbage collection.
364 Existing,
365 /// A live key is fully populated and usable by clients.
366 Live,
367 /// An unreferenced key is scheduled for garbage collection.
368 Unreferenced,
369}
370
371impl ToSql for KeyLifeCycle {
372 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
373 match self {
374 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
375 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
376 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
377 }
378 }
379}
380
381impl FromSql for KeyLifeCycle {
382 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
383 match i64::column_result(value)? {
384 0 => Ok(KeyLifeCycle::Existing),
385 1 => Ok(KeyLifeCycle::Live),
386 2 => Ok(KeyLifeCycle::Unreferenced),
387 v => Err(FromSqlError::OutOfRange(v)),
388 }
389 }
390}
391
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700392/// Keys have a KeyMint blob component and optional public certificate and
393/// certificate chain components.
394/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
395/// which components shall be loaded from the database if present.
396#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
397pub struct KeyEntryLoadBits(u32);
398
399impl KeyEntryLoadBits {
400 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
401 pub const NONE: KeyEntryLoadBits = Self(0);
402 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
403 pub const KM: KeyEntryLoadBits = Self(1);
404 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
405 pub const PUBLIC: KeyEntryLoadBits = Self(2);
406 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
407 pub const BOTH: KeyEntryLoadBits = Self(3);
408
409 /// Returns true if this object indicates that the public components shall be loaded.
410 pub const fn load_public(&self) -> bool {
411 self.0 & Self::PUBLIC.0 != 0
412 }
413
414 /// Returns true if the object indicates that the KeyMint component shall be loaded.
415 pub const fn load_km(&self) -> bool {
416 self.0 & Self::KM.0 != 0
417 }
418}
419
Janis Danisevskisaec14592020-11-12 09:41:49 -0800420lazy_static! {
421 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
422}
423
424struct KeyIdLockDb {
425 locked_keys: Mutex<HashSet<i64>>,
426 cond_var: Condvar,
427}
428
429/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
430/// from the database a second time. Most functions manipulating the key blob database
431/// require a KeyIdGuard.
432#[derive(Debug)]
433pub struct KeyIdGuard(i64);
434
435impl KeyIdLockDb {
436 fn new() -> Self {
437 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
438 }
439
440 /// This function blocks until an exclusive lock for the given key entry id can
441 /// be acquired. It returns a guard object, that represents the lifecycle of the
442 /// acquired lock.
443 pub fn get(&self, key_id: i64) -> KeyIdGuard {
444 let mut locked_keys = self.locked_keys.lock().unwrap();
445 while locked_keys.contains(&key_id) {
446 locked_keys = self.cond_var.wait(locked_keys).unwrap();
447 }
448 locked_keys.insert(key_id);
449 KeyIdGuard(key_id)
450 }
451
452 /// This function attempts to acquire an exclusive lock on a given key id. If the
453 /// given key id is already taken the function returns None immediately. If a lock
454 /// can be acquired this function returns a guard object, that represents the
455 /// lifecycle of the acquired lock.
456 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
457 let mut locked_keys = self.locked_keys.lock().unwrap();
458 if locked_keys.insert(key_id) {
459 Some(KeyIdGuard(key_id))
460 } else {
461 None
462 }
463 }
464}
465
466impl KeyIdGuard {
467 /// Get the numeric key id of the locked key.
468 pub fn id(&self) -> i64 {
469 self.0
470 }
471}
472
473impl Drop for KeyIdGuard {
474 fn drop(&mut self) {
475 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
476 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800477 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800478 KEY_ID_LOCK.cond_var.notify_all();
479 }
480}
481
Max Bires8e93d2b2021-01-14 13:17:59 -0800482/// This type represents a certificate and certificate chain entry for a key.
483#[derive(Debug)]
484pub struct CertificateInfo {
485 cert: Option<Vec<u8>>,
486 cert_chain: Option<Vec<u8>>,
487}
488
489impl CertificateInfo {
490 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
491 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
492 Self { cert, cert_chain }
493 }
494
495 /// Take the cert
496 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
497 self.cert.take()
498 }
499
500 /// Take the cert chain
501 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
502 self.cert_chain.take()
503 }
504}
505
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700506/// This type represents a Keystore 2.0 key entry.
507/// An entry has a unique `id` by which it can be found in the database.
508/// It has a security level field, key parameters, and three optional fields
509/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800510#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700511pub struct KeyEntry {
512 id: i64,
513 km_blob: Option<Vec<u8>>,
514 cert: Option<Vec<u8>>,
515 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800516 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700517 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800518 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800519 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700520}
521
522impl KeyEntry {
523 /// Returns the unique id of the Key entry.
524 pub fn id(&self) -> i64 {
525 self.id
526 }
527 /// Exposes the optional KeyMint blob.
528 pub fn km_blob(&self) -> &Option<Vec<u8>> {
529 &self.km_blob
530 }
531 /// Extracts the Optional KeyMint blob.
532 pub fn take_km_blob(&mut self) -> Option<Vec<u8>> {
533 self.km_blob.take()
534 }
535 /// Exposes the optional public certificate.
536 pub fn cert(&self) -> &Option<Vec<u8>> {
537 &self.cert
538 }
539 /// Extracts the optional public certificate.
540 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
541 self.cert.take()
542 }
543 /// Exposes the optional public certificate chain.
544 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
545 &self.cert_chain
546 }
547 /// Extracts the optional public certificate_chain.
548 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
549 self.cert_chain.take()
550 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800551 /// Returns the uuid of the owning KeyMint instance.
552 pub fn km_uuid(&self) -> &Uuid {
553 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700554 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700555 /// Exposes the key parameters of this key entry.
556 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
557 &self.parameters
558 }
559 /// Consumes this key entry and extracts the keyparameters from it.
560 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
561 self.parameters
562 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800563 /// Exposes the key metadata of this key entry.
564 pub fn metadata(&self) -> &KeyMetaData {
565 &self.metadata
566 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800567 /// This returns true if the entry is a pure certificate entry with no
568 /// private key component.
569 pub fn pure_cert(&self) -> bool {
570 self.pure_cert
571 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700572}
573
574/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800575#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700576pub struct SubComponentType(u32);
577impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800578 /// Persistent identifier for a key blob.
579 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700580 /// Persistent identifier for a certificate blob.
581 pub const CERT: SubComponentType = Self(1);
582 /// Persistent identifier for a certificate chain blob.
583 pub const CERT_CHAIN: SubComponentType = Self(2);
584}
585
586impl ToSql for SubComponentType {
587 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
588 self.0.to_sql()
589 }
590}
591
592impl FromSql for SubComponentType {
593 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
594 Ok(Self(u32::column_result(value)?))
595 }
596}
597
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700598/// KeystoreDB wraps a connection to an SQLite database and tracks its
599/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700600pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700601 conn: Connection,
602}
603
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000604/// Database representation of the monotonic time retrieved from the system call clock_gettime with
605/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds.
606#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
607pub struct MonotonicRawTime(i64);
608
609impl MonotonicRawTime {
610 /// Constructs a new MonotonicRawTime
611 pub fn now() -> Self {
612 Self(get_current_time_in_seconds())
613 }
614
615 /// Returns the integer value of MonotonicRawTime as i64
616 pub fn seconds(&self) -> i64 {
617 self.0
618 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800619
620 /// Like i64::checked_sub.
621 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
622 self.0.checked_sub(other.0).map(Self)
623 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000624}
625
626impl ToSql for MonotonicRawTime {
627 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
628 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
629 }
630}
631
632impl FromSql for MonotonicRawTime {
633 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
634 Ok(Self(i64::column_result(value)?))
635 }
636}
637
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000638/// This struct encapsulates the information to be stored in the database about the auth tokens
639/// received by keystore.
640pub struct AuthTokenEntry {
641 auth_token: HardwareAuthToken,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000642 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000643}
644
645impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000646 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000647 AuthTokenEntry { auth_token, time_received }
648 }
649
650 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800651 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000652 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800653 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
654 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000655 })
656 }
657
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000658 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800659 pub fn auth_token(&self) -> &HardwareAuthToken {
660 &self.auth_token
661 }
662
663 /// Returns the auth token wrapped by the AuthTokenEntry
664 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000665 self.auth_token
666 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800667
668 /// Returns the time that this auth token was received.
669 pub fn time_received(&self) -> MonotonicRawTime {
670 self.time_received
671 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000672}
673
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800674/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
675/// This object does not allow access to the database connection. But it keeps a database
676/// connection alive in order to keep the in memory per boot database alive.
677pub struct PerBootDbKeepAlive(Connection);
678
Joel Galenson26f4d012020-07-17 14:57:21 -0700679impl KeystoreDB {
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800680 const PERBOOT_DB_FILE_NAME: &'static str = &"file:perboot.sqlite?mode=memory&cache=shared";
681
682 /// This creates a PerBootDbKeepAlive object to keep the per boot database alive.
683 pub fn keep_perboot_db_alive() -> Result<PerBootDbKeepAlive> {
684 let conn = Connection::open_in_memory()
685 .context("In keep_perboot_db_alive: Failed to initialize SQLite connection.")?;
686
687 conn.execute("ATTACH DATABASE ? as perboot;", params![Self::PERBOOT_DB_FILE_NAME])
688 .context("In keep_perboot_db_alive: Failed to attach database perboot.")?;
689 Ok(PerBootDbKeepAlive(conn))
690 }
691
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700692 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800693 /// files persistent.sqlite and perboot.sqlite in the given directory.
694 /// It also attempts to initialize all of the tables.
695 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700696 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800697 pub fn new(db_root: &Path) -> Result<Self> {
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800698 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800699 let mut persistent_path = db_root.to_path_buf();
700 persistent_path.push("persistent.sqlite");
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700701
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800702 // Now convert them to strings prefixed with "file:"
703 let mut persistent_path_str = "file:".to_owned();
704 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800705
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800706 let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?;
Janis Danisevskisaea27342021-01-29 08:38:11 -0800707 conn.busy_handler(Some(|_| {
708 std::thread::sleep(std::time::Duration::from_micros(50));
709 true
710 }))
711 .context("In KeystoreDB::new: Failed to set busy handler.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800712
713 Self::init_tables(&conn)?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700714 Ok(Self { conn })
Joel Galenson2aab4432020-07-22 15:27:57 -0700715 }
716
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700717 fn init_tables(conn: &Connection) -> Result<()> {
718 conn.execute(
719 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700720 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800721 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700722 domain INTEGER,
723 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800724 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800725 state INTEGER,
726 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700727 NO_PARAMS,
728 )
729 .context("Failed to initialize \"keyentry\" table.")?;
730
731 conn.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700732 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
733 id INTEGER PRIMARY KEY,
734 subcomponent_type INTEGER,
735 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800736 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700737 NO_PARAMS,
738 )
739 .context("Failed to initialize \"blobentry\" table.")?;
740
741 conn.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700742 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000743 keyentryid INTEGER,
744 tag INTEGER,
745 data ANY,
746 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700747 NO_PARAMS,
748 )
749 .context("Failed to initialize \"keyparameter\" table.")?;
750
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700751 conn.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800752 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
753 keyentryid INTEGER,
754 tag INTEGER,
755 data ANY);",
756 NO_PARAMS,
757 )
758 .context("Failed to initialize \"keymetadata\" table.")?;
759
760 conn.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800761 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700762 id INTEGER UNIQUE,
763 grantee INTEGER,
764 keyentryid INTEGER,
765 access_vector INTEGER);",
766 NO_PARAMS,
767 )
768 .context("Failed to initialize \"grant\" table.")?;
769
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000770 //TODO: only drop the following two perboot tables if this is the first start up
771 //during the boot (b/175716626).
772 // conn.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS)
773 // .context("Failed to drop perboot.authtoken table")?;
774 conn.execute(
775 "CREATE TABLE IF NOT EXISTS perboot.authtoken (
776 id INTEGER PRIMARY KEY,
777 challenge INTEGER,
778 user_id INTEGER,
779 auth_id INTEGER,
780 authenticator_type INTEGER,
781 timestamp INTEGER,
782 mac BLOB,
783 time_received INTEGER,
784 UNIQUE(user_id, auth_id, authenticator_type));",
785 NO_PARAMS,
786 )
787 .context("Failed to initialize \"authtoken\" table.")?;
788
789 // conn.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS)
790 // .context("Failed to drop perboot.metadata table")?;
791 // metadata table stores certain miscellaneous information required for keystore functioning
792 // during a boot cycle, as key-value pairs.
793 conn.execute(
794 "CREATE TABLE IF NOT EXISTS perboot.metadata (
795 key TEXT,
796 value BLOB,
797 UNIQUE(key));",
798 NO_PARAMS,
799 )
800 .context("Failed to initialize \"metadata\" table.")?;
Joel Galenson0891bc12020-07-20 10:37:03 -0700801 Ok(())
802 }
803
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700804 fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> {
805 let conn =
806 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
807
808 conn.execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
809 .context("Failed to attach database persistent.")?;
810 conn.execute("ATTACH DATABASE ? as perboot;", params![perboot_file])
811 .context("Failed to attach database perboot.")?;
812
813 Ok(conn)
814 }
815
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800816 /// Get one unreferenced key. There is no particular order in which the keys are returned.
817 fn get_unreferenced_key_id(tx: &Transaction) -> Result<Option<i64>> {
818 tx.query_row(
819 "SELECT id FROM persistent.keyentry WHERE state = ?",
820 params![KeyLifeCycle::Unreferenced],
821 |row| row.get(0),
822 )
823 .optional()
824 .context("In get_unreferenced_key_id: Trying to get unreferenced key id.")
825 }
826
827 /// Returns a key id guard and key entry for one unreferenced key entry. Of the optional
828 /// fields of the key entry only the km_blob field will be populated. This is required
829 /// to subject the blob to its KeyMint instance for deletion.
830 pub fn get_unreferenced_key(&mut self) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
831 self.with_transaction(TransactionBehavior::Deferred, |tx| {
832 let key_id = match Self::get_unreferenced_key_id(tx)
833 .context("Trying to get unreferenced key id")?
834 {
835 None => return Ok(None),
836 Some(id) => KEY_ID_LOCK.try_get(id).ok_or_else(KsError::sys).context(concat!(
837 "A key id lock was held for an unreferenced key. ",
838 "This should never happen."
839 ))?,
840 };
841 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id.id())
842 .context("Trying to get key components.")?;
843 Ok(Some((key_id, key_entry)))
844 })
845 .context("In get_unreferenced_key.")
846 }
847
848 /// This function purges all remnants of a key entry from the database.
849 /// Important: This does not check if the key was unreferenced, nor does it
850 /// subject the key to its KeyMint instance for permanent invalidation.
851 /// This function should only be called by the garbage collector.
852 /// To delete a key call `mark_unreferenced`, which transitions the key to the unreferenced
853 /// state, deletes all grants to the key, and notifies the garbage collector.
854 /// The garbage collector will:
855 /// 1. Call get_unreferenced_key.
856 /// 2. Determine the proper way to dispose of sensitive key material, e.g., call
857 /// `KeyMintDevice::delete()`.
858 /// 3. Call `purge_key_entry`.
859 pub fn purge_key_entry(&mut self, key_id: KeyIdGuard) -> Result<()> {
860 self.with_transaction(TransactionBehavior::Immediate, |tx| {
861 tx.execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id.id()])
862 .context("Trying to delete keyentry.")?;
863 tx.execute(
864 "DELETE FROM persistent.blobentry WHERE keyentryid = ?;",
865 params![key_id.id()],
866 )
867 .context("Trying to delete blobentries.")?;
868 tx.execute(
869 "DELETE FROM persistent.keymetadata WHERE keyentryid = ?;",
870 params![key_id.id()],
871 )
872 .context("Trying to delete keymetadata.")?;
873 tx.execute(
874 "DELETE FROM persistent.keyparameter WHERE keyentryid = ?;",
875 params![key_id.id()],
876 )
877 .context("Trying to delete keyparameters.")?;
878 let grants_deleted = tx
879 .execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id.id()])
880 .context("Trying to delete grants.")?;
881 if grants_deleted != 0 {
882 log::error!("Purged key that still had grants. This should not happen.");
883 }
884 Ok(())
885 })
886 .context("In purge_key_entry.")
887 }
888
889 /// This maintenance function should be called only once before the database is used for the
890 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
891 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
892 /// returns the number of rows affected. If this returns a value greater than 0, it means that
893 /// Keystore crashed at some point during key generation. Callers may want to log such
894 /// occurrences.
895 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
896 /// it to `KeyLifeCycle::Live` may have grants.
897 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
898 self.conn
899 .execute(
900 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
901 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
902 )
903 .context("In cleanup_leftovers.")
904 }
905
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800906 /// Atomically loads a key entry and associated metadata or creates it using the
907 /// callback create_new_key callback. The callback is called during a database
908 /// transaction. This means that implementers should be mindful about using
909 /// blocking operations such as IPC or grabbing mutexes.
910 pub fn get_or_create_key_with<F>(
911 &mut self,
912 domain: Domain,
913 namespace: i64,
914 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -0800915 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800916 create_new_key: F,
917 ) -> Result<(KeyIdGuard, KeyEntry)>
918 where
919 F: FnOnce() -> Result<(Vec<u8>, KeyMetaData)>,
920 {
921 let tx = self
922 .conn
923 .transaction_with_behavior(TransactionBehavior::Immediate)
924 .context("In get_or_create_key_with: Failed to initialize transaction.")?;
925
926 let id = {
927 let mut stmt = tx
928 .prepare(
929 "SELECT id FROM persistent.keyentry
930 WHERE
931 key_type = ?
932 AND domain = ?
933 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800934 AND alias = ?
935 AND state = ?;",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800936 )
937 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
938 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800939 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800940 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
941
942 db_utils::with_rows_extract_one(&mut rows, |row| {
943 Ok(match row {
944 Some(r) => r.get(0).context("Failed to unpack id.")?,
945 None => None,
946 })
947 })
948 .context("In get_or_create_key_with.")?
949 };
950
951 let (id, entry) = match id {
952 Some(id) => (
953 id,
954 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
955 .context("In get_or_create_key_with.")?,
956 ),
957
958 None => {
959 let id = Self::insert_with_retry(|id| {
960 tx.execute(
961 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -0800962 (id, key_type, domain, namespace, alias, state, km_uuid)
963 VALUES(?, ?, ?, ?, ?, ?, ?);",
964 params![
965 id,
966 KeyType::Super,
967 domain.0,
968 namespace,
969 alias,
970 KeyLifeCycle::Live,
971 km_uuid,
972 ],
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800973 )
974 })
975 .context("In get_or_create_key_with.")?;
976
977 let (blob, metadata) = create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -0800978 Self::set_blob_internal(&tx, id, SubComponentType::KEY_BLOB, Some(&blob))
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800979 .context("In get_of_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800980 metadata.store_in_db(id, &tx).context("In get_or_create_key_with.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -0800981 (
982 id,
983 KeyEntry {
984 id,
985 km_blob: Some(blob),
986 metadata,
987 pure_cert: false,
988 ..Default::default()
989 },
990 )
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800991 }
992 };
993 tx.commit().context("In get_or_create_key_with: Failed to commit transaction.")?;
994 Ok((KEY_ID_LOCK.get(id), entry))
995 }
996
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800997 /// Creates a transaction with the given behavior and executes f with the new transaction.
998 /// The transaction is committed only if f returns Ok.
999 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1000 where
1001 F: FnOnce(&Transaction) -> Result<T>,
1002 {
1003 let tx = self
1004 .conn
1005 .transaction_with_behavior(behavior)
1006 .context("In with_transaction: Failed to initialize transaction.")?;
1007 f(&tx).and_then(|result| {
1008 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1009 Ok(result)
1010 })
1011 }
1012
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001013 /// Creates a new key entry and allocates a new randomized id for the new key.
1014 /// The key id gets associated with a domain and namespace but not with an alias.
1015 /// To complete key generation `rebind_alias` should be called after all of the
1016 /// key artifacts, i.e., blobs and parameters have been associated with the new
1017 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1018 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001019 pub fn create_key_entry(
1020 &mut self,
1021 domain: Domain,
1022 namespace: i64,
1023 km_uuid: &Uuid,
1024 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001025 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Max Bires8e93d2b2021-01-14 13:17:59 -08001026 Self::create_key_entry_internal(tx, domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001027 })
1028 .context("In create_key_entry.")
1029 }
1030
1031 fn create_key_entry_internal(
1032 tx: &Transaction,
1033 domain: Domain,
1034 namespace: i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001035 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001036 ) -> Result<KeyIdGuard> {
Joel Galenson0891bc12020-07-20 10:37:03 -07001037 match domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001038 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001039 _ => {
1040 return Err(KsError::sys())
1041 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1042 }
1043 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001044 Ok(KEY_ID_LOCK.get(
1045 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001046 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001047 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001048 (id, key_type, domain, namespace, alias, state, km_uuid)
1049 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001050 params![
1051 id,
1052 KeyType::Client,
1053 domain.0 as u32,
1054 namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001055 KeyLifeCycle::Existing,
1056 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001057 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001058 )
1059 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001060 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001061 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001062 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001063
Janis Danisevskis377d1002021-01-27 19:07:48 -08001064 /// Set a new blob and associates it with the given key id. Each blob
1065 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001066 /// Each key can have one of each sub component type associated. If more
1067 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001068 /// will get garbage collected.
1069 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1070 /// removed by setting blob to None.
1071 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001072 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001073 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001074 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001075 blob: Option<&[u8]>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001076 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001077 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001078 Self::set_blob_internal(&tx, key_id.0, sc_type, blob)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001079 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001080 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001081 }
1082
Janis Danisevskis377d1002021-01-27 19:07:48 -08001083 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001084 tx: &Transaction,
1085 key_id: i64,
1086 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001087 blob: Option<&[u8]>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001088 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001089 match (blob, sc_type) {
1090 (Some(blob), _) => {
1091 tx.execute(
1092 "INSERT INTO persistent.blobentry
1093 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1094 params![sc_type, key_id, blob],
1095 )
1096 .context("In set_blob_internal: Failed to insert blob.")?;
1097 }
1098 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1099 tx.execute(
1100 "DELETE FROM persistent.blobentry
1101 WHERE subcomponent_type = ? AND keyentryid = ?;",
1102 params![sc_type, key_id],
1103 )
1104 .context("In set_blob_internal: Failed to delete blob.")?;
1105 }
1106 (None, _) => {
1107 return Err(KsError::sys())
1108 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1109 }
1110 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001111 Ok(())
1112 }
1113
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001114 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1115 /// and associates them with the given `key_id`.
1116 pub fn insert_keyparameter<'a>(
1117 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001118 key_id: &KeyIdGuard,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001119 params: impl IntoIterator<Item = &'a KeyParameter>,
1120 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001121 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1122 Self::insert_keyparameter_internal(tx, key_id, params)
1123 })
1124 .context("In insert_keyparameter.")
1125 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001126
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001127 fn insert_keyparameter_internal<'a>(
1128 tx: &Transaction,
1129 key_id: &KeyIdGuard,
1130 params: impl IntoIterator<Item = &'a KeyParameter>,
1131 ) -> Result<()> {
1132 let mut stmt = tx
1133 .prepare(
1134 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1135 VALUES (?, ?, ?, ?);",
1136 )
1137 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1138
1139 let iter = params.into_iter();
1140 for p in iter {
1141 stmt.insert(params![
1142 key_id.0,
1143 p.get_tag().0,
1144 p.key_parameter_value(),
1145 p.security_level().0
1146 ])
1147 .with_context(|| {
1148 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1149 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001150 }
1151 Ok(())
1152 }
1153
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001154 /// Insert a set of key entry specific metadata into the database.
1155 pub fn insert_key_metadata(
1156 &mut self,
1157 key_id: &KeyIdGuard,
1158 metadata: &KeyMetaData,
1159 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001160 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1161 metadata.store_in_db(key_id.0, &tx)
1162 })
1163 .context("In insert_key_metadata.")
1164 }
1165
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001166 /// Updates the alias column of the given key id `newid` with the given alias,
1167 /// and atomically, removes the alias, domain, and namespace from another row
1168 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001169 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1170 /// collector.
1171 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001172 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001173 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001174 alias: &str,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001175 domain: Domain,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001176 namespace: i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001177 ) -> Result<bool> {
Joel Galenson33c04ad2020-08-03 11:04:38 -07001178 match domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001179 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001180 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001181 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001182 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001183 domain
1184 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001185 }
1186 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001187 let updated = tx
1188 .execute(
1189 "UPDATE persistent.keyentry
1190 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07001191 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001192 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
1193 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001194 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001195 let result = tx
1196 .execute(
1197 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001198 SET alias = ?, state = ?
1199 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
1200 params![
1201 alias,
1202 KeyLifeCycle::Live,
1203 newid.0,
1204 domain.0 as u32,
1205 namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001206 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001207 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001208 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001209 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001210 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07001211 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001212 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001213 result
1214 ));
1215 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001216 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001217 }
1218
1219 /// Store a new key in a single transaction.
1220 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1221 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001222 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1223 /// is now unreferenced and needs to be collected.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001224 pub fn store_new_key<'a>(
1225 &mut self,
1226 key: KeyDescriptor,
1227 params: impl IntoIterator<Item = &'a KeyParameter>,
1228 blob: &[u8],
Max Bires8e93d2b2021-01-14 13:17:59 -08001229 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001230 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001231 km_uuid: &Uuid,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001232 ) -> Result<(bool, KeyIdGuard)> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001233 let (alias, domain, namespace) = match key {
1234 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1235 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1236 (alias, key.domain, nspace)
1237 }
1238 _ => {
1239 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1240 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
1241 }
1242 };
1243 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Max Bires8e93d2b2021-01-14 13:17:59 -08001244 let key_id = Self::create_key_entry_internal(tx, domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001245 .context("Trying to create new key entry.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001246 Self::set_blob_internal(tx, key_id.id(), SubComponentType::KEY_BLOB, Some(blob))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001247 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001248 if let Some(cert) = &cert_info.cert {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001249 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001250 .context("Trying to insert the certificate.")?;
1251 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001252 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001253 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001254 tx,
1255 key_id.id(),
1256 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001257 Some(&cert_chain),
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001258 )
1259 .context("Trying to insert the certificate chain.")?;
1260 }
1261 Self::insert_keyparameter_internal(tx, &key_id, params)
1262 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001263 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001264 let need_gc = Self::rebind_alias(tx, &key_id, &alias, domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001265 .context("Trying to rebind alias.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001266 Ok((need_gc, key_id))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001267 })
1268 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001269 }
1270
Janis Danisevskis377d1002021-01-27 19:07:48 -08001271 /// Store a new certificate
1272 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1273 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001274 pub fn store_new_certificate(
1275 &mut self,
1276 key: KeyDescriptor,
1277 cert: &[u8],
1278 km_uuid: &Uuid,
1279 ) -> Result<KeyIdGuard> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001280 let (alias, domain, namespace) = match key {
1281 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1282 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1283 (alias, key.domain, nspace)
1284 }
1285 _ => {
1286 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
1287 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
1288 )
1289 }
1290 };
1291 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Max Bires8e93d2b2021-01-14 13:17:59 -08001292 let key_id = Self::create_key_entry_internal(tx, domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001293 .context("Trying to create new key entry.")?;
1294
1295 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT_CHAIN, Some(cert))
1296 .context("Trying to insert certificate.")?;
1297
1298 let mut metadata = KeyMetaData::new();
1299 metadata.add(KeyMetaEntry::CreationDate(
1300 DateTime::now().context("Trying to make creation time.")?,
1301 ));
1302
1303 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1304
1305 Self::rebind_alias(tx, &key_id, &alias, domain, namespace)
1306 .context("Trying to rebind alias.")?;
1307 Ok(key_id)
1308 })
1309 .context("In store_new_certificate.")
1310 }
1311
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001312 // Helper function loading the key_id given the key descriptor
1313 // tuple comprising domain, namespace, and alias.
1314 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001315 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001316 let alias = key
1317 .alias
1318 .as_ref()
1319 .map_or_else(|| Err(KsError::sys()), Ok)
1320 .context("In load_key_entry_id: Alias must be specified.")?;
1321 let mut stmt = tx
1322 .prepare(
1323 "SELECT id FROM persistent.keyentry
1324 WHERE
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001325 key_type = ?
1326 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001327 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001328 AND alias = ?
1329 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001330 )
1331 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1332 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001333 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001334 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001335 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001336 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001337 .get(0)
1338 .context("Failed to unpack id.")
1339 })
1340 .context("In load_key_entry_id.")
1341 }
1342
1343 /// This helper function completes the access tuple of a key, which is required
1344 /// to perform access control. The strategy depends on the `domain` field in the
1345 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001346 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001347 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001348 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001349 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001350 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001351 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001352 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001353 /// `namespace`.
1354 /// In each case the information returned is sufficient to perform the access
1355 /// check and the key id can be used to load further key artifacts.
1356 fn load_access_tuple(
1357 tx: &Transaction,
1358 key: KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001359 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001360 caller_uid: u32,
1361 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
1362 match key.domain {
1363 // Domain App or SELinux. In this case we load the key_id from
1364 // the keyentry database for further loading of key components.
1365 // We already have the full access tuple to perform access control.
1366 // The only distinction is that we use the caller_uid instead
1367 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001368 // Domain::APP.
1369 Domain::APP | Domain::SELINUX => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001370 let mut access_key = key;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001371 if access_key.domain == Domain::APP {
1372 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001373 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001374 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001375 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001376
1377 Ok((key_id, access_key, None))
1378 }
1379
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001380 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001381 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001382 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001383 let mut stmt = tx
1384 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001385 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001386 WHERE grantee = ? AND id = ?;",
1387 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001388 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001389 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001390 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001391 .context("Domain:Grant: query failed.")?;
1392 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001393 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001394 let r =
1395 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001396 Ok((
1397 r.get(0).context("Failed to unpack key_id.")?,
1398 r.get(1).context("Failed to unpack access_vector.")?,
1399 ))
1400 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001401 .context("Domain::GRANT.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001402 Ok((key_id, key, Some(access_vector.into())))
1403 }
1404
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001405 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001406 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001407 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08001408 let (domain, namespace): (Domain, i64) = {
1409 let mut stmt = tx
1410 .prepare(
1411 "SELECT domain, namespace FROM persistent.keyentry
1412 WHERE
1413 id = ?
1414 AND state = ?;",
1415 )
1416 .context("Domain::KEY_ID: prepare statement failed")?;
1417 let mut rows = stmt
1418 .query(params![key.nspace, KeyLifeCycle::Live])
1419 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001420 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001421 let r =
1422 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001423 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001424 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001425 r.get(1).context("Failed to unpack namespace.")?,
1426 ))
1427 })
Janis Danisevskis45760022021-01-19 16:34:10 -08001428 .context("Domain::KEY_ID.")?
1429 };
1430
1431 // We may use a key by id after loading it by grant.
1432 // In this case we have to check if the caller has a grant for this particular
1433 // key. We can skip this if we already know that the caller is the owner.
1434 // But we cannot know this if domain is anything but App. E.g. in the case
1435 // of Domain::SELINUX we have to speculatively check for grants because we have to
1436 // consult the SEPolicy before we know if the caller is the owner.
1437 let access_vector: Option<KeyPermSet> =
1438 if domain != Domain::APP || namespace != caller_uid as i64 {
1439 let access_vector: Option<i32> = tx
1440 .query_row(
1441 "SELECT access_vector FROM persistent.grant
1442 WHERE grantee = ? AND keyentryid = ?;",
1443 params![caller_uid as i64, key.nspace],
1444 |row| row.get(0),
1445 )
1446 .optional()
1447 .context("Domain::KEY_ID: query grant failed.")?;
1448 access_vector.map(|p| p.into())
1449 } else {
1450 None
1451 };
1452
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001453 let key_id = key.nspace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001454 let mut access_key = key;
1455 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001456 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001457
Janis Danisevskis45760022021-01-19 16:34:10 -08001458 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001459 }
1460 _ => Err(anyhow!(KsError::sys())),
1461 }
1462 }
1463
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001464 fn load_blob_components(
1465 key_id: i64,
1466 load_bits: KeyEntryLoadBits,
1467 tx: &Transaction,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001468 ) -> Result<(bool, Option<Vec<u8>>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001469 let mut stmt = tx
1470 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001471 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001472 WHERE keyentryid = ? GROUP BY subcomponent_type;",
1473 )
1474 .context("In load_blob_components: prepare statement failed.")?;
1475
1476 let mut rows =
1477 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
1478
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001479 let mut km_blob: Option<Vec<u8>> = None;
1480 let mut cert_blob: Option<Vec<u8>> = None;
1481 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001482 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001483 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001484 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001485 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001486 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001487 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
1488 (SubComponentType::KEY_BLOB, _, true) => {
1489 km_blob = Some(row.get(2).context("Failed to extract KM blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001490 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001491 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001492 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001493 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001494 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001495 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001496 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001497 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001498 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001499 (SubComponentType::CERT, _, _)
1500 | (SubComponentType::CERT_CHAIN, _, _)
1501 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001502 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
1503 }
1504 Ok(())
1505 })
1506 .context("In load_blob_components.")?;
1507
Janis Danisevskis377d1002021-01-27 19:07:48 -08001508 Ok((has_km_blob, km_blob, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001509 }
1510
1511 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
1512 let mut stmt = tx
1513 .prepare(
1514 "SELECT tag, data, security_level from persistent.keyparameter
1515 WHERE keyentryid = ?;",
1516 )
1517 .context("In load_key_parameters: prepare statement failed.")?;
1518
1519 let mut parameters: Vec<KeyParameter> = Vec::new();
1520
1521 let mut rows =
1522 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001523 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001524 let tag = Tag(row.get(0).context("Failed to read tag.")?);
1525 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001526 parameters.push(
1527 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
1528 .context("Failed to read KeyParameter.")?,
1529 );
1530 Ok(())
1531 })
1532 .context("In load_key_parameters.")?;
1533
1534 Ok(parameters)
1535 }
1536
Qi Wub9433b52020-12-01 14:52:46 +08001537 /// Decrements the usage count of a limited use key. This function first checks whether the
1538 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
1539 /// zero, the key also gets marked unreferenced and scheduled for deletion.
1540 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
1541 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<bool> {
1542 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1543 let limit: Option<i32> = tx
1544 .query_row(
1545 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
1546 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
1547 |row| row.get(0),
1548 )
1549 .optional()
1550 .context("Trying to load usage count")?;
1551
1552 let limit = limit
1553 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
1554 .context("The Key no longer exists. Key is exhausted.")?;
1555
1556 tx.execute(
1557 "UPDATE persistent.keyparameter
1558 SET data = data - 1
1559 WHERE keyentryid = ? AND tag = ? AND data > 0;",
1560 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
1561 )
1562 .context("Failed to update key usage count.")?;
1563
1564 match limit {
1565 1 => Self::mark_unreferenced(tx, key_id)
1566 .context("Trying to mark limited use key for deletion."),
1567 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
1568 _ => Ok(false),
1569 }
1570 })
1571 .context("In check_and_update_key_usage_count.")
1572 }
1573
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001574 /// Load a key entry by the given key descriptor.
1575 /// It uses the `check_permission` callback to verify if the access is allowed
1576 /// given the key access tuple read from the database using `load_access_tuple`.
1577 /// With `load_bits` the caller may specify which blobs shall be loaded from
1578 /// the blob database.
1579 pub fn load_key_entry(
1580 &mut self,
1581 key: KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001582 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001583 load_bits: KeyEntryLoadBits,
1584 caller_uid: u32,
1585 check_permission: impl FnOnce(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001586 ) -> Result<(KeyIdGuard, KeyEntry)> {
1587 // KEY ID LOCK 1/2
1588 // If we got a key descriptor with a key id we can get the lock right away.
1589 // Otherwise we have to defer it until we know the key id.
1590 let key_id_guard = match key.domain {
1591 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
1592 _ => None,
1593 };
1594
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001595 let tx = self
1596 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08001597 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001598 .context("In load_key_entry: Failed to initialize transaction.")?;
1599
1600 // Load the key_id and complete the access control tuple.
1601 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001602 Self::load_access_tuple(&tx, key, key_type, caller_uid)
1603 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001604
1605 // Perform access control. It is vital that we return here if the permission is denied.
1606 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001607 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001608
Janis Danisevskisaec14592020-11-12 09:41:49 -08001609 // KEY ID LOCK 2/2
1610 // If we did not get a key id lock by now, it was because we got a key descriptor
1611 // without a key id. At this point we got the key id, so we can try and get a lock.
1612 // However, we cannot block here, because we are in the middle of the transaction.
1613 // So first we try to get the lock non blocking. If that fails, we roll back the
1614 // transaction and block until we get the lock. After we successfully got the lock,
1615 // we start a new transaction and load the access tuple again.
1616 //
1617 // We don't need to perform access control again, because we already established
1618 // that the caller had access to the given key. But we need to make sure that the
1619 // key id still exists. So we have to load the key entry by key id this time.
1620 let (key_id_guard, tx) = match key_id_guard {
1621 None => match KEY_ID_LOCK.try_get(key_id) {
1622 None => {
1623 // Roll back the transaction.
1624 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001625
Janis Danisevskisaec14592020-11-12 09:41:49 -08001626 // Block until we have a key id lock.
1627 let key_id_guard = KEY_ID_LOCK.get(key_id);
1628
1629 // Create a new transaction.
1630 let tx = self.conn.unchecked_transaction().context(
1631 "In load_key_entry: Failed to initialize transaction. (deferred key lock)",
1632 )?;
1633
1634 Self::load_access_tuple(
1635 &tx,
1636 // This time we have to load the key by the retrieved key id, because the
1637 // alias may have been rebound after we rolled back the transaction.
1638 KeyDescriptor {
1639 domain: Domain::KEY_ID,
1640 nspace: key_id,
1641 ..Default::default()
1642 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001643 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001644 caller_uid,
1645 )
1646 .context("In load_key_entry. (deferred key lock)")?;
1647 (key_id_guard, tx)
1648 }
1649 Some(l) => (l, tx),
1650 },
1651 Some(key_id_guard) => (key_id_guard, tx),
1652 };
1653
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001654 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
1655 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001656
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001657 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
1658
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001659 Ok((key_id_guard, key_entry))
1660 }
1661
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001662 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001663 let updated = tx
1664 .execute(
1665 "UPDATE persistent.keyentry SET state = ? WHERE id = ?;",
1666 params![KeyLifeCycle::Unreferenced, key_id],
1667 )
1668 .context("In mark_unreferenced: Failed to update state of key entry.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001669 tx.execute("DELETE from persistent.grant WHERE keyentryid = ?;", params![key_id])
1670 .context("In mark_unreferenced: Failed to drop grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001671 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001672 }
1673
1674 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001675 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001676 pub fn unbind_key(
1677 &mut self,
1678 key: KeyDescriptor,
1679 key_type: KeyType,
1680 caller_uid: u32,
1681 check_permission: impl FnOnce(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001682 ) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001683 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1684 let (key_id, access_key_descriptor, access_vector) =
1685 Self::load_access_tuple(tx, key, key_type, caller_uid)
1686 .context("Trying to get access tuple.")?;
1687
1688 // Perform access control. It is vital that we return here if the permission is denied.
1689 // So do not touch that '?' at the end.
1690 check_permission(&access_key_descriptor, access_vector)
1691 .context("While checking permission.")?;
1692
1693 Self::mark_unreferenced(tx, key_id).context("Trying to mark the key unreferenced.")
1694 })
1695 .context("In unbind_key.")
1696 }
1697
Max Bires8e93d2b2021-01-14 13:17:59 -08001698 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
1699 tx.query_row(
1700 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
1701 params![key_id],
1702 |row| row.get(0),
1703 )
1704 .context("In get_key_km_uuid.")
1705 }
1706
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001707 fn load_key_components(
1708 tx: &Transaction,
1709 load_bits: KeyEntryLoadBits,
1710 key_id: i64,
1711 ) -> Result<KeyEntry> {
1712 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
1713
Janis Danisevskis377d1002021-01-27 19:07:48 -08001714 let (has_km_blob, km_blob, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001715 Self::load_blob_components(key_id, load_bits, &tx)
1716 .context("In load_key_components.")?;
1717
Max Bires8e93d2b2021-01-14 13:17:59 -08001718 let parameters = Self::load_key_parameters(key_id, &tx)
1719 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001720
Max Bires8e93d2b2021-01-14 13:17:59 -08001721 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
1722 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001723
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001724 Ok(KeyEntry {
1725 id: key_id,
1726 km_blob,
1727 cert: cert_blob,
1728 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08001729 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001730 parameters,
1731 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001732 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001733 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001734 }
1735
Janis Danisevskise92a5e62020-12-02 12:57:41 -08001736 /// Returns a list of KeyDescriptors in the selected domain/namespace.
1737 /// The key descriptors will have the domain, nspace, and alias field set.
1738 /// Domain must be APP or SELINUX, the caller must make sure of that.
1739 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
1740 let mut stmt = self
1741 .conn
1742 .prepare(
1743 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001744 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskise92a5e62020-12-02 12:57:41 -08001745 )
1746 .context("In list: Failed to prepare.")?;
1747
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001748 let mut rows = stmt
1749 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
1750 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08001751
1752 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
1753 db_utils::with_rows_extract_all(&mut rows, |row| {
1754 descriptors.push(KeyDescriptor {
1755 domain,
1756 nspace: namespace,
1757 alias: Some(row.get(0).context("Trying to extract alias.")?),
1758 blob: None,
1759 });
1760 Ok(())
1761 })
1762 .context("In list.")?;
1763 Ok(descriptors)
1764 }
1765
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001766 /// Adds a grant to the grant table.
1767 /// Like `load_key_entry` this function loads the access tuple before
1768 /// it uses the callback for a permission check. Upon success,
1769 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
1770 /// grant table. The new row will have a randomized id, which is used as
1771 /// grant id in the namespace field of the resulting KeyDescriptor.
1772 pub fn grant(
1773 &mut self,
1774 key: KeyDescriptor,
1775 caller_uid: u32,
1776 grantee_uid: u32,
1777 access_vector: KeyPermSet,
1778 check_permission: impl FnOnce(&KeyDescriptor, &KeyPermSet) -> Result<()>,
1779 ) -> Result<KeyDescriptor> {
1780 let tx = self
1781 .conn
1782 .transaction_with_behavior(TransactionBehavior::Immediate)
1783 .context("In grant: Failed to initialize transaction.")?;
1784
1785 // Load the key_id and complete the access control tuple.
1786 // We ignore the access vector here because grants cannot be granted.
1787 // The access vector returned here expresses the permissions the
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001788 // grantee has if key.domain == Domain::GRANT. But this vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001789 // cannot include the grant permission by design, so there is no way the
1790 // subsequent permission check can pass.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001791 // We could check key.domain == Domain::GRANT and fail early.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001792 // But even if we load the access tuple by grant here, the permission
1793 // check denies the attempt to create a grant by grant descriptor.
1794 let (key_id, access_key_descriptor, _) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001795 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid).context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001796
1797 // Perform access control. It is vital that we return here if the permission
1798 // was denied. So do not touch that '?' at the end of the line.
1799 // This permission check checks if the caller has the grant permission
1800 // for the given key and in addition to all of the permissions
1801 // expressed in `access_vector`.
1802 check_permission(&access_key_descriptor, &access_vector)
1803 .context("In grant: check_permission failed.")?;
1804
1805 let grant_id = if let Some(grant_id) = tx
1806 .query_row(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001807 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001808 WHERE keyentryid = ? AND grantee = ?;",
1809 params![key_id, grantee_uid],
1810 |row| row.get(0),
1811 )
1812 .optional()
1813 .context("In grant: Failed get optional existing grant id.")?
1814 {
1815 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001816 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001817 SET access_vector = ?
1818 WHERE id = ?;",
1819 params![i32::from(access_vector), grant_id],
1820 )
1821 .context("In grant: Failed to update existing grant.")?;
1822 grant_id
1823 } else {
Joel Galenson845f74b2020-09-09 14:11:55 -07001824 Self::insert_with_retry(|id| {
1825 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001826 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001827 VALUES (?, ?, ?, ?);",
Joel Galenson845f74b2020-09-09 14:11:55 -07001828 params![id, grantee_uid, key_id, i32::from(access_vector)],
1829 )
1830 })
1831 .context("In grant")?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001832 };
1833 tx.commit().context("In grant: failed to commit transaction.")?;
1834
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001835 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001836 }
1837
1838 /// This function checks permissions like `grant` and `load_key_entry`
1839 /// before removing a grant from the grant table.
1840 pub fn ungrant(
1841 &mut self,
1842 key: KeyDescriptor,
1843 caller_uid: u32,
1844 grantee_uid: u32,
1845 check_permission: impl FnOnce(&KeyDescriptor) -> Result<()>,
1846 ) -> Result<()> {
1847 let tx = self
1848 .conn
1849 .transaction_with_behavior(TransactionBehavior::Immediate)
1850 .context("In ungrant: Failed to initialize transaction.")?;
1851
1852 // Load the key_id and complete the access control tuple.
1853 // We ignore the access vector here because grants cannot be granted.
1854 let (key_id, access_key_descriptor, _) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001855 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
1856 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001857
1858 // Perform access control. We must return here if the permission
1859 // was denied. So do not touch the '?' at the end of this line.
1860 check_permission(&access_key_descriptor).context("In grant: check_permission failed.")?;
1861
1862 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001863 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001864 WHERE keyentryid = ? AND grantee = ?;",
1865 params![key_id, grantee_uid],
1866 )
1867 .context("Failed to delete grant.")?;
1868
1869 tx.commit().context("In ungrant: failed to commit transaction.")?;
1870
1871 Ok(())
1872 }
1873
Joel Galenson845f74b2020-09-09 14:11:55 -07001874 // Generates a random id and passes it to the given function, which will
1875 // try to insert it into a database. If that insertion fails, retry;
1876 // otherwise return the id.
1877 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
1878 loop {
1879 let newid: i64 = random();
1880 match inserter(newid) {
1881 // If the id already existed, try again.
1882 Err(rusqlite::Error::SqliteFailure(
1883 libsqlite3_sys::Error {
1884 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
1885 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
1886 },
1887 _,
1888 )) => (),
1889 Err(e) => {
1890 return Err(e).context("In insert_with_retry: failed to insert into database.")
1891 }
1892 _ => return Ok(newid),
1893 }
1894 }
1895 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001896
1897 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
1898 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
1899 self.conn
1900 .execute(
1901 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
1902 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
1903 params![
1904 auth_token.challenge,
1905 auth_token.userId,
1906 auth_token.authenticatorId,
1907 auth_token.authenticatorType.0 as i32,
1908 auth_token.timestamp.milliSeconds as i64,
1909 auth_token.mac,
1910 MonotonicRawTime::now(),
1911 ],
1912 )
1913 .context("In insert_auth_token: failed to insert auth token into the database")?;
1914 Ok(())
1915 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001916
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001917 /// Find the newest auth token matching the given predicate.
1918 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001919 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001920 p: F,
1921 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
1922 where
1923 F: Fn(&AuthTokenEntry) -> bool,
1924 {
1925 self.with_transaction(TransactionBehavior::Deferred, |tx| {
1926 let mut stmt = tx
1927 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
1928 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001929
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001930 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001931
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001932 while let Some(row) = rows.next().context("Failed to get next row.")? {
1933 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001934 HardwareAuthToken {
1935 challenge: row.get(1)?,
1936 userId: row.get(2)?,
1937 authenticatorId: row.get(3)?,
1938 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
1939 timestamp: Timestamp { milliSeconds: row.get(5)? },
1940 mac: row.get(6)?,
1941 },
1942 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001943 );
1944 if p(&entry) {
1945 return Ok(Some((
1946 entry,
1947 Self::get_last_off_body(tx)
1948 .context("In find_auth_token_entry: Trying to get last off body")?,
1949 )));
1950 }
1951 }
1952 Ok(None)
1953 })
1954 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001955 }
1956
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001957 /// Insert last_off_body into the metadata table at the initialization of auth token table
1958 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) -> Result<()> {
1959 self.conn
1960 .execute(
1961 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
1962 params!["last_off_body", last_off_body],
1963 )
1964 .context("In insert_last_off_body: failed to insert.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001965 Ok(())
1966 }
1967
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001968 /// Update last_off_body when on_device_off_body is called
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001969 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) -> Result<()> {
1970 self.conn
1971 .execute(
1972 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
1973 params![last_off_body, "last_off_body"],
1974 )
1975 .context("In update_last_off_body: failed to update.")?;
1976 Ok(())
1977 }
1978
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001979 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001980 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08001981 tx.query_row(
1982 "SELECT value from perboot.metadata WHERE key = ?;",
1983 params!["last_off_body"],
1984 |row| Ok(row.get(0)?),
1985 )
1986 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00001987 }
Joel Galenson26f4d012020-07-17 14:57:21 -07001988}
1989
1990#[cfg(test)]
1991mod tests {
1992
1993 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001994 use crate::key_parameter::{
1995 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
1996 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
1997 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001998 use crate::key_perm_set;
1999 use crate::permission::{KeyPerm, KeyPermSet};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002000 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002001 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2002 HardwareAuthToken::HardwareAuthToken,
2003 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002004 };
2005 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002006 Timestamp::Timestamp,
2007 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002008 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002009 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07002010 use std::cell::RefCell;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002011 use std::sync::atomic::{AtomicU8, Ordering};
2012 use std::sync::Arc;
2013 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002014 use std::time::{Duration, SystemTime};
Joel Galenson0891bc12020-07-20 10:37:03 -07002015
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002016 fn new_test_db() -> Result<KeystoreDB> {
2017 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
2018
2019 KeystoreDB::init_tables(&conn).context("Failed to initialize tables.")?;
2020 Ok(KeystoreDB { conn })
2021 }
2022
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002023 fn rebind_alias(
2024 db: &mut KeystoreDB,
2025 newid: &KeyIdGuard,
2026 alias: &str,
2027 domain: Domain,
2028 namespace: i64,
2029 ) -> Result<bool> {
2030 db.with_transaction(TransactionBehavior::Immediate, |tx| {
2031 KeystoreDB::rebind_alias(tx, newid, alias, domain, namespace)
2032 })
2033 .context("In rebind_alias.")
2034 }
2035
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002036 #[test]
2037 fn datetime() -> Result<()> {
2038 let conn = Connection::open_in_memory()?;
2039 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
2040 let now = SystemTime::now();
2041 let duration = Duration::from_secs(1000);
2042 let then = now.checked_sub(duration).unwrap();
2043 let soon = now.checked_add(duration).unwrap();
2044 conn.execute(
2045 "INSERT INTO test (ts) VALUES (?), (?), (?);",
2046 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
2047 )?;
2048 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
2049 let mut rows = stmt.query(NO_PARAMS)?;
2050 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
2051 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
2052 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
2053 assert!(rows.next()?.is_none());
2054 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
2055 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
2056 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
2057 Ok(())
2058 }
2059
Joel Galenson0891bc12020-07-20 10:37:03 -07002060 // Ensure that we're using the "injected" random function, not the real one.
2061 #[test]
2062 fn test_mocked_random() {
2063 let rand1 = random();
2064 let rand2 = random();
2065 let rand3 = random();
2066 if rand1 == rand2 {
2067 assert_eq!(rand2 + 1, rand3);
2068 } else {
2069 assert_eq!(rand1 + 1, rand2);
2070 assert_eq!(rand2, rand3);
2071 }
2072 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002073
Joel Galenson26f4d012020-07-17 14:57:21 -07002074 // Test that we have the correct tables.
2075 #[test]
2076 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002077 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07002078 let tables = db
2079 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07002080 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07002081 .query_map(params![], |row| row.get(0))?
2082 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002083 assert_eq!(tables.len(), 5);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002084 assert_eq!(tables[0], "blobentry");
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002085 assert_eq!(tables[1], "grant");
2086 assert_eq!(tables[2], "keyentry");
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002087 assert_eq!(tables[3], "keymetadata");
2088 assert_eq!(tables[4], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002089 let tables = db
2090 .conn
2091 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
2092 .query_map(params![], |row| row.get(0))?
2093 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002094
2095 assert_eq!(tables.len(), 2);
2096 assert_eq!(tables[0], "authtoken");
2097 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07002098 Ok(())
2099 }
2100
2101 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002102 fn test_auth_token_table_invariant() -> Result<()> {
2103 let mut db = new_test_db()?;
2104 let auth_token1 = HardwareAuthToken {
2105 challenge: i64::MAX,
2106 userId: 200,
2107 authenticatorId: 200,
2108 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2109 timestamp: Timestamp { milliSeconds: 500 },
2110 mac: String::from("mac").into_bytes(),
2111 };
2112 db.insert_auth_token(&auth_token1)?;
2113 let auth_tokens_returned = get_auth_tokens(&mut db)?;
2114 assert_eq!(auth_tokens_returned.len(), 1);
2115
2116 // insert another auth token with the same values for the columns in the UNIQUE constraint
2117 // of the auth token table and different value for timestamp
2118 let auth_token2 = HardwareAuthToken {
2119 challenge: i64::MAX,
2120 userId: 200,
2121 authenticatorId: 200,
2122 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2123 timestamp: Timestamp { milliSeconds: 600 },
2124 mac: String::from("mac").into_bytes(),
2125 };
2126
2127 db.insert_auth_token(&auth_token2)?;
2128 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
2129 assert_eq!(auth_tokens_returned.len(), 1);
2130
2131 if let Some(auth_token) = auth_tokens_returned.pop() {
2132 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
2133 }
2134
2135 // insert another auth token with the different values for the columns in the UNIQUE
2136 // constraint of the auth token table
2137 let auth_token3 = HardwareAuthToken {
2138 challenge: i64::MAX,
2139 userId: 201,
2140 authenticatorId: 200,
2141 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2142 timestamp: Timestamp { milliSeconds: 600 },
2143 mac: String::from("mac").into_bytes(),
2144 };
2145
2146 db.insert_auth_token(&auth_token3)?;
2147 let auth_tokens_returned = get_auth_tokens(&mut db)?;
2148 assert_eq!(auth_tokens_returned.len(), 2);
2149
2150 Ok(())
2151 }
2152
2153 // utility function for test_auth_token_table_invariant()
2154 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
2155 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
2156
2157 let auth_token_entries: Vec<AuthTokenEntry> = stmt
2158 .query_map(NO_PARAMS, |row| {
2159 Ok(AuthTokenEntry::new(
2160 HardwareAuthToken {
2161 challenge: row.get(1)?,
2162 userId: row.get(2)?,
2163 authenticatorId: row.get(3)?,
2164 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
2165 timestamp: Timestamp { milliSeconds: row.get(5)? },
2166 mac: row.get(6)?,
2167 },
2168 row.get(7)?,
2169 ))
2170 })?
2171 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
2172 Ok(auth_token_entries)
2173 }
2174
2175 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07002176 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002177 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002178 let mut db = KeystoreDB::new(temp_dir.path())?;
Joel Galenson2aab4432020-07-22 15:27:57 -07002179
Max Bires8e93d2b2021-01-14 13:17:59 -08002180 db.create_key_entry(Domain::APP, 100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07002181 let entries = get_keyentry(&db)?;
2182 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002183
2184 let db = KeystoreDB::new(temp_dir.path())?;
Joel Galenson2aab4432020-07-22 15:27:57 -07002185
2186 let entries_new = get_keyentry(&db)?;
2187 assert_eq!(entries, entries_new);
2188 Ok(())
2189 }
2190
2191 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07002192 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08002193 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
2194 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07002195 }
2196
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002197 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07002198
Max Bires8e93d2b2021-01-14 13:17:59 -08002199 db.create_key_entry(Domain::APP, 100, &KEYSTORE_UUID)?;
2200 db.create_key_entry(Domain::SELINUX, 101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07002201
2202 let entries = get_keyentry(&db)?;
2203 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08002204 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
2205 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07002206
2207 // Test that we must pass in a valid Domain.
2208 check_result_is_error_containing_string(
Max Bires8e93d2b2021-01-14 13:17:59 -08002209 db.create_key_entry(Domain::GRANT, 102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002210 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07002211 );
2212 check_result_is_error_containing_string(
Max Bires8e93d2b2021-01-14 13:17:59 -08002213 db.create_key_entry(Domain::BLOB, 103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002214 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07002215 );
2216 check_result_is_error_containing_string(
Max Bires8e93d2b2021-01-14 13:17:59 -08002217 db.create_key_entry(Domain::KEY_ID, 104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002218 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07002219 );
2220
2221 Ok(())
2222 }
2223
Joel Galenson33c04ad2020-08-03 11:04:38 -07002224 #[test]
2225 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08002226 fn extractor(
2227 ke: &KeyEntryRow,
2228 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
2229 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07002230 }
2231
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002232 let mut db = new_test_db()?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002233 db.create_key_entry(Domain::APP, 42, &KEYSTORE_UUID)?;
2234 db.create_key_entry(Domain::APP, 42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002235 let entries = get_keyentry(&db)?;
2236 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08002237 assert_eq!(
2238 extractor(&entries[0]),
2239 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
2240 );
2241 assert_eq!(
2242 extractor(&entries[1]),
2243 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
2244 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07002245
2246 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002247 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002248 let entries = get_keyentry(&db)?;
2249 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08002250 assert_eq!(
2251 extractor(&entries[0]),
2252 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
2253 );
2254 assert_eq!(
2255 extractor(&entries[1]),
2256 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
2257 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07002258
2259 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002260 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002261 let entries = get_keyentry(&db)?;
2262 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08002263 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
2264 assert_eq!(
2265 extractor(&entries[1]),
2266 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
2267 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07002268
2269 // Test that we must pass in a valid Domain.
2270 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002271 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002272 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002273 );
2274 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002275 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002276 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002277 );
2278 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002279 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002280 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002281 );
2282
2283 // Test that we correctly handle setting an alias for something that does not exist.
2284 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002285 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07002286 "Expected to update a single entry but instead updated 0",
2287 );
2288 // Test that we correctly abort the transaction in this case.
2289 let entries = get_keyentry(&db)?;
2290 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08002291 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
2292 assert_eq!(
2293 extractor(&entries[1]),
2294 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
2295 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07002296
2297 Ok(())
2298 }
2299
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002300 #[test]
2301 fn test_grant_ungrant() -> Result<()> {
2302 const CALLER_UID: u32 = 15;
2303 const GRANTEE_UID: u32 = 12;
2304 const SELINUX_NAMESPACE: i64 = 7;
2305
2306 let mut db = new_test_db()?;
2307 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08002308 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
2309 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
2310 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002311 )?;
2312 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002313 domain: super::Domain::APP,
2314 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002315 alias: Some("key".to_string()),
2316 blob: None,
2317 };
2318 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
2319 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
2320
2321 // Reset totally predictable random number generator in case we
2322 // are not the first test running on this thread.
2323 reset_random();
2324 let next_random = 0i64;
2325
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002326 let app_granted_key = db
2327 .grant(app_key.clone(), CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002328 assert_eq!(*a, PVEC1);
2329 assert_eq!(
2330 *k,
2331 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002332 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002333 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002334 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002335 alias: Some("key".to_string()),
2336 blob: None,
2337 }
2338 );
2339 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002340 })
2341 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002342
2343 assert_eq!(
2344 app_granted_key,
2345 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002346 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002347 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002348 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002349 alias: None,
2350 blob: None,
2351 }
2352 );
2353
2354 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002355 domain: super::Domain::SELINUX,
2356 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002357 alias: Some("yek".to_string()),
2358 blob: None,
2359 };
2360
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002361 let selinux_granted_key = db
2362 .grant(selinux_key.clone(), CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002363 assert_eq!(*a, PVEC1);
2364 assert_eq!(
2365 *k,
2366 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002367 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002368 // namespace must be the supplied SELinux
2369 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002370 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002371 alias: Some("yek".to_string()),
2372 blob: None,
2373 }
2374 );
2375 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002376 })
2377 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002378
2379 assert_eq!(
2380 selinux_granted_key,
2381 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002382 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002383 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002384 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002385 alias: None,
2386 blob: None,
2387 }
2388 );
2389
2390 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002391 let selinux_granted_key = db
2392 .grant(selinux_key.clone(), CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002393 assert_eq!(*a, PVEC2);
2394 assert_eq!(
2395 *k,
2396 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002397 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002398 // namespace must be the supplied SELinux
2399 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002400 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002401 alias: Some("yek".to_string()),
2402 blob: None,
2403 }
2404 );
2405 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002406 })
2407 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002408
2409 assert_eq!(
2410 selinux_granted_key,
2411 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002412 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002413 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002414 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002415 alias: None,
2416 blob: None,
2417 }
2418 );
2419
2420 {
2421 // Limiting scope of stmt, because it borrows db.
2422 let mut stmt = db
2423 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002424 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07002425 let mut rows =
2426 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
2427 Ok((
2428 row.get(0)?,
2429 row.get(1)?,
2430 row.get(2)?,
2431 KeyPermSet::from(row.get::<_, i32>(3)?),
2432 ))
2433 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002434
2435 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07002436 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002437 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07002438 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002439 assert!(rows.next().is_none());
2440 }
2441
2442 debug_dump_keyentry_table(&mut db)?;
2443 println!("app_key {:?}", app_key);
2444 println!("selinux_key {:?}", selinux_key);
2445
2446 db.ungrant(app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
2447 db.ungrant(selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
2448
2449 Ok(())
2450 }
2451
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002452 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002453 static TEST_CERT_BLOB: &[u8] = b"my test cert";
2454 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
2455
2456 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08002457 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002458 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002459 let mut db = new_test_db()?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002460 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB))?;
2461 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB))?;
2462 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002463 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002464
2465 let mut stmt = db.conn.prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002466 "SELECT subcomponent_type, keyentryid, blob FROM persistent.blobentry
2467 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002468 )?;
2469 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002470 .query_map::<(SubComponentType, i64, Vec<u8>), _, _>(NO_PARAMS, |row| {
2471 Ok((row.get(0)?, row.get(1)?, row.get(2)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002472 })?;
2473 let r = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002474 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002475 let r = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002476 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002477 let r = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002478 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002479
2480 Ok(())
2481 }
2482
2483 static TEST_ALIAS: &str = "my super duper key";
2484
2485 #[test]
2486 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
2487 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08002488 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08002489 .context("test_insert_and_load_full_keyentry_domain_app")?
2490 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002491 let (_key_guard, key_entry) = db
2492 .load_key_entry(
2493 KeyDescriptor {
2494 domain: Domain::APP,
2495 nspace: 0,
2496 alias: Some(TEST_ALIAS.to_string()),
2497 blob: None,
2498 },
2499 KeyType::Client,
2500 KeyEntryLoadBits::BOTH,
2501 1,
2502 |_k, _av| Ok(()),
2503 )
2504 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08002505 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002506
2507 db.unbind_key(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002508 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002509 domain: Domain::APP,
2510 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002511 alias: Some(TEST_ALIAS.to_string()),
2512 blob: None,
2513 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002514 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002515 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002516 |_, _| Ok(()),
2517 )
2518 .unwrap();
2519
2520 assert_eq!(
2521 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
2522 db.load_key_entry(
2523 KeyDescriptor {
2524 domain: Domain::APP,
2525 nspace: 0,
2526 alias: Some(TEST_ALIAS.to_string()),
2527 blob: None,
2528 },
2529 KeyType::Client,
2530 KeyEntryLoadBits::NONE,
2531 1,
2532 |_k, _av| Ok(()),
2533 )
2534 .unwrap_err()
2535 .root_cause()
2536 .downcast_ref::<KsError>()
2537 );
2538
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002539 Ok(())
2540 }
2541
2542 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08002543 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
2544 let mut db = new_test_db()?;
2545
2546 db.store_new_certificate(
2547 KeyDescriptor {
2548 domain: Domain::APP,
2549 nspace: 1,
2550 alias: Some(TEST_ALIAS.to_string()),
2551 blob: None,
2552 },
2553 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08002554 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002555 )
2556 .expect("Trying to insert cert.");
2557
2558 let (_key_guard, mut key_entry) = db
2559 .load_key_entry(
2560 KeyDescriptor {
2561 domain: Domain::APP,
2562 nspace: 1,
2563 alias: Some(TEST_ALIAS.to_string()),
2564 blob: None,
2565 },
2566 KeyType::Client,
2567 KeyEntryLoadBits::PUBLIC,
2568 1,
2569 |_k, _av| Ok(()),
2570 )
2571 .expect("Trying to read certificate entry.");
2572
2573 assert!(key_entry.pure_cert());
2574 assert!(key_entry.cert().is_none());
2575 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
2576
2577 db.unbind_key(
2578 KeyDescriptor {
2579 domain: Domain::APP,
2580 nspace: 1,
2581 alias: Some(TEST_ALIAS.to_string()),
2582 blob: None,
2583 },
2584 KeyType::Client,
2585 1,
2586 |_, _| Ok(()),
2587 )
2588 .unwrap();
2589
2590 assert_eq!(
2591 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
2592 db.load_key_entry(
2593 KeyDescriptor {
2594 domain: Domain::APP,
2595 nspace: 1,
2596 alias: Some(TEST_ALIAS.to_string()),
2597 blob: None,
2598 },
2599 KeyType::Client,
2600 KeyEntryLoadBits::NONE,
2601 1,
2602 |_k, _av| Ok(()),
2603 )
2604 .unwrap_err()
2605 .root_cause()
2606 .downcast_ref::<KsError>()
2607 );
2608
2609 Ok(())
2610 }
2611
2612 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002613 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
2614 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08002615 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08002616 .context("test_insert_and_load_full_keyentry_domain_selinux")?
2617 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002618 let (_key_guard, key_entry) = db
2619 .load_key_entry(
2620 KeyDescriptor {
2621 domain: Domain::SELINUX,
2622 nspace: 1,
2623 alias: Some(TEST_ALIAS.to_string()),
2624 blob: None,
2625 },
2626 KeyType::Client,
2627 KeyEntryLoadBits::BOTH,
2628 1,
2629 |_k, _av| Ok(()),
2630 )
2631 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08002632 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002633
2634 db.unbind_key(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002635 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002636 domain: Domain::SELINUX,
2637 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002638 alias: Some(TEST_ALIAS.to_string()),
2639 blob: None,
2640 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002641 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002642 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002643 |_, _| Ok(()),
2644 )
2645 .unwrap();
2646
2647 assert_eq!(
2648 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
2649 db.load_key_entry(
2650 KeyDescriptor {
2651 domain: Domain::SELINUX,
2652 nspace: 1,
2653 alias: Some(TEST_ALIAS.to_string()),
2654 blob: None,
2655 },
2656 KeyType::Client,
2657 KeyEntryLoadBits::NONE,
2658 1,
2659 |_k, _av| Ok(()),
2660 )
2661 .unwrap_err()
2662 .root_cause()
2663 .downcast_ref::<KsError>()
2664 );
2665
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002666 Ok(())
2667 }
2668
2669 #[test]
2670 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
2671 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08002672 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08002673 .context("test_insert_and_load_full_keyentry_domain_key_id")?
2674 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002675 let (_, key_entry) = db
2676 .load_key_entry(
2677 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
2678 KeyType::Client,
2679 KeyEntryLoadBits::BOTH,
2680 1,
2681 |_k, _av| Ok(()),
2682 )
2683 .unwrap();
2684
Qi Wub9433b52020-12-01 14:52:46 +08002685 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002686
2687 db.unbind_key(
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002688 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002689 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002690 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002691 |_, _| Ok(()),
2692 )
2693 .unwrap();
2694
2695 assert_eq!(
2696 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
2697 db.load_key_entry(
2698 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
2699 KeyType::Client,
2700 KeyEntryLoadBits::NONE,
2701 1,
2702 |_k, _av| Ok(()),
2703 )
2704 .unwrap_err()
2705 .root_cause()
2706 .downcast_ref::<KsError>()
2707 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002708
2709 Ok(())
2710 }
2711
2712 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08002713 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
2714 let mut db = new_test_db()?;
2715 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
2716 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
2717 .0;
2718 // Update the usage count of the limited use key.
2719 db.check_and_update_key_usage_count(key_id)?;
2720
2721 let (_key_guard, key_entry) = db.load_key_entry(
2722 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
2723 KeyType::Client,
2724 KeyEntryLoadBits::BOTH,
2725 1,
2726 |_k, _av| Ok(()),
2727 )?;
2728
2729 // The usage count is decremented now.
2730 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
2731
2732 Ok(())
2733 }
2734
2735 #[test]
2736 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
2737 let mut db = new_test_db()?;
2738 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
2739 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
2740 .0;
2741 // Update the usage count of the limited use key.
2742 db.check_and_update_key_usage_count(key_id).expect(concat!(
2743 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
2744 "This should succeed."
2745 ));
2746
2747 // Try to update the exhausted limited use key.
2748 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
2749 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
2750 "This should fail."
2751 ));
2752 assert_eq!(
2753 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
2754 e.root_cause().downcast_ref::<KsError>().unwrap()
2755 );
2756
2757 Ok(())
2758 }
2759
2760 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002761 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
2762 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08002763 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08002764 .context("test_insert_and_load_full_keyentry_from_grant")?
2765 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002766
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002767 let granted_key = db
2768 .grant(
2769 KeyDescriptor {
2770 domain: Domain::APP,
2771 nspace: 0,
2772 alias: Some(TEST_ALIAS.to_string()),
2773 blob: None,
2774 },
2775 1,
2776 2,
2777 key_perm_set![KeyPerm::use_()],
2778 |_k, _av| Ok(()),
2779 )
2780 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002781
2782 debug_dump_grant_table(&mut db)?;
2783
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002784 let (_key_guard, key_entry) = db
2785 .load_key_entry(
2786 granted_key.clone(),
2787 KeyType::Client,
2788 KeyEntryLoadBits::BOTH,
2789 2,
2790 |k, av| {
2791 assert_eq!(Domain::GRANT, k.domain);
2792 assert!(av.unwrap().includes(KeyPerm::use_()));
2793 Ok(())
2794 },
2795 )
2796 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002797
Qi Wub9433b52020-12-01 14:52:46 +08002798 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002799
2800 db.unbind_key(granted_key.clone(), KeyType::Client, 2, |_, _| Ok(())).unwrap();
2801
2802 assert_eq!(
2803 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
2804 db.load_key_entry(
2805 granted_key,
2806 KeyType::Client,
2807 KeyEntryLoadBits::NONE,
2808 2,
2809 |_k, _av| Ok(()),
2810 )
2811 .unwrap_err()
2812 .root_cause()
2813 .downcast_ref::<KsError>()
2814 );
2815
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002816 Ok(())
2817 }
2818
Janis Danisevskis45760022021-01-19 16:34:10 -08002819 // This test attempts to load a key by key id while the caller is not the owner
2820 // but a grant exists for the given key and the caller.
2821 #[test]
2822 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
2823 let mut db = new_test_db()?;
2824 const OWNER_UID: u32 = 1u32;
2825 const GRANTEE_UID: u32 = 2u32;
2826 const SOMEONE_ELSE_UID: u32 = 3u32;
2827 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
2828 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
2829 .0;
2830
2831 db.grant(
2832 KeyDescriptor {
2833 domain: Domain::APP,
2834 nspace: 0,
2835 alias: Some(TEST_ALIAS.to_string()),
2836 blob: None,
2837 },
2838 OWNER_UID,
2839 GRANTEE_UID,
2840 key_perm_set![KeyPerm::use_()],
2841 |_k, _av| Ok(()),
2842 )
2843 .unwrap();
2844
2845 debug_dump_grant_table(&mut db)?;
2846
2847 let id_descriptor =
2848 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
2849
2850 let (_, key_entry) = db
2851 .load_key_entry(
2852 id_descriptor.clone(),
2853 KeyType::Client,
2854 KeyEntryLoadBits::BOTH,
2855 GRANTEE_UID,
2856 |k, av| {
2857 assert_eq!(Domain::APP, k.domain);
2858 assert_eq!(OWNER_UID as i64, k.nspace);
2859 assert!(av.unwrap().includes(KeyPerm::use_()));
2860 Ok(())
2861 },
2862 )
2863 .unwrap();
2864
2865 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
2866
2867 let (_, key_entry) = db
2868 .load_key_entry(
2869 id_descriptor.clone(),
2870 KeyType::Client,
2871 KeyEntryLoadBits::BOTH,
2872 SOMEONE_ELSE_UID,
2873 |k, av| {
2874 assert_eq!(Domain::APP, k.domain);
2875 assert_eq!(OWNER_UID as i64, k.nspace);
2876 assert!(av.is_none());
2877 Ok(())
2878 },
2879 )
2880 .unwrap();
2881
2882 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
2883
2884 db.unbind_key(id_descriptor.clone(), KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
2885
2886 assert_eq!(
2887 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
2888 db.load_key_entry(
2889 id_descriptor,
2890 KeyType::Client,
2891 KeyEntryLoadBits::NONE,
2892 GRANTEE_UID,
2893 |_k, _av| Ok(()),
2894 )
2895 .unwrap_err()
2896 .root_cause()
2897 .downcast_ref::<KsError>()
2898 );
2899
2900 Ok(())
2901 }
2902
Janis Danisevskisaec14592020-11-12 09:41:49 -08002903 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
2904
Janis Danisevskisaec14592020-11-12 09:41:49 -08002905 #[test]
2906 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
2907 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002908 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
2909 let temp_dir_clone = temp_dir.clone();
2910 let mut db = KeystoreDB::new(temp_dir.path())?;
Qi Wub9433b52020-12-01 14:52:46 +08002911 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08002912 .context("test_insert_and_load_full_keyentry_domain_app")?
2913 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002914 let (_key_guard, key_entry) = db
2915 .load_key_entry(
2916 KeyDescriptor {
2917 domain: Domain::APP,
2918 nspace: 0,
2919 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
2920 blob: None,
2921 },
2922 KeyType::Client,
2923 KeyEntryLoadBits::BOTH,
2924 33,
2925 |_k, _av| Ok(()),
2926 )
2927 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08002928 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08002929 let state = Arc::new(AtomicU8::new(1));
2930 let state2 = state.clone();
2931
2932 // Spawning a second thread that attempts to acquire the key id lock
2933 // for the same key as the primary thread. The primary thread then
2934 // waits, thereby forcing the secondary thread into the second stage
2935 // of acquiring the lock (see KEY ID LOCK 2/2 above).
2936 // The test succeeds if the secondary thread observes the transition
2937 // of `state` from 1 to 2, despite having a whole second to overtake
2938 // the primary thread.
2939 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002940 let temp_dir = temp_dir_clone;
2941 let mut db = KeystoreDB::new(temp_dir.path()).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08002942 assert!(db
2943 .load_key_entry(
2944 KeyDescriptor {
2945 domain: Domain::APP,
2946 nspace: 0,
2947 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
2948 blob: None,
2949 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002950 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002951 KeyEntryLoadBits::BOTH,
2952 33,
2953 |_k, _av| Ok(()),
2954 )
2955 .is_ok());
2956 // We should only see a 2 here because we can only return
2957 // from load_key_entry when the `_key_guard` expires,
2958 // which happens at the end of the scope.
2959 assert_eq!(2, state2.load(Ordering::Relaxed));
2960 });
2961
2962 thread::sleep(std::time::Duration::from_millis(1000));
2963
2964 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
2965
2966 // Return the handle from this scope so we can join with the
2967 // secondary thread after the key id lock has expired.
2968 handle
2969 // This is where the `_key_guard` goes out of scope,
2970 // which is the reason for concurrent load_key_entry on the same key
2971 // to unblock.
2972 };
2973 // Join with the secondary thread and unwrap, to propagate failing asserts to the
2974 // main test thread. We will not see failing asserts in secondary threads otherwise.
2975 handle.join().unwrap();
2976 Ok(())
2977 }
2978
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002979 #[test]
2980 fn list() -> Result<()> {
2981 let temp_dir = TempDir::new("list_test")?;
2982 let mut db = KeystoreDB::new(temp_dir.path())?;
2983 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
2984 (Domain::APP, 1, "test1"),
2985 (Domain::APP, 1, "test2"),
2986 (Domain::APP, 1, "test3"),
2987 (Domain::APP, 1, "test4"),
2988 (Domain::APP, 1, "test5"),
2989 (Domain::APP, 1, "test6"),
2990 (Domain::APP, 1, "test7"),
2991 (Domain::APP, 2, "test1"),
2992 (Domain::APP, 2, "test2"),
2993 (Domain::APP, 2, "test3"),
2994 (Domain::APP, 2, "test4"),
2995 (Domain::APP, 2, "test5"),
2996 (Domain::APP, 2, "test6"),
2997 (Domain::APP, 2, "test8"),
2998 (Domain::SELINUX, 100, "test1"),
2999 (Domain::SELINUX, 100, "test2"),
3000 (Domain::SELINUX, 100, "test3"),
3001 (Domain::SELINUX, 100, "test4"),
3002 (Domain::SELINUX, 100, "test5"),
3003 (Domain::SELINUX, 100, "test6"),
3004 (Domain::SELINUX, 100, "test9"),
3005 ];
3006
3007 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
3008 .iter()
3009 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08003010 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
3011 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003012 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
3013 });
3014 (entry.id(), *ns)
3015 })
3016 .collect();
3017
3018 for (domain, namespace) in
3019 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
3020 {
3021 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
3022 .iter()
3023 .filter_map(|(domain, ns, alias)| match ns {
3024 ns if *ns == *namespace => Some(KeyDescriptor {
3025 domain: *domain,
3026 nspace: *ns,
3027 alias: Some(alias.to_string()),
3028 blob: None,
3029 }),
3030 _ => None,
3031 })
3032 .collect();
3033 list_o_descriptors.sort();
3034 let mut list_result = db.list(*domain, *namespace)?;
3035 list_result.sort();
3036 assert_eq!(list_o_descriptors, list_result);
3037
3038 let mut list_o_ids: Vec<i64> = list_o_descriptors
3039 .into_iter()
3040 .map(|d| {
3041 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003042 .load_key_entry(
3043 d,
3044 KeyType::Client,
3045 KeyEntryLoadBits::NONE,
3046 *namespace as u32,
3047 |_, _| Ok(()),
3048 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003049 .unwrap();
3050 entry.id()
3051 })
3052 .collect();
3053 list_o_ids.sort_unstable();
3054 let mut loaded_entries: Vec<i64> = list_o_keys
3055 .iter()
3056 .filter_map(|(id, ns)| match ns {
3057 ns if *ns == *namespace => Some(*id),
3058 _ => None,
3059 })
3060 .collect();
3061 loaded_entries.sort_unstable();
3062 assert_eq!(list_o_ids, loaded_entries);
3063 }
3064 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
3065
3066 Ok(())
3067 }
3068
Joel Galenson0891bc12020-07-20 10:37:03 -07003069 // Helpers
3070
3071 // Checks that the given result is an error containing the given string.
3072 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
3073 let error_str = format!(
3074 "{:#?}",
3075 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
3076 );
3077 assert!(
3078 error_str.contains(target),
3079 "The string \"{}\" should contain \"{}\"",
3080 error_str,
3081 target
3082 );
3083 }
3084
Joel Galenson2aab4432020-07-22 15:27:57 -07003085 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07003086 #[allow(dead_code)]
3087 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003088 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003089 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003090 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07003091 namespace: Option<i64>,
3092 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003093 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08003094 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07003095 }
3096
3097 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
3098 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003099 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07003100 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07003101 Ok(KeyEntryRow {
3102 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003103 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003104 domain: match row.get(2)? {
3105 Some(i) => Some(Domain(i)),
3106 None => None,
3107 },
Joel Galenson0891bc12020-07-20 10:37:03 -07003108 namespace: row.get(3)?,
3109 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003110 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08003111 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07003112 })
3113 })?
3114 .map(|r| r.context("Could not read keyentry row."))
3115 .collect::<Result<Vec<_>>>()
3116 }
3117
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003118 // Note: The parameters and SecurityLevel associations are nonsensical. This
3119 // collection is only used to check if the parameters are preserved as expected by the
3120 // database.
Qi Wub9433b52020-12-01 14:52:46 +08003121 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
3122 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003123 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
3124 KeyParameter::new(
3125 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
3126 SecurityLevel::TRUSTED_ENVIRONMENT,
3127 ),
3128 KeyParameter::new(
3129 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
3130 SecurityLevel::TRUSTED_ENVIRONMENT,
3131 ),
3132 KeyParameter::new(
3133 KeyParameterValue::Algorithm(Algorithm::RSA),
3134 SecurityLevel::TRUSTED_ENVIRONMENT,
3135 ),
3136 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
3137 KeyParameter::new(
3138 KeyParameterValue::BlockMode(BlockMode::ECB),
3139 SecurityLevel::TRUSTED_ENVIRONMENT,
3140 ),
3141 KeyParameter::new(
3142 KeyParameterValue::BlockMode(BlockMode::GCM),
3143 SecurityLevel::TRUSTED_ENVIRONMENT,
3144 ),
3145 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
3146 KeyParameter::new(
3147 KeyParameterValue::Digest(Digest::MD5),
3148 SecurityLevel::TRUSTED_ENVIRONMENT,
3149 ),
3150 KeyParameter::new(
3151 KeyParameterValue::Digest(Digest::SHA_2_224),
3152 SecurityLevel::TRUSTED_ENVIRONMENT,
3153 ),
3154 KeyParameter::new(
3155 KeyParameterValue::Digest(Digest::SHA_2_256),
3156 SecurityLevel::STRONGBOX,
3157 ),
3158 KeyParameter::new(
3159 KeyParameterValue::PaddingMode(PaddingMode::NONE),
3160 SecurityLevel::TRUSTED_ENVIRONMENT,
3161 ),
3162 KeyParameter::new(
3163 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
3164 SecurityLevel::TRUSTED_ENVIRONMENT,
3165 ),
3166 KeyParameter::new(
3167 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
3168 SecurityLevel::STRONGBOX,
3169 ),
3170 KeyParameter::new(
3171 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
3172 SecurityLevel::TRUSTED_ENVIRONMENT,
3173 ),
3174 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
3175 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
3176 KeyParameter::new(
3177 KeyParameterValue::EcCurve(EcCurve::P_224),
3178 SecurityLevel::TRUSTED_ENVIRONMENT,
3179 ),
3180 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
3181 KeyParameter::new(
3182 KeyParameterValue::EcCurve(EcCurve::P_384),
3183 SecurityLevel::TRUSTED_ENVIRONMENT,
3184 ),
3185 KeyParameter::new(
3186 KeyParameterValue::EcCurve(EcCurve::P_521),
3187 SecurityLevel::TRUSTED_ENVIRONMENT,
3188 ),
3189 KeyParameter::new(
3190 KeyParameterValue::RSAPublicExponent(3),
3191 SecurityLevel::TRUSTED_ENVIRONMENT,
3192 ),
3193 KeyParameter::new(
3194 KeyParameterValue::IncludeUniqueID,
3195 SecurityLevel::TRUSTED_ENVIRONMENT,
3196 ),
3197 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
3198 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
3199 KeyParameter::new(
3200 KeyParameterValue::ActiveDateTime(1234567890),
3201 SecurityLevel::STRONGBOX,
3202 ),
3203 KeyParameter::new(
3204 KeyParameterValue::OriginationExpireDateTime(1234567890),
3205 SecurityLevel::TRUSTED_ENVIRONMENT,
3206 ),
3207 KeyParameter::new(
3208 KeyParameterValue::UsageExpireDateTime(1234567890),
3209 SecurityLevel::TRUSTED_ENVIRONMENT,
3210 ),
3211 KeyParameter::new(
3212 KeyParameterValue::MinSecondsBetweenOps(1234567890),
3213 SecurityLevel::TRUSTED_ENVIRONMENT,
3214 ),
3215 KeyParameter::new(
3216 KeyParameterValue::MaxUsesPerBoot(1234567890),
3217 SecurityLevel::TRUSTED_ENVIRONMENT,
3218 ),
3219 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
3220 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
3221 KeyParameter::new(
3222 KeyParameterValue::NoAuthRequired,
3223 SecurityLevel::TRUSTED_ENVIRONMENT,
3224 ),
3225 KeyParameter::new(
3226 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
3227 SecurityLevel::TRUSTED_ENVIRONMENT,
3228 ),
3229 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
3230 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
3231 KeyParameter::new(
3232 KeyParameterValue::TrustedUserPresenceRequired,
3233 SecurityLevel::TRUSTED_ENVIRONMENT,
3234 ),
3235 KeyParameter::new(
3236 KeyParameterValue::TrustedConfirmationRequired,
3237 SecurityLevel::TRUSTED_ENVIRONMENT,
3238 ),
3239 KeyParameter::new(
3240 KeyParameterValue::UnlockedDeviceRequired,
3241 SecurityLevel::TRUSTED_ENVIRONMENT,
3242 ),
3243 KeyParameter::new(
3244 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
3245 SecurityLevel::SOFTWARE,
3246 ),
3247 KeyParameter::new(
3248 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
3249 SecurityLevel::SOFTWARE,
3250 ),
3251 KeyParameter::new(
3252 KeyParameterValue::CreationDateTime(12345677890),
3253 SecurityLevel::SOFTWARE,
3254 ),
3255 KeyParameter::new(
3256 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
3257 SecurityLevel::TRUSTED_ENVIRONMENT,
3258 ),
3259 KeyParameter::new(
3260 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
3261 SecurityLevel::TRUSTED_ENVIRONMENT,
3262 ),
3263 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
3264 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
3265 KeyParameter::new(
3266 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
3267 SecurityLevel::SOFTWARE,
3268 ),
3269 KeyParameter::new(
3270 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
3271 SecurityLevel::TRUSTED_ENVIRONMENT,
3272 ),
3273 KeyParameter::new(
3274 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
3275 SecurityLevel::TRUSTED_ENVIRONMENT,
3276 ),
3277 KeyParameter::new(
3278 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
3279 SecurityLevel::TRUSTED_ENVIRONMENT,
3280 ),
3281 KeyParameter::new(
3282 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
3283 SecurityLevel::TRUSTED_ENVIRONMENT,
3284 ),
3285 KeyParameter::new(
3286 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
3287 SecurityLevel::TRUSTED_ENVIRONMENT,
3288 ),
3289 KeyParameter::new(
3290 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
3291 SecurityLevel::TRUSTED_ENVIRONMENT,
3292 ),
3293 KeyParameter::new(
3294 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
3295 SecurityLevel::TRUSTED_ENVIRONMENT,
3296 ),
3297 KeyParameter::new(
3298 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
3299 SecurityLevel::TRUSTED_ENVIRONMENT,
3300 ),
3301 KeyParameter::new(
3302 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
3303 SecurityLevel::TRUSTED_ENVIRONMENT,
3304 ),
3305 KeyParameter::new(
3306 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
3307 SecurityLevel::TRUSTED_ENVIRONMENT,
3308 ),
3309 KeyParameter::new(
3310 KeyParameterValue::VendorPatchLevel(3),
3311 SecurityLevel::TRUSTED_ENVIRONMENT,
3312 ),
3313 KeyParameter::new(
3314 KeyParameterValue::BootPatchLevel(4),
3315 SecurityLevel::TRUSTED_ENVIRONMENT,
3316 ),
3317 KeyParameter::new(
3318 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
3319 SecurityLevel::TRUSTED_ENVIRONMENT,
3320 ),
3321 KeyParameter::new(
3322 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
3323 SecurityLevel::TRUSTED_ENVIRONMENT,
3324 ),
3325 KeyParameter::new(
3326 KeyParameterValue::MacLength(256),
3327 SecurityLevel::TRUSTED_ENVIRONMENT,
3328 ),
3329 KeyParameter::new(
3330 KeyParameterValue::ResetSinceIdRotation,
3331 SecurityLevel::TRUSTED_ENVIRONMENT,
3332 ),
3333 KeyParameter::new(
3334 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
3335 SecurityLevel::TRUSTED_ENVIRONMENT,
3336 ),
Qi Wub9433b52020-12-01 14:52:46 +08003337 ];
3338 if let Some(value) = max_usage_count {
3339 params.push(KeyParameter::new(
3340 KeyParameterValue::UsageCountLimit(value),
3341 SecurityLevel::SOFTWARE,
3342 ));
3343 }
3344 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003345 }
3346
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003347 fn make_test_key_entry(
3348 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003349 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003350 namespace: i64,
3351 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08003352 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08003353 ) -> Result<KeyIdGuard> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003354 let key_id = db.create_key_entry(domain, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08003355 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB))?;
3356 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB))?;
3357 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB))?;
Qi Wub9433b52020-12-01 14:52:46 +08003358
3359 let params = make_test_params(max_usage_count);
3360 db.insert_keyparameter(&key_id, &params)?;
3361
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003362 let mut metadata = KeyMetaData::new();
3363 metadata.add(KeyMetaEntry::EncryptedBy(EncryptedBy::Password));
3364 metadata.add(KeyMetaEntry::Salt(vec![1, 2, 3]));
3365 metadata.add(KeyMetaEntry::Iv(vec![2, 3, 1]));
3366 metadata.add(KeyMetaEntry::AeadTag(vec![3, 1, 2]));
3367 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003368 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003369 Ok(key_id)
3370 }
3371
Qi Wub9433b52020-12-01 14:52:46 +08003372 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
3373 let params = make_test_params(max_usage_count);
3374
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003375 let mut metadata = KeyMetaData::new();
3376 metadata.add(KeyMetaEntry::EncryptedBy(EncryptedBy::Password));
3377 metadata.add(KeyMetaEntry::Salt(vec![1, 2, 3]));
3378 metadata.add(KeyMetaEntry::Iv(vec![2, 3, 1]));
3379 metadata.add(KeyMetaEntry::AeadTag(vec![3, 1, 2]));
3380
3381 KeyEntry {
3382 id: key_id,
3383 km_blob: Some(TEST_KEY_BLOB.to_vec()),
3384 cert: Some(TEST_CERT_BLOB.to_vec()),
3385 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08003386 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08003387 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003388 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003389 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003390 }
3391 }
3392
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003393 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003394 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08003395 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003396 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08003397 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003398 NO_PARAMS,
3399 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08003400 Ok((
3401 row.get(0)?,
3402 row.get(1)?,
3403 row.get(2)?,
3404 row.get(3)?,
3405 row.get(4)?,
3406 row.get(5)?,
3407 row.get(6)?,
3408 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003409 },
3410 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003411
3412 println!("Key entry table rows:");
3413 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08003414 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003415 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08003416 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
3417 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003418 );
3419 }
3420 Ok(())
3421 }
3422
3423 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003424 let mut stmt = db
3425 .conn
3426 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003427 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
3428 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
3429 })?;
3430
3431 println!("Grant table rows:");
3432 for r in rows {
3433 let (id, gt, ki, av) = r.unwrap();
3434 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
3435 }
3436 Ok(())
3437 }
3438
Joel Galenson0891bc12020-07-20 10:37:03 -07003439 // Use a custom random number generator that repeats each number once.
3440 // This allows us to test repeated elements.
3441
3442 thread_local! {
3443 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
3444 }
3445
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003446 fn reset_random() {
3447 RANDOM_COUNTER.with(|counter| {
3448 *counter.borrow_mut() = 0;
3449 })
3450 }
3451
Joel Galenson0891bc12020-07-20 10:37:03 -07003452 pub fn random() -> i64 {
3453 RANDOM_COUNTER.with(|counter| {
3454 let result = *counter.borrow() / 2;
3455 *counter.borrow_mut() += 1;
3456 result
3457 })
3458 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003459
3460 #[test]
3461 fn test_last_off_body() -> Result<()> {
3462 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003463 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003464 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
3465 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
3466 tx.commit()?;
3467 let one_second = Duration::from_secs(1);
3468 thread::sleep(one_second);
3469 db.update_last_off_body(MonotonicRawTime::now())?;
3470 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
3471 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
3472 tx2.commit()?;
3473 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
3474 Ok(())
3475 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003476}