Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 1 | // 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 15 | //! 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 Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 43 | |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 44 | use crate::db_utils::{self, SqlField}; |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 45 | use crate::error::{Error as KsError, ErrorCode, ResponseCode}; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 46 | use crate::impl_metadata; // This is in db_utils.rs |
Janis Danisevskis | 4522c2b | 2020-11-27 18:04:58 -0800 | [diff] [blame] | 47 | use crate::key_parameter::{KeyParameter, Tag}; |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 48 | use crate::permission::KeyPermSet; |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 49 | use crate::utils::get_current_time_in_seconds; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 50 | use anyhow::{anyhow, Context, Result}; |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 51 | use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError}; |
Janis Danisevskis | 60400fe | 2020-08-26 15:24:42 -0700 | [diff] [blame] | 52 | |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 53 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{ |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 54 | HardwareAuthToken::HardwareAuthToken, |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 55 | HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel, |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 56 | }; |
| 57 | use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{ |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 58 | Timestamp::Timestamp, |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 59 | }; |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 60 | use android_system_keystore2::aidl::android::system::keystore2::{ |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 61 | Domain::Domain, KeyDescriptor::KeyDescriptor, |
Janis Danisevskis | 60400fe | 2020-08-26 15:24:42 -0700 | [diff] [blame] | 62 | }; |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 63 | use lazy_static::lazy_static; |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 64 | use log::error; |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 65 | #[cfg(not(test))] |
| 66 | use rand::prelude::random; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 67 | use rusqlite::{ |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 68 | params, |
| 69 | types::FromSql, |
| 70 | types::FromSqlResult, |
| 71 | types::ToSqlOutput, |
| 72 | types::{FromSqlError, Value, ValueRef}, |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 73 | Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 74 | }; |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 75 | use std::{ |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 76 | collections::{HashMap, HashSet}, |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 77 | path::Path, |
| 78 | sync::{Condvar, Mutex}, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 79 | time::{Duration, SystemTime}, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 80 | }; |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 81 | #[cfg(test)] |
| 82 | use tests::random; |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 83 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 84 | impl_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 | |
| 111 | impl 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)] |
| 158 | pub 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 | |
| 169 | impl 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 | |
| 179 | impl 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 Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 190 | /// 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)] |
| 194 | pub struct Uuid([u8; 16]); |
| 195 | |
| 196 | impl Deref for Uuid { |
| 197 | type Target = [u8; 16]; |
| 198 | |
| 199 | fn deref(&self) -> &Self::Target { |
| 200 | &self.0 |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | impl From<SecurityLevel> for Uuid { |
| 205 | fn from(sec_level: SecurityLevel) -> Self { |
| 206 | Self((sec_level.0 as u128).to_be_bytes()) |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | impl ToSql for Uuid { |
| 211 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 212 | self.0.to_sql() |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | impl 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. |
| 230 | pub 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 234 | /// Indicates how the sensitive part of this key blob is encrypted. |
| 235 | #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)] |
| 236 | pub 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 | |
| 246 | impl 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 | |
| 255 | impl 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)] |
| 267 | pub struct DateTime(i64); |
| 268 | |
| 269 | /// Error type returned when creating DateTime or converting it from and to |
| 270 | /// SystemTime. |
| 271 | #[derive(thiserror::Error, Debug)] |
| 272 | pub 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 | |
| 286 | impl 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 | |
| 309 | impl ToSql for DateTime { |
| 310 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 311 | Ok(ToSqlOutput::Owned(Value::Integer(self.0))) |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | impl FromSql for DateTime { |
| 316 | fn column_result(value: ValueRef) -> FromSqlResult<Self> { |
| 317 | Ok(Self(i64::column_result(value)?)) |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | impl 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 | |
| 351 | impl 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 Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 359 | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] |
| 360 | enum 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 | |
| 371 | impl 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 | |
| 381 | impl 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 392 | /// 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)] |
| 397 | pub struct KeyEntryLoadBits(u32); |
| 398 | |
| 399 | impl 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 Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 420 | lazy_static! { |
| 421 | static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new(); |
| 422 | } |
| 423 | |
| 424 | struct 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)] |
| 433 | pub struct KeyIdGuard(i64); |
| 434 | |
| 435 | impl 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 | |
| 466 | impl KeyIdGuard { |
| 467 | /// Get the numeric key id of the locked key. |
| 468 | pub fn id(&self) -> i64 { |
| 469 | self.0 |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | impl 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 Danisevskis | 7fd5358 | 2020-11-23 13:40:34 -0800 | [diff] [blame] | 477 | drop(locked_keys); |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 478 | KEY_ID_LOCK.cond_var.notify_all(); |
| 479 | } |
| 480 | } |
| 481 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 482 | /// This type represents a certificate and certificate chain entry for a key. |
| 483 | #[derive(Debug)] |
| 484 | pub struct CertificateInfo { |
| 485 | cert: Option<Vec<u8>>, |
| 486 | cert_chain: Option<Vec<u8>>, |
| 487 | } |
| 488 | |
| 489 | impl 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 506 | /// 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 510 | #[derive(Debug, Default, Eq, PartialEq)] |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 511 | pub struct KeyEntry { |
| 512 | id: i64, |
| 513 | km_blob: Option<Vec<u8>>, |
| 514 | cert: Option<Vec<u8>>, |
| 515 | cert_chain: Option<Vec<u8>>, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 516 | km_uuid: Uuid, |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 517 | parameters: Vec<KeyParameter>, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 518 | metadata: KeyMetaData, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 519 | pure_cert: bool, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 520 | } |
| 521 | |
| 522 | impl 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 Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 551 | /// Returns the uuid of the owning KeyMint instance. |
| 552 | pub fn km_uuid(&self) -> &Uuid { |
| 553 | &self.km_uuid |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 554 | } |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 555 | /// 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 563 | /// Exposes the key metadata of this key entry. |
| 564 | pub fn metadata(&self) -> &KeyMetaData { |
| 565 | &self.metadata |
| 566 | } |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 567 | /// 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 572 | } |
| 573 | |
| 574 | /// Indicates the sub component of a key entry for persistent storage. |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 575 | #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 576 | pub struct SubComponentType(u32); |
| 577 | impl SubComponentType { |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 578 | /// Persistent identifier for a key blob. |
| 579 | pub const KEY_BLOB: SubComponentType = Self(0); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 580 | /// 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 | |
| 586 | impl ToSql for SubComponentType { |
| 587 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 588 | self.0.to_sql() |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | impl FromSql for SubComponentType { |
| 593 | fn column_result(value: ValueRef) -> FromSqlResult<Self> { |
| 594 | Ok(Self(u32::column_result(value)?)) |
| 595 | } |
| 596 | } |
| 597 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 598 | /// 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 Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 600 | pub struct KeystoreDB { |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 601 | conn: Connection, |
| 602 | } |
| 603 | |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 604 | /// 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)] |
| 607 | pub struct MonotonicRawTime(i64); |
| 608 | |
| 609 | impl 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 Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 619 | |
| 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 Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 624 | } |
| 625 | |
| 626 | impl ToSql for MonotonicRawTime { |
| 627 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 628 | Ok(ToSqlOutput::Owned(Value::Integer(self.0))) |
| 629 | } |
| 630 | } |
| 631 | |
| 632 | impl FromSql for MonotonicRawTime { |
| 633 | fn column_result(value: ValueRef) -> FromSqlResult<Self> { |
| 634 | Ok(Self(i64::column_result(value)?)) |
| 635 | } |
| 636 | } |
| 637 | |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 638 | /// This struct encapsulates the information to be stored in the database about the auth tokens |
| 639 | /// received by keystore. |
| 640 | pub struct AuthTokenEntry { |
| 641 | auth_token: HardwareAuthToken, |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 642 | time_received: MonotonicRawTime, |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 643 | } |
| 644 | |
| 645 | impl AuthTokenEntry { |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 646 | fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self { |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 647 | AuthTokenEntry { auth_token, time_received } |
| 648 | } |
| 649 | |
| 650 | /// Checks if this auth token satisfies the given authentication information. |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 651 | pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool { |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 652 | user_secure_ids.iter().any(|&sid| { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 653 | (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 Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 655 | }) |
| 656 | } |
| 657 | |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 658 | /// Returns the auth token wrapped by the AuthTokenEntry |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 659 | 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 Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 665 | self.auth_token |
| 666 | } |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 667 | |
| 668 | /// Returns the time that this auth token was received. |
| 669 | pub fn time_received(&self) -> MonotonicRawTime { |
| 670 | self.time_received |
| 671 | } |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 672 | } |
| 673 | |
Janis Danisevskis | b00ebd0 | 2021-02-02 21:52:24 -0800 | [diff] [blame^] | 674 | /// 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. |
| 677 | pub struct PerBootDbKeepAlive(Connection); |
| 678 | |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 679 | impl KeystoreDB { |
Janis Danisevskis | b00ebd0 | 2021-02-02 21:52:24 -0800 | [diff] [blame^] | 680 | 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 692 | /// This will create a new database connection connecting the two |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 693 | /// 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 696 | /// Each thread should open their own connection using `thread_local!`. |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 697 | pub fn new(db_root: &Path) -> Result<Self> { |
Janis Danisevskis | b00ebd0 | 2021-02-02 21:52:24 -0800 | [diff] [blame^] | 698 | // Build the path to the sqlite file. |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 699 | let mut persistent_path = db_root.to_path_buf(); |
| 700 | persistent_path.push("persistent.sqlite"); |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 701 | |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 702 | // 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 Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 705 | |
Janis Danisevskis | b00ebd0 | 2021-02-02 21:52:24 -0800 | [diff] [blame^] | 706 | let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?; |
Janis Danisevskis | aea2734 | 2021-01-29 08:38:11 -0800 | [diff] [blame] | 707 | 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 Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 712 | |
| 713 | Self::init_tables(&conn)?; |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 714 | Ok(Self { conn }) |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 715 | } |
| 716 | |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 717 | fn init_tables(conn: &Connection) -> Result<()> { |
| 718 | conn.execute( |
| 719 | "CREATE TABLE IF NOT EXISTS persistent.keyentry ( |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 720 | id INTEGER UNIQUE, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 721 | key_type INTEGER, |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 722 | domain INTEGER, |
| 723 | namespace INTEGER, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 724 | alias BLOB, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 725 | state INTEGER, |
| 726 | km_uuid BLOB);", |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 727 | NO_PARAMS, |
| 728 | ) |
| 729 | .context("Failed to initialize \"keyentry\" table.")?; |
| 730 | |
| 731 | conn.execute( |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 732 | "CREATE TABLE IF NOT EXISTS persistent.blobentry ( |
| 733 | id INTEGER PRIMARY KEY, |
| 734 | subcomponent_type INTEGER, |
| 735 | keyentryid INTEGER, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 736 | blob BLOB);", |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 737 | NO_PARAMS, |
| 738 | ) |
| 739 | .context("Failed to initialize \"blobentry\" table.")?; |
| 740 | |
| 741 | conn.execute( |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 742 | "CREATE TABLE IF NOT EXISTS persistent.keyparameter ( |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 743 | keyentryid INTEGER, |
| 744 | tag INTEGER, |
| 745 | data ANY, |
| 746 | security_level INTEGER);", |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 747 | NO_PARAMS, |
| 748 | ) |
| 749 | .context("Failed to initialize \"keyparameter\" table.")?; |
| 750 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 751 | conn.execute( |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 752 | "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 Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 761 | "CREATE TABLE IF NOT EXISTS persistent.grant ( |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 762 | 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 Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 770 | //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 Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 801 | Ok(()) |
| 802 | } |
| 803 | |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 804 | 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 Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 816 | /// 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 906 | /// 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 Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 915 | km_uuid: Uuid, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 916 | 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 Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 934 | AND alias = ? |
| 935 | AND state = ?;", |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 936 | ) |
| 937 | .context("In get_or_create_key_with: Failed to select from keyentry table.")?; |
| 938 | let mut rows = stmt |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 939 | .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live]) |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 940 | .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 Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 962 | (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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 973 | ) |
| 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 Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 978 | Self::set_blob_internal(&tx, id, SubComponentType::KEY_BLOB, Some(&blob)) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 979 | .context("In get_of_create_key_with.")?; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 980 | metadata.store_in_db(id, &tx).context("In get_or_create_key_with.")?; |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 981 | ( |
| 982 | id, |
| 983 | KeyEntry { |
| 984 | id, |
| 985 | km_blob: Some(blob), |
| 986 | metadata, |
| 987 | pure_cert: false, |
| 988 | ..Default::default() |
| 989 | }, |
| 990 | ) |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 991 | } |
| 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 Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 997 | /// 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1013 | /// 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 Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1019 | pub fn create_key_entry( |
| 1020 | &mut self, |
| 1021 | domain: Domain, |
| 1022 | namespace: i64, |
| 1023 | km_uuid: &Uuid, |
| 1024 | ) -> Result<KeyIdGuard> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1025 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1026 | Self::create_key_entry_internal(tx, domain, namespace, km_uuid) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1027 | }) |
| 1028 | .context("In create_key_entry.") |
| 1029 | } |
| 1030 | |
| 1031 | fn create_key_entry_internal( |
| 1032 | tx: &Transaction, |
| 1033 | domain: Domain, |
| 1034 | namespace: i64, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1035 | km_uuid: &Uuid, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1036 | ) -> Result<KeyIdGuard> { |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 1037 | match domain { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1038 | Domain::APP | Domain::SELINUX => {} |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 1039 | _ => { |
| 1040 | return Err(KsError::sys()) |
| 1041 | .context(format!("Domain {:?} must be either App or SELinux.", domain)); |
| 1042 | } |
| 1043 | } |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1044 | Ok(KEY_ID_LOCK.get( |
| 1045 | Self::insert_with_retry(|id| { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1046 | tx.execute( |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1047 | "INSERT into persistent.keyentry |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1048 | (id, key_type, domain, namespace, alias, state, km_uuid) |
| 1049 | VALUES(?, ?, ?, ?, NULL, ?, ?);", |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1050 | params![ |
| 1051 | id, |
| 1052 | KeyType::Client, |
| 1053 | domain.0 as u32, |
| 1054 | namespace, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1055 | KeyLifeCycle::Existing, |
| 1056 | km_uuid, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1057 | ], |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1058 | ) |
| 1059 | }) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1060 | .context("In create_key_entry_internal")?, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1061 | )) |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 1062 | } |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1063 | |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1064 | /// Set a new blob and associates it with the given key id. Each blob |
| 1065 | /// has a sub component type. |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1066 | /// 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 Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1068 | /// 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1072 | &mut self, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1073 | key_id: &KeyIdGuard, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1074 | sc_type: SubComponentType, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1075 | blob: Option<&[u8]>, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1076 | ) -> Result<()> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1077 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1078 | Self::set_blob_internal(&tx, key_id.0, sc_type, blob) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1079 | }) |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1080 | .context("In set_blob.") |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1081 | } |
| 1082 | |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1083 | fn set_blob_internal( |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1084 | tx: &Transaction, |
| 1085 | key_id: i64, |
| 1086 | sc_type: SubComponentType, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1087 | blob: Option<&[u8]>, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1088 | ) -> Result<()> { |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1089 | 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1111 | Ok(()) |
| 1112 | } |
| 1113 | |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1114 | /// 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 Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1118 | key_id: &KeyIdGuard, |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1119 | params: impl IntoIterator<Item = &'a KeyParameter>, |
| 1120 | ) -> Result<()> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1121 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 1122 | Self::insert_keyparameter_internal(tx, key_id, params) |
| 1123 | }) |
| 1124 | .context("In insert_keyparameter.") |
| 1125 | } |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1126 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1127 | 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 Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1150 | } |
| 1151 | Ok(()) |
| 1152 | } |
| 1153 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1154 | /// 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 Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1160 | 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1166 | /// 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 Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1169 | /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage |
| 1170 | /// collector. |
| 1171 | fn rebind_alias( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1172 | tx: &Transaction, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1173 | newid: &KeyIdGuard, |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1174 | alias: &str, |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1175 | domain: Domain, |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1176 | namespace: i64, |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1177 | ) -> Result<bool> { |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1178 | match domain { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1179 | Domain::APP | Domain::SELINUX => {} |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1180 | _ => { |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1181 | return Err(KsError::sys()).context(format!( |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1182 | "In rebind_alias: Domain {:?} must be either App or SELinux.", |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1183 | domain |
| 1184 | )); |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1185 | } |
| 1186 | } |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1187 | let updated = tx |
| 1188 | .execute( |
| 1189 | "UPDATE persistent.keyentry |
| 1190 | SET alias = NULL, domain = NULL, namespace = NULL, state = ? |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1191 | WHERE alias = ? AND domain = ? AND namespace = ?;", |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1192 | params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace], |
| 1193 | ) |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1194 | .context("In rebind_alias: Failed to rebind existing entry.")?; |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1195 | let result = tx |
| 1196 | .execute( |
| 1197 | "UPDATE persistent.keyentry |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1198 | 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 Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1206 | KeyLifeCycle::Existing, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1207 | ], |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1208 | ) |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1209 | .context("In rebind_alias: Failed to set alias.")?; |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1210 | if result != 1 { |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1211 | return Err(KsError::sys()).context(format!( |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1212 | "In rebind_alias: Expected to update a single entry but instead updated {}.", |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1213 | result |
| 1214 | )); |
| 1215 | } |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1216 | Ok(updated != 0) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1217 | } |
| 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 Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1222 | /// 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 Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1224 | pub fn store_new_key<'a>( |
| 1225 | &mut self, |
| 1226 | key: KeyDescriptor, |
| 1227 | params: impl IntoIterator<Item = &'a KeyParameter>, |
| 1228 | blob: &[u8], |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1229 | cert_info: &CertificateInfo, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1230 | metadata: &KeyMetaData, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1231 | km_uuid: &Uuid, |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1232 | ) -> Result<(bool, KeyIdGuard)> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1233 | 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 Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1244 | let key_id = Self::create_key_entry_internal(tx, domain, namespace, km_uuid) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1245 | .context("Trying to create new key entry.")?; |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1246 | Self::set_blob_internal(tx, key_id.id(), SubComponentType::KEY_BLOB, Some(blob)) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1247 | .context("Trying to insert the key blob.")?; |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1248 | if let Some(cert) = &cert_info.cert { |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1249 | Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert)) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1250 | .context("Trying to insert the certificate.")?; |
| 1251 | } |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1252 | if let Some(cert_chain) = &cert_info.cert_chain { |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1253 | Self::set_blob_internal( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1254 | tx, |
| 1255 | key_id.id(), |
| 1256 | SubComponentType::CERT_CHAIN, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1257 | Some(&cert_chain), |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1258 | ) |
| 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 Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1263 | metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?; |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1264 | let need_gc = Self::rebind_alias(tx, &key_id, &alias, domain, namespace) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1265 | .context("Trying to rebind alias.")?; |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1266 | Ok((need_gc, key_id)) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1267 | }) |
| 1268 | .context("In store_new_key.") |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1269 | } |
| 1270 | |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1271 | /// 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 Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1274 | pub fn store_new_certificate( |
| 1275 | &mut self, |
| 1276 | key: KeyDescriptor, |
| 1277 | cert: &[u8], |
| 1278 | km_uuid: &Uuid, |
| 1279 | ) -> Result<KeyIdGuard> { |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1280 | 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 Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1292 | let key_id = Self::create_key_entry_internal(tx, domain, namespace, km_uuid) |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1293 | .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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1312 | // Helper function loading the key_id given the key descriptor |
| 1313 | // tuple comprising domain, namespace, and alias. |
| 1314 | // Requires a valid transaction. |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1315 | fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> { |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1316 | 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1325 | key_type = ? |
| 1326 | AND domain = ? |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1327 | AND namespace = ? |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1328 | AND alias = ? |
| 1329 | AND state = ?;", |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1330 | ) |
| 1331 | .context("In load_key_entry_id: Failed to select from keyentry table.")?; |
| 1332 | let mut rows = stmt |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1333 | .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live]) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1334 | .context("In load_key_entry_id: Failed to read from keyentry table.")?; |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 1335 | db_utils::with_rows_extract_one(&mut rows, |row| { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1336 | row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)? |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1337 | .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 Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1346 | /// * Domain::SELINUX: The access tuple is complete and this function only loads |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1347 | /// the key_id for further processing. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1348 | /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid` |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1349 | /// which serves as the namespace. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1350 | /// * Domain::GRANT: The grant table is queried for the `key_id` and the |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1351 | /// `access_vector`. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1352 | /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1353 | /// `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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1359 | key_type: KeyType, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1360 | 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 Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1368 | // Domain::APP. |
| 1369 | Domain::APP | Domain::SELINUX => { |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1370 | let mut access_key = key; |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1371 | if access_key.domain == Domain::APP { |
| 1372 | access_key.nspace = caller_uid as i64; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1373 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1374 | let key_id = Self::load_key_entry_id(&tx, &access_key, key_type) |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1375 | .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1376 | |
| 1377 | Ok((key_id, access_key, None)) |
| 1378 | } |
| 1379 | |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1380 | // Domain::GRANT. In this case we load the key_id and the access_vector |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1381 | // from the grant table. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1382 | Domain::GRANT => { |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1383 | let mut stmt = tx |
| 1384 | .prepare( |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 1385 | "SELECT keyentryid, access_vector FROM persistent.grant |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1386 | WHERE grantee = ? AND id = ?;", |
| 1387 | ) |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1388 | .context("Domain::GRANT prepare statement failed")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1389 | let mut rows = stmt |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1390 | .query(params![caller_uid as i64, key.nspace]) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1391 | .context("Domain:Grant: query failed.")?; |
| 1392 | let (key_id, access_vector): (i64, i32) = |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 1393 | db_utils::with_rows_extract_one(&mut rows, |row| { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1394 | let r = |
| 1395 | row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1396 | Ok(( |
| 1397 | r.get(0).context("Failed to unpack key_id.")?, |
| 1398 | r.get(1).context("Failed to unpack access_vector.")?, |
| 1399 | )) |
| 1400 | }) |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1401 | .context("Domain::GRANT.")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1402 | Ok((key_id, key, Some(access_vector.into()))) |
| 1403 | } |
| 1404 | |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1405 | // Domain::KEY_ID. In this case we load the domain and namespace from the |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1406 | // keyentry database because we need them for access control. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1407 | Domain::KEY_ID => { |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 1408 | 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 Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 1420 | db_utils::with_rows_extract_one(&mut rows, |row| { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1421 | let r = |
| 1422 | row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1423 | Ok(( |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1424 | Domain(r.get(0).context("Failed to unpack domain.")?), |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1425 | r.get(1).context("Failed to unpack namespace.")?, |
| 1426 | )) |
| 1427 | }) |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 1428 | .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 Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1453 | let key_id = key.nspace; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1454 | let mut access_key = key; |
| 1455 | access_key.domain = domain; |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1456 | access_key.nspace = namespace; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1457 | |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 1458 | Ok((key_id, access_key, access_vector)) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1459 | } |
| 1460 | _ => Err(anyhow!(KsError::sys())), |
| 1461 | } |
| 1462 | } |
| 1463 | |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1464 | fn load_blob_components( |
| 1465 | key_id: i64, |
| 1466 | load_bits: KeyEntryLoadBits, |
| 1467 | tx: &Transaction, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1468 | ) -> Result<(bool, Option<Vec<u8>>, Option<Vec<u8>>, Option<Vec<u8>>)> { |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1469 | let mut stmt = tx |
| 1470 | .prepare( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1471 | "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1472 | 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 Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1479 | 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 Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1482 | let mut has_km_blob: bool = false; |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 1483 | db_utils::with_rows_extract_all(&mut rows, |row| { |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1484 | let sub_type: SubComponentType = |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1485 | row.get(1).context("Failed to extract subcomponent_type.")?; |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1486 | has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1487 | 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 Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1490 | } |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1491 | (SubComponentType::CERT, true, _) => { |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1492 | cert_blob = |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1493 | Some(row.get(2).context("Failed to extract public certificate blob.")?); |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1494 | } |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1495 | (SubComponentType::CERT_CHAIN, true, _) => { |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1496 | cert_chain_blob = |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1497 | Some(row.get(2).context("Failed to extract certificate chain blob.")?); |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1498 | } |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1499 | (SubComponentType::CERT, _, _) |
| 1500 | | (SubComponentType::CERT_CHAIN, _, _) |
| 1501 | | (SubComponentType::KEY_BLOB, _, _) => {} |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1502 | _ => Err(KsError::sys()).context("Unknown subcomponent type.")?, |
| 1503 | } |
| 1504 | Ok(()) |
| 1505 | }) |
| 1506 | .context("In load_blob_components.")?; |
| 1507 | |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1508 | Ok((has_km_blob, km_blob, cert_blob, cert_chain_blob)) |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1509 | } |
| 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 Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 1523 | db_utils::with_rows_extract_all(&mut rows, |row| { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1524 | 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 Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1526 | 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 Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 1537 | /// 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1574 | /// 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1582 | key_type: KeyType, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1583 | load_bits: KeyEntryLoadBits, |
| 1584 | caller_uid: u32, |
| 1585 | check_permission: impl FnOnce(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1586 | ) -> 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1595 | let tx = self |
| 1596 | .conn |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1597 | .unchecked_transaction() |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1598 | .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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1602 | Self::load_access_tuple(&tx, key, key_type, caller_uid) |
| 1603 | .context("In load_key_entry.")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1604 | |
| 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 Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1607 | check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1608 | |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1609 | // 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1625 | |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1626 | // 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1643 | key_type, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1644 | 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1654 | let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id()) |
| 1655 | .context("In load_key_entry.")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1656 | |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1657 | tx.commit().context("In load_key_entry: Failed to commit transaction.")?; |
| 1658 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1659 | Ok((key_id_guard, key_entry)) |
| 1660 | } |
| 1661 | |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1662 | fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1663 | 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 Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1669 | tx.execute("DELETE from persistent.grant WHERE keyentryid = ?;", params![key_id]) |
| 1670 | .context("In mark_unreferenced: Failed to drop grants.")?; |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1671 | Ok(updated != 0) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1672 | } |
| 1673 | |
| 1674 | /// Marks the given key as unreferenced and removes all of the grants to this key. |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1675 | /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector. |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1676 | 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 Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1682 | ) -> Result<bool> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1683 | 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 Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1698 | 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1707 | 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 Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1714 | let (has_km_blob, km_blob, cert_blob, cert_chain_blob) = |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1715 | Self::load_blob_components(key_id, load_bits, &tx) |
| 1716 | .context("In load_key_components.")?; |
| 1717 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1718 | let parameters = Self::load_key_parameters(key_id, &tx) |
| 1719 | .context("In load_key_components: Trying to load key parameters.")?; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1720 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1721 | let km_uuid = Self::get_key_km_uuid(&tx, key_id) |
| 1722 | .context("In load_key_components: Trying to get KM uuid.")?; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1723 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1724 | Ok(KeyEntry { |
| 1725 | id: key_id, |
| 1726 | km_blob, |
| 1727 | cert: cert_blob, |
| 1728 | cert_chain: cert_chain_blob, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1729 | km_uuid, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1730 | parameters, |
| 1731 | metadata, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1732 | pure_cert: !has_km_blob, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1733 | }) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1734 | } |
| 1735 | |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 1736 | /// 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 Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1744 | WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;", |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 1745 | ) |
| 1746 | .context("In list: Failed to prepare.")?; |
| 1747 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1748 | let mut rows = stmt |
| 1749 | .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live]) |
| 1750 | .context("In list: Failed to query.")?; |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 1751 | |
| 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1766 | /// 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 Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1788 | // grantee has if key.domain == Domain::GRANT. But this vector |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1789 | // cannot include the grant permission by design, so there is no way the |
| 1790 | // subsequent permission check can pass. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1791 | // We could check key.domain == Domain::GRANT and fail early. |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1792 | // 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1795 | Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid).context("In grant")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1796 | |
| 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 Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 1807 | "SELECT id FROM persistent.grant |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1808 | 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 Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 1816 | "UPDATE persistent.grant |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1817 | 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 Galenson | 845f74b | 2020-09-09 14:11:55 -0700 | [diff] [blame] | 1824 | Self::insert_with_retry(|id| { |
| 1825 | tx.execute( |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 1826 | "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1827 | VALUES (?, ?, ?, ?);", |
Joel Galenson | 845f74b | 2020-09-09 14:11:55 -0700 | [diff] [blame] | 1828 | params![id, grantee_uid, key_id, i32::from(access_vector)], |
| 1829 | ) |
| 1830 | }) |
| 1831 | .context("In grant")? |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1832 | }; |
| 1833 | tx.commit().context("In grant: failed to commit transaction.")?; |
| 1834 | |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1835 | Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None }) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1836 | } |
| 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1855 | Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid) |
| 1856 | .context("In ungrant.")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1857 | |
| 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 Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 1863 | "DELETE FROM persistent.grant |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1864 | 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 Galenson | 845f74b | 2020-09-09 14:11:55 -0700 | [diff] [blame] | 1874 | // 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 Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 1896 | |
| 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 Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 1916 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 1917 | /// Find the newest auth token matching the given predicate. |
| 1918 | pub fn find_auth_token_entry<F>( |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 1919 | &mut self, |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 1920 | 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 Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 1929 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 1930 | let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?; |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 1931 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 1932 | while let Some(row) = rows.next().context("Failed to get next row.")? { |
| 1933 | let entry = AuthTokenEntry::new( |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 1934 | 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 Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 1943 | ); |
| 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 Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 1955 | } |
| 1956 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 1957 | /// 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 Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 1965 | Ok(()) |
| 1966 | } |
| 1967 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 1968 | /// Update last_off_body when on_device_off_body is called |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 1969 | 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 Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 1979 | /// Get last_off_body time when finding auth tokens |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 1980 | fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 1981 | 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 Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 1987 | } |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 1988 | } |
| 1989 | |
| 1990 | #[cfg(test)] |
| 1991 | mod tests { |
| 1992 | |
| 1993 | use super::*; |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1994 | use crate::key_parameter::{ |
| 1995 | Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter, |
| 1996 | KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel, |
| 1997 | }; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1998 | use crate::key_perm_set; |
| 1999 | use crate::permission::{KeyPerm, KeyPermSet}; |
Janis Danisevskis | 2a8330a | 2021-01-20 15:34:26 -0800 | [diff] [blame] | 2000 | use keystore2_test_utils::TempDir; |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 2001 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{ |
| 2002 | HardwareAuthToken::HardwareAuthToken, |
| 2003 | HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type, |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 2004 | }; |
| 2005 | use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{ |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 2006 | Timestamp::Timestamp, |
| 2007 | }; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2008 | use rusqlite::NO_PARAMS; |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 2009 | use rusqlite::{Error, TransactionBehavior}; |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 2010 | use std::cell::RefCell; |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2011 | use std::sync::atomic::{AtomicU8, Ordering}; |
| 2012 | use std::sync::Arc; |
| 2013 | use std::thread; |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 2014 | use std::time::{Duration, SystemTime}; |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 2015 | |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 2016 | 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 Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2023 | 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2036 | #[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 Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 2060 | // 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 Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 2073 | |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 2074 | // Test that we have the correct tables. |
| 2075 | #[test] |
| 2076 | fn test_tables() -> Result<()> { |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 2077 | let db = new_test_db()?; |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 2078 | let tables = db |
| 2079 | .conn |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 2080 | .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")? |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 2081 | .query_map(params![], |row| row.get(0))? |
| 2082 | .collect::<rusqlite::Result<Vec<String>>>()?; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2083 | assert_eq!(tables.len(), 5); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2084 | assert_eq!(tables[0], "blobentry"); |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 2085 | assert_eq!(tables[1], "grant"); |
| 2086 | assert_eq!(tables[2], "keyentry"); |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2087 | assert_eq!(tables[3], "keymetadata"); |
| 2088 | assert_eq!(tables[4], "keyparameter"); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2089 | 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 Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 2094 | |
| 2095 | assert_eq!(tables.len(), 2); |
| 2096 | assert_eq!(tables[0], "authtoken"); |
| 2097 | assert_eq!(tables[1], "metadata"); |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 2098 | Ok(()) |
| 2099 | } |
| 2100 | |
| 2101 | #[test] |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 2102 | 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 Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 2176 | fn test_persistence_for_files() -> Result<()> { |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 2177 | let temp_dir = TempDir::new("persistent_db_test")?; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2178 | let mut db = KeystoreDB::new(temp_dir.path())?; |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 2179 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2180 | db.create_key_entry(Domain::APP, 100, &KEYSTORE_UUID)?; |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 2181 | let entries = get_keyentry(&db)?; |
| 2182 | assert_eq!(entries.len(), 1); |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 2183 | |
| 2184 | let db = KeystoreDB::new(temp_dir.path())?; |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 2185 | |
| 2186 | let entries_new = get_keyentry(&db)?; |
| 2187 | assert_eq!(entries, entries_new); |
| 2188 | Ok(()) |
| 2189 | } |
| 2190 | |
| 2191 | #[test] |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 2192 | fn test_create_key_entry() -> Result<()> { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2193 | 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 Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 2195 | } |
| 2196 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2197 | let mut db = new_test_db()?; |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 2198 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2199 | db.create_key_entry(Domain::APP, 100, &KEYSTORE_UUID)?; |
| 2200 | db.create_key_entry(Domain::SELINUX, 101, &KEYSTORE_UUID)?; |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 2201 | |
| 2202 | let entries = get_keyentry(&db)?; |
| 2203 | assert_eq!(entries.len(), 2); |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2204 | assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID)); |
| 2205 | assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID)); |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 2206 | |
| 2207 | // Test that we must pass in a valid Domain. |
| 2208 | check_result_is_error_containing_string( |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2209 | db.create_key_entry(Domain::GRANT, 102, &KEYSTORE_UUID), |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2210 | "Domain Domain(1) must be either App or SELinux.", |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 2211 | ); |
| 2212 | check_result_is_error_containing_string( |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2213 | db.create_key_entry(Domain::BLOB, 103, &KEYSTORE_UUID), |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2214 | "Domain Domain(3) must be either App or SELinux.", |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 2215 | ); |
| 2216 | check_result_is_error_containing_string( |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2217 | db.create_key_entry(Domain::KEY_ID, 104, &KEYSTORE_UUID), |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2218 | "Domain Domain(4) must be either App or SELinux.", |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 2219 | ); |
| 2220 | |
| 2221 | Ok(()) |
| 2222 | } |
| 2223 | |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2224 | #[test] |
| 2225 | fn test_rebind_alias() -> Result<()> { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2226 | 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 Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2230 | } |
| 2231 | |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 2232 | let mut db = new_test_db()?; |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2233 | db.create_key_entry(Domain::APP, 42, &KEYSTORE_UUID)?; |
| 2234 | db.create_key_entry(Domain::APP, 42, &KEYSTORE_UUID)?; |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2235 | let entries = get_keyentry(&db)?; |
| 2236 | assert_eq!(entries.len(), 2); |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2237 | 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 Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2245 | |
| 2246 | // Test that the first call to rebind_alias sets the alias. |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2247 | rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?; |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2248 | let entries = get_keyentry(&db)?; |
| 2249 | assert_eq!(entries.len(), 2); |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2250 | 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 Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2258 | |
| 2259 | // Test that the second call to rebind_alias also empties the old one. |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2260 | rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?; |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2261 | let entries = get_keyentry(&db)?; |
| 2262 | assert_eq!(entries.len(), 2); |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2263 | 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 Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2268 | |
| 2269 | // Test that we must pass in a valid Domain. |
| 2270 | check_result_is_error_containing_string( |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2271 | rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42), |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2272 | "Domain Domain(1) must be either App or SELinux.", |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2273 | ); |
| 2274 | check_result_is_error_containing_string( |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2275 | rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42), |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2276 | "Domain Domain(3) must be either App or SELinux.", |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2277 | ); |
| 2278 | check_result_is_error_containing_string( |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2279 | rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42), |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2280 | "Domain Domain(4) must be either App or SELinux.", |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2281 | ); |
| 2282 | |
| 2283 | // Test that we correctly handle setting an alias for something that does not exist. |
| 2284 | check_result_is_error_containing_string( |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2285 | rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42), |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2286 | "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 Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2291 | 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 Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2296 | |
| 2297 | Ok(()) |
| 2298 | } |
| 2299 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2300 | #[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 Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2308 | "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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2311 | )?; |
| 2312 | let app_key = KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2313 | domain: super::Domain::APP, |
| 2314 | nspace: 0, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2315 | 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 Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2326 | let app_granted_key = db |
| 2327 | .grant(app_key.clone(), CALLER_UID, GRANTEE_UID, PVEC1, |k, a| { |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2328 | assert_eq!(*a, PVEC1); |
| 2329 | assert_eq!( |
| 2330 | *k, |
| 2331 | KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2332 | domain: super::Domain::APP, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2333 | // namespace must be set to the caller_uid. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2334 | nspace: CALLER_UID as i64, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2335 | alias: Some("key".to_string()), |
| 2336 | blob: None, |
| 2337 | } |
| 2338 | ); |
| 2339 | Ok(()) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2340 | }) |
| 2341 | .unwrap(); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2342 | |
| 2343 | assert_eq!( |
| 2344 | app_granted_key, |
| 2345 | KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2346 | domain: super::Domain::GRANT, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2347 | // The grantid is next_random due to the mock random number generator. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2348 | nspace: next_random, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2349 | alias: None, |
| 2350 | blob: None, |
| 2351 | } |
| 2352 | ); |
| 2353 | |
| 2354 | let selinux_key = KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2355 | domain: super::Domain::SELINUX, |
| 2356 | nspace: SELINUX_NAMESPACE, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2357 | alias: Some("yek".to_string()), |
| 2358 | blob: None, |
| 2359 | }; |
| 2360 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2361 | let selinux_granted_key = db |
| 2362 | .grant(selinux_key.clone(), CALLER_UID, 12, PVEC1, |k, a| { |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2363 | assert_eq!(*a, PVEC1); |
| 2364 | assert_eq!( |
| 2365 | *k, |
| 2366 | KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2367 | domain: super::Domain::SELINUX, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2368 | // namespace must be the supplied SELinux |
| 2369 | // namespace. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2370 | nspace: SELINUX_NAMESPACE, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2371 | alias: Some("yek".to_string()), |
| 2372 | blob: None, |
| 2373 | } |
| 2374 | ); |
| 2375 | Ok(()) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2376 | }) |
| 2377 | .unwrap(); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2378 | |
| 2379 | assert_eq!( |
| 2380 | selinux_granted_key, |
| 2381 | KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2382 | domain: super::Domain::GRANT, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2383 | // The grantid is next_random + 1 due to the mock random number generator. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2384 | nspace: next_random + 1, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2385 | alias: None, |
| 2386 | blob: None, |
| 2387 | } |
| 2388 | ); |
| 2389 | |
| 2390 | // This should update the existing grant with PVEC2. |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2391 | let selinux_granted_key = db |
| 2392 | .grant(selinux_key.clone(), CALLER_UID, 12, PVEC2, |k, a| { |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2393 | assert_eq!(*a, PVEC2); |
| 2394 | assert_eq!( |
| 2395 | *k, |
| 2396 | KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2397 | domain: super::Domain::SELINUX, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2398 | // namespace must be the supplied SELinux |
| 2399 | // namespace. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2400 | nspace: SELINUX_NAMESPACE, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2401 | alias: Some("yek".to_string()), |
| 2402 | blob: None, |
| 2403 | } |
| 2404 | ); |
| 2405 | Ok(()) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2406 | }) |
| 2407 | .unwrap(); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2408 | |
| 2409 | assert_eq!( |
| 2410 | selinux_granted_key, |
| 2411 | KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2412 | domain: super::Domain::GRANT, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2413 | // Same grant id as before. The entry was only updated. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2414 | nspace: next_random + 1, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2415 | 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 Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 2424 | .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?; |
Janis Danisevskis | ee10b5f | 2020-09-22 16:42:35 -0700 | [diff] [blame] | 2425 | 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2434 | |
| 2435 | let r = rows.next().unwrap().unwrap(); |
Janis Danisevskis | ee10b5f | 2020-09-22 16:42:35 -0700 | [diff] [blame] | 2436 | assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1)); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2437 | let r = rows.next().unwrap().unwrap(); |
Janis Danisevskis | ee10b5f | 2020-09-22 16:42:35 -0700 | [diff] [blame] | 2438 | assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2)); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2439 | 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2452 | static TEST_KEY_BLOB: &[u8] = b"my test blob"; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2453 | 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 Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2457 | fn test_set_blob() -> Result<()> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2458 | let key_id = KEY_ID_LOCK.get(3000); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2459 | let mut db = new_test_db()?; |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2460 | 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 Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2463 | drop(key_id); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2464 | |
| 2465 | let mut stmt = db.conn.prepare( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2466 | "SELECT subcomponent_type, keyentryid, blob FROM persistent.blobentry |
| 2467 | ORDER BY subcomponent_type ASC;", |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2468 | )?; |
| 2469 | let mut rows = stmt |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2470 | .query_map::<(SubComponentType, i64, Vec<u8>), _, _>(NO_PARAMS, |row| { |
| 2471 | Ok((row.get(0)?, row.get(1)?, row.get(2)?)) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2472 | })?; |
| 2473 | let r = rows.next().unwrap().unwrap(); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2474 | assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec())); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2475 | let r = rows.next().unwrap().unwrap(); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2476 | assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec())); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2477 | let r = rows.next().unwrap().unwrap(); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2478 | assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec())); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2479 | |
| 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 Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2488 | let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None) |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2489 | .context("test_insert_and_load_full_keyentry_domain_app")? |
| 2490 | .0; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2491 | 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 Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2505 | assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None)); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2506 | |
| 2507 | db.unbind_key( |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2508 | KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2509 | domain: Domain::APP, |
| 2510 | nspace: 0, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2511 | alias: Some(TEST_ALIAS.to_string()), |
| 2512 | blob: None, |
| 2513 | }, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2514 | KeyType::Client, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2515 | 1, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2516 | |_, _| 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2539 | Ok(()) |
| 2540 | } |
| 2541 | |
| 2542 | #[test] |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2543 | 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 Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2554 | &KEYSTORE_UUID, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2555 | ) |
| 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2613 | fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> { |
| 2614 | let mut db = new_test_db()?; |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2615 | let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None) |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2616 | .context("test_insert_and_load_full_keyentry_domain_selinux")? |
| 2617 | .0; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2618 | 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 Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2632 | assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None)); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2633 | |
| 2634 | db.unbind_key( |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2635 | KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2636 | domain: Domain::SELINUX, |
| 2637 | nspace: 1, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2638 | alias: Some(TEST_ALIAS.to_string()), |
| 2639 | blob: None, |
| 2640 | }, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2641 | KeyType::Client, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2642 | 1, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2643 | |_, _| 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2666 | 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 Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2672 | let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None) |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2673 | .context("test_insert_and_load_full_keyentry_domain_key_id")? |
| 2674 | .0; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2675 | 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 Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2685 | assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None)); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2686 | |
| 2687 | db.unbind_key( |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2688 | KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None }, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2689 | KeyType::Client, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2690 | 1, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2691 | |_, _| 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2708 | |
| 2709 | Ok(()) |
| 2710 | } |
| 2711 | |
| 2712 | #[test] |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2713 | 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2761 | fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> { |
| 2762 | let mut db = new_test_db()?; |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2763 | let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None) |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2764 | .context("test_insert_and_load_full_keyentry_from_grant")? |
| 2765 | .0; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2766 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2767 | 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2781 | |
| 2782 | debug_dump_grant_table(&mut db)?; |
| 2783 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2784 | 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2797 | |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2798 | assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None)); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2799 | |
| 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2816 | Ok(()) |
| 2817 | } |
| 2818 | |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 2819 | // 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 Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2903 | static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key"; |
| 2904 | |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2905 | #[test] |
| 2906 | fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> { |
| 2907 | let handle = { |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 2908 | 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 Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2911 | let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None) |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2912 | .context("test_insert_and_load_full_keyentry_domain_app")? |
| 2913 | .0; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2914 | 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 Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2928 | assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None)); |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2929 | 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 Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 2940 | let temp_dir = temp_dir_clone; |
| 2941 | let mut db = KeystoreDB::new(temp_dir.path()).unwrap(); |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2942 | 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2950 | KeyType::Client, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2951 | 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 Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 2979 | #[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 Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3010 | let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None) |
| 3011 | .unwrap_or_else(|e| { |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 3012 | 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 3042 | .load_key_entry( |
| 3043 | d, |
| 3044 | KeyType::Client, |
| 3045 | KeyEntryLoadBits::NONE, |
| 3046 | *namespace as u32, |
| 3047 | |_, _| Ok(()), |
| 3048 | ) |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 3049 | .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 Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3069 | // 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 Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 3085 | #[derive(Debug, PartialEq)] |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3086 | #[allow(dead_code)] |
| 3087 | struct KeyEntryRow { |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3088 | id: i64, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 3089 | key_type: KeyType, |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3090 | domain: Option<Domain>, |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3091 | namespace: Option<i64>, |
| 3092 | alias: Option<String>, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3093 | state: KeyLifeCycle, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3094 | km_uuid: Option<Uuid>, |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3095 | } |
| 3096 | |
| 3097 | fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> { |
| 3098 | db.conn |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 3099 | .prepare("SELECT * FROM persistent.keyentry;")? |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3100 | .query_map(NO_PARAMS, |row| { |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3101 | Ok(KeyEntryRow { |
| 3102 | id: row.get(0)?, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 3103 | key_type: row.get(1)?, |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3104 | domain: match row.get(2)? { |
| 3105 | Some(i) => Some(Domain(i)), |
| 3106 | None => None, |
| 3107 | }, |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3108 | namespace: row.get(3)?, |
| 3109 | alias: row.get(4)?, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3110 | state: row.get(5)?, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3111 | km_uuid: row.get(6)?, |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3112 | }) |
| 3113 | })? |
| 3114 | .map(|r| r.context("Could not read keyentry row.")) |
| 3115 | .collect::<Result<Vec<_>>>() |
| 3116 | } |
| 3117 | |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 3118 | // 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 Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3121 | fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> { |
| 3122 | let mut params = vec![ |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 3123 | 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 Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3337 | ]; |
| 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 Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 3345 | } |
| 3346 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3347 | fn make_test_key_entry( |
| 3348 | db: &mut KeystoreDB, |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3349 | domain: Domain, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3350 | namespace: i64, |
| 3351 | alias: &str, |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3352 | max_usage_count: Option<i32>, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 3353 | ) -> Result<KeyIdGuard> { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3354 | let key_id = db.create_key_entry(domain, namespace, &KEYSTORE_UUID)?; |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 3355 | 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 Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3358 | |
| 3359 | let params = make_test_params(max_usage_count); |
| 3360 | db.insert_keyparameter(&key_id, ¶ms)?; |
| 3361 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 3362 | 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 Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 3368 | rebind_alias(db, &key_id, alias, domain, namespace)?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3369 | Ok(key_id) |
| 3370 | } |
| 3371 | |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3372 | 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 Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 3375 | 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 Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3386 | km_uuid: KEYSTORE_UUID, |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3387 | parameters: params, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 3388 | metadata, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 3389 | pure_cert: false, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 3390 | } |
| 3391 | } |
| 3392 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3393 | fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3394 | let mut stmt = db.conn.prepare( |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3395 | "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;", |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3396 | )?; |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3397 | let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3398 | NO_PARAMS, |
| 3399 | |row| { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3400 | 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 Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3409 | }, |
| 3410 | )?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3411 | |
| 3412 | println!("Key entry table rows:"); |
| 3413 | for r in rows { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3414 | let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap(); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3415 | println!( |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3416 | " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}", |
| 3417 | id, key_type, domain, namespace, alias, state, km_uuid |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3418 | ); |
| 3419 | } |
| 3420 | Ok(()) |
| 3421 | } |
| 3422 | |
| 3423 | fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> { |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 3424 | let mut stmt = db |
| 3425 | .conn |
| 3426 | .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3427 | 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 Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3439 | // 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 Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3446 | fn reset_random() { |
| 3447 | RANDOM_COUNTER.with(|counter| { |
| 3448 | *counter.borrow_mut() = 0; |
| 3449 | }) |
| 3450 | } |
| 3451 | |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3452 | 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 Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 3459 | |
| 3460 | #[test] |
| 3461 | fn test_last_off_body() -> Result<()> { |
| 3462 | let mut db = new_test_db()?; |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 3463 | db.insert_last_off_body(MonotonicRawTime::now())?; |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 3464 | 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 Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 3476 | } |