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 | |
Jeff Vander Stoep | 46bbc61 | 2021-04-09 08:55:21 +0200 | [diff] [blame] | 44 | #![allow(clippy::needless_question_mark)] |
| 45 | |
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 | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 49 | use crate::utils::{get_current_time_in_seconds, AID_USER_OFFSET}; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 50 | use crate::{ |
| 51 | db_utils::{self, SqlField}, |
| 52 | gc::Gc, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 53 | super_key::USER_SUPER_KEY, |
| 54 | }; |
| 55 | use crate::{ |
| 56 | error::{Error as KsError, ErrorCode, ResponseCode}, |
| 57 | super_key::SuperKeyType, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 58 | }; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 59 | use anyhow::{anyhow, Context, Result}; |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 60 | use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError}; |
Janis Danisevskis | 60400fe | 2020-08-26 15:24:42 -0700 | [diff] [blame] | 61 | |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 62 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{ |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 63 | HardwareAuthToken::HardwareAuthToken, |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 64 | HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel, |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 65 | }; |
| 66 | use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{ |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 67 | Timestamp::Timestamp, |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 68 | }; |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 69 | use android_system_keystore2::aidl::android::system::keystore2::{ |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 70 | Domain::Domain, KeyDescriptor::KeyDescriptor, |
Janis Danisevskis | 60400fe | 2020-08-26 15:24:42 -0700 | [diff] [blame] | 71 | }; |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 72 | use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{ |
| 73 | AttestationPoolStatus::AttestationPoolStatus, |
| 74 | }; |
| 75 | |
| 76 | use keystore2_crypto::ZVec; |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 77 | use lazy_static::lazy_static; |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 78 | use log::error; |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 79 | #[cfg(not(test))] |
| 80 | use rand::prelude::random; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 81 | use rusqlite::{ |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 82 | params, |
| 83 | types::FromSql, |
| 84 | types::FromSqlResult, |
| 85 | types::ToSqlOutput, |
| 86 | types::{FromSqlError, Value, ValueRef}, |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 87 | Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 88 | }; |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 89 | |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 90 | use std::{ |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 91 | collections::{HashMap, HashSet}, |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 92 | path::Path, |
| 93 | sync::{Condvar, Mutex}, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 94 | time::{Duration, SystemTime}, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 95 | }; |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 96 | |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 97 | #[cfg(test)] |
| 98 | use tests::random; |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 99 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 100 | impl_metadata!( |
| 101 | /// A set of metadata for key entries. |
| 102 | #[derive(Debug, Default, Eq, PartialEq)] |
| 103 | pub struct KeyMetaData; |
| 104 | /// A metadata entry for key entries. |
| 105 | #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)] |
| 106 | pub enum KeyMetaEntry { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 107 | /// Date of the creation of the key entry. |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 108 | CreationDate(DateTime) with accessor creation_date, |
| 109 | /// Expiration date for attestation keys. |
| 110 | AttestationExpirationDate(DateTime) with accessor attestation_expiration_date, |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 111 | /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote |
| 112 | /// provisioning |
| 113 | AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key, |
| 114 | /// Vector representing the raw public key so results from the server can be matched |
| 115 | /// to the right entry |
| 116 | AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 117 | /// SEC1 public key for ECDH encryption |
| 118 | Sec1PublicKey(Vec<u8>) with accessor sec1_public_key, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 119 | // --- ADD NEW META DATA FIELDS HERE --- |
| 120 | // For backwards compatibility add new entries only to |
| 121 | // end of this list and above this comment. |
| 122 | }; |
| 123 | ); |
| 124 | |
| 125 | impl KeyMetaData { |
| 126 | fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> { |
| 127 | let mut stmt = tx |
| 128 | .prepare( |
| 129 | "SELECT tag, data from persistent.keymetadata |
| 130 | WHERE keyentryid = ?;", |
| 131 | ) |
| 132 | .context("In KeyMetaData::load_from_db: prepare statement failed.")?; |
| 133 | |
| 134 | let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default(); |
| 135 | |
| 136 | let mut rows = |
| 137 | stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?; |
| 138 | db_utils::with_rows_extract_all(&mut rows, |row| { |
| 139 | let db_tag: i64 = row.get(0).context("Failed to read tag.")?; |
| 140 | metadata.insert( |
| 141 | db_tag, |
| 142 | KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row)) |
| 143 | .context("Failed to read KeyMetaEntry.")?, |
| 144 | ); |
| 145 | Ok(()) |
| 146 | }) |
| 147 | .context("In KeyMetaData::load_from_db.")?; |
| 148 | |
| 149 | Ok(Self { data: metadata }) |
| 150 | } |
| 151 | |
| 152 | fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> { |
| 153 | let mut stmt = tx |
| 154 | .prepare( |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 155 | "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data) |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 156 | VALUES (?, ?, ?);", |
| 157 | ) |
| 158 | .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?; |
| 159 | |
| 160 | let iter = self.data.iter(); |
| 161 | for (tag, entry) in iter { |
| 162 | stmt.insert(params![key_id, tag, entry,]).with_context(|| { |
| 163 | format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry) |
| 164 | })?; |
| 165 | } |
| 166 | Ok(()) |
| 167 | } |
| 168 | } |
| 169 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 170 | impl_metadata!( |
| 171 | /// A set of metadata for key blobs. |
| 172 | #[derive(Debug, Default, Eq, PartialEq)] |
| 173 | pub struct BlobMetaData; |
| 174 | /// A metadata entry for key blobs. |
| 175 | #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)] |
| 176 | pub enum BlobMetaEntry { |
| 177 | /// If present, indicates that the blob is encrypted with another key or a key derived |
| 178 | /// from a password. |
| 179 | EncryptedBy(EncryptedBy) with accessor encrypted_by, |
| 180 | /// If the blob is password encrypted this field is set to the |
| 181 | /// salt used for the key derivation. |
| 182 | Salt(Vec<u8>) with accessor salt, |
| 183 | /// If the blob is encrypted, this field is set to the initialization vector. |
| 184 | Iv(Vec<u8>) with accessor iv, |
| 185 | /// If the blob is encrypted, this field holds the AEAD TAG. |
| 186 | AeadTag(Vec<u8>) with accessor aead_tag, |
| 187 | /// The uuid of the owning KeyMint instance. |
| 188 | KmUuid(Uuid) with accessor km_uuid, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 189 | /// If the key is ECDH encrypted, this is the ephemeral public key |
| 190 | PublicKey(Vec<u8>) with accessor public_key, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 191 | // --- ADD NEW META DATA FIELDS HERE --- |
| 192 | // For backwards compatibility add new entries only to |
| 193 | // end of this list and above this comment. |
| 194 | }; |
| 195 | ); |
| 196 | |
| 197 | impl BlobMetaData { |
| 198 | fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> { |
| 199 | let mut stmt = tx |
| 200 | .prepare( |
| 201 | "SELECT tag, data from persistent.blobmetadata |
| 202 | WHERE blobentryid = ?;", |
| 203 | ) |
| 204 | .context("In BlobMetaData::load_from_db: prepare statement failed.")?; |
| 205 | |
| 206 | let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default(); |
| 207 | |
| 208 | let mut rows = |
| 209 | stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?; |
| 210 | db_utils::with_rows_extract_all(&mut rows, |row| { |
| 211 | let db_tag: i64 = row.get(0).context("Failed to read tag.")?; |
| 212 | metadata.insert( |
| 213 | db_tag, |
| 214 | BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row)) |
| 215 | .context("Failed to read BlobMetaEntry.")?, |
| 216 | ); |
| 217 | Ok(()) |
| 218 | }) |
| 219 | .context("In BlobMetaData::load_from_db.")?; |
| 220 | |
| 221 | Ok(Self { data: metadata }) |
| 222 | } |
| 223 | |
| 224 | fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> { |
| 225 | let mut stmt = tx |
| 226 | .prepare( |
| 227 | "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data) |
| 228 | VALUES (?, ?, ?);", |
| 229 | ) |
| 230 | .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?; |
| 231 | |
| 232 | let iter = self.data.iter(); |
| 233 | for (tag, entry) in iter { |
| 234 | stmt.insert(params![blob_id, tag, entry,]).with_context(|| { |
| 235 | format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry) |
| 236 | })?; |
| 237 | } |
| 238 | Ok(()) |
| 239 | } |
| 240 | } |
| 241 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 242 | /// Indicates the type of the keyentry. |
| 243 | #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] |
| 244 | pub enum KeyType { |
| 245 | /// This is a client key type. These keys are created or imported through the Keystore 2.0 |
| 246 | /// AIDL interface android.system.keystore2. |
| 247 | Client, |
| 248 | /// This is a super key type. These keys are created by keystore itself and used to encrypt |
| 249 | /// other key blobs to provide LSKF binding. |
| 250 | Super, |
| 251 | /// This is an attestation key. These keys are created by the remote provisioning mechanism. |
| 252 | Attestation, |
| 253 | } |
| 254 | |
| 255 | impl ToSql for KeyType { |
| 256 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 257 | Ok(ToSqlOutput::Owned(Value::Integer(match self { |
| 258 | KeyType::Client => 0, |
| 259 | KeyType::Super => 1, |
| 260 | KeyType::Attestation => 2, |
| 261 | }))) |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | impl FromSql for KeyType { |
| 266 | fn column_result(value: ValueRef) -> FromSqlResult<Self> { |
| 267 | match i64::column_result(value)? { |
| 268 | 0 => Ok(KeyType::Client), |
| 269 | 1 => Ok(KeyType::Super), |
| 270 | 2 => Ok(KeyType::Attestation), |
| 271 | v => Err(FromSqlError::OutOfRange(v)), |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 276 | /// Uuid representation that can be stored in the database. |
| 277 | /// Right now it can only be initialized from SecurityLevel. |
| 278 | /// Once KeyMint provides a UUID type a corresponding From impl shall be added. |
| 279 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 280 | pub struct Uuid([u8; 16]); |
| 281 | |
| 282 | impl Deref for Uuid { |
| 283 | type Target = [u8; 16]; |
| 284 | |
| 285 | fn deref(&self) -> &Self::Target { |
| 286 | &self.0 |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | impl From<SecurityLevel> for Uuid { |
| 291 | fn from(sec_level: SecurityLevel) -> Self { |
| 292 | Self((sec_level.0 as u128).to_be_bytes()) |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | impl ToSql for Uuid { |
| 297 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 298 | self.0.to_sql() |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | impl FromSql for Uuid { |
| 303 | fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> { |
| 304 | let blob = Vec::<u8>::column_result(value)?; |
| 305 | if blob.len() != 16 { |
| 306 | return Err(FromSqlError::OutOfRange(blob.len() as i64)); |
| 307 | } |
| 308 | let mut arr = [0u8; 16]; |
| 309 | arr.copy_from_slice(&blob); |
| 310 | Ok(Self(arr)) |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | /// Key entries that are not associated with any KeyMint instance, such as pure certificate |
| 315 | /// entries are associated with this UUID. |
| 316 | pub static KEYSTORE_UUID: Uuid = Uuid([ |
| 317 | 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11, |
| 318 | ]); |
| 319 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 320 | /// Indicates how the sensitive part of this key blob is encrypted. |
| 321 | #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)] |
| 322 | pub enum EncryptedBy { |
| 323 | /// The keyblob is encrypted by a user password. |
| 324 | /// In the database this variant is represented as NULL. |
| 325 | Password, |
| 326 | /// The keyblob is encrypted by another key with wrapped key id. |
| 327 | /// In the database this variant is represented as non NULL value |
| 328 | /// that is convertible to i64, typically NUMERIC. |
| 329 | KeyId(i64), |
| 330 | } |
| 331 | |
| 332 | impl ToSql for EncryptedBy { |
| 333 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 334 | match self { |
| 335 | Self::Password => Ok(ToSqlOutput::Owned(Value::Null)), |
| 336 | Self::KeyId(id) => id.to_sql(), |
| 337 | } |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | impl FromSql for EncryptedBy { |
| 342 | fn column_result(value: ValueRef) -> FromSqlResult<Self> { |
| 343 | match value { |
| 344 | ValueRef::Null => Ok(Self::Password), |
| 345 | _ => Ok(Self::KeyId(i64::column_result(value)?)), |
| 346 | } |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | /// A database representation of wall clock time. DateTime stores unix epoch time as |
| 351 | /// i64 in milliseconds. |
| 352 | #[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)] |
| 353 | pub struct DateTime(i64); |
| 354 | |
| 355 | /// Error type returned when creating DateTime or converting it from and to |
| 356 | /// SystemTime. |
| 357 | #[derive(thiserror::Error, Debug)] |
| 358 | pub enum DateTimeError { |
| 359 | /// This is returned when SystemTime and Duration computations fail. |
| 360 | #[error(transparent)] |
| 361 | SystemTimeError(#[from] SystemTimeError), |
| 362 | |
| 363 | /// This is returned when type conversions fail. |
| 364 | #[error(transparent)] |
| 365 | TypeConversion(#[from] std::num::TryFromIntError), |
| 366 | |
| 367 | /// This is returned when checked time arithmetic failed. |
| 368 | #[error("Time arithmetic failed.")] |
| 369 | TimeArithmetic, |
| 370 | } |
| 371 | |
| 372 | impl DateTime { |
| 373 | /// Constructs a new DateTime object denoting the current time. This may fail during |
| 374 | /// conversion to unix epoch time and during conversion to the internal i64 representation. |
| 375 | pub fn now() -> Result<Self, DateTimeError> { |
| 376 | Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?)) |
| 377 | } |
| 378 | |
| 379 | /// Constructs a new DateTime object from milliseconds. |
| 380 | pub fn from_millis_epoch(millis: i64) -> Self { |
| 381 | Self(millis) |
| 382 | } |
| 383 | |
| 384 | /// Returns unix epoch time in milliseconds. |
| 385 | pub fn to_millis_epoch(&self) -> i64 { |
| 386 | self.0 |
| 387 | } |
| 388 | |
| 389 | /// Returns unix epoch time in seconds. |
| 390 | pub fn to_secs_epoch(&self) -> i64 { |
| 391 | self.0 / 1000 |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | impl ToSql for DateTime { |
| 396 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 397 | Ok(ToSqlOutput::Owned(Value::Integer(self.0))) |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | impl FromSql for DateTime { |
| 402 | fn column_result(value: ValueRef) -> FromSqlResult<Self> { |
| 403 | Ok(Self(i64::column_result(value)?)) |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | impl TryInto<SystemTime> for DateTime { |
| 408 | type Error = DateTimeError; |
| 409 | |
| 410 | fn try_into(self) -> Result<SystemTime, Self::Error> { |
| 411 | // We want to construct a SystemTime representation equivalent to self, denoting |
| 412 | // a point in time THEN, but we cannot set the time directly. We can only construct |
| 413 | // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW, |
| 414 | // and between EPOCH and THEN. With this common reference we can construct the |
| 415 | // duration between NOW and THEN which we can add to our SystemTime representation |
| 416 | // of NOW to get a SystemTime representation of THEN. |
| 417 | // Durations can only be positive, thus the if statement below. |
| 418 | let now = SystemTime::now(); |
| 419 | let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?; |
| 420 | let then_epoch = Duration::from_millis(self.0.try_into()?); |
| 421 | Ok(if now_epoch > then_epoch { |
| 422 | // then = now - (now_epoch - then_epoch) |
| 423 | now_epoch |
| 424 | .checked_sub(then_epoch) |
| 425 | .and_then(|d| now.checked_sub(d)) |
| 426 | .ok_or(DateTimeError::TimeArithmetic)? |
| 427 | } else { |
| 428 | // then = now + (then_epoch - now_epoch) |
| 429 | then_epoch |
| 430 | .checked_sub(now_epoch) |
| 431 | .and_then(|d| now.checked_add(d)) |
| 432 | .ok_or(DateTimeError::TimeArithmetic)? |
| 433 | }) |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | impl TryFrom<SystemTime> for DateTime { |
| 438 | type Error = DateTimeError; |
| 439 | |
| 440 | fn try_from(t: SystemTime) -> Result<Self, Self::Error> { |
| 441 | Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?)) |
| 442 | } |
| 443 | } |
| 444 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 445 | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] |
| 446 | enum KeyLifeCycle { |
| 447 | /// Existing keys have a key ID but are not fully populated yet. |
| 448 | /// This is a transient state. If Keystore finds any such keys when it starts up, it must move |
| 449 | /// them to Unreferenced for garbage collection. |
| 450 | Existing, |
| 451 | /// A live key is fully populated and usable by clients. |
| 452 | Live, |
| 453 | /// An unreferenced key is scheduled for garbage collection. |
| 454 | Unreferenced, |
| 455 | } |
| 456 | |
| 457 | impl ToSql for KeyLifeCycle { |
| 458 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 459 | match self { |
| 460 | Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))), |
| 461 | Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))), |
| 462 | Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))), |
| 463 | } |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | impl FromSql for KeyLifeCycle { |
| 468 | fn column_result(value: ValueRef) -> FromSqlResult<Self> { |
| 469 | match i64::column_result(value)? { |
| 470 | 0 => Ok(KeyLifeCycle::Existing), |
| 471 | 1 => Ok(KeyLifeCycle::Live), |
| 472 | 2 => Ok(KeyLifeCycle::Unreferenced), |
| 473 | v => Err(FromSqlError::OutOfRange(v)), |
| 474 | } |
| 475 | } |
| 476 | } |
| 477 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 478 | /// Keys have a KeyMint blob component and optional public certificate and |
| 479 | /// certificate chain components. |
| 480 | /// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry` |
| 481 | /// which components shall be loaded from the database if present. |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 482 | #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 483 | pub struct KeyEntryLoadBits(u32); |
| 484 | |
| 485 | impl KeyEntryLoadBits { |
| 486 | /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded. |
| 487 | pub const NONE: KeyEntryLoadBits = Self(0); |
| 488 | /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded. |
| 489 | pub const KM: KeyEntryLoadBits = Self(1); |
| 490 | /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded. |
| 491 | pub const PUBLIC: KeyEntryLoadBits = Self(2); |
| 492 | /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded. |
| 493 | pub const BOTH: KeyEntryLoadBits = Self(3); |
| 494 | |
| 495 | /// Returns true if this object indicates that the public components shall be loaded. |
| 496 | pub const fn load_public(&self) -> bool { |
| 497 | self.0 & Self::PUBLIC.0 != 0 |
| 498 | } |
| 499 | |
| 500 | /// Returns true if the object indicates that the KeyMint component shall be loaded. |
| 501 | pub const fn load_km(&self) -> bool { |
| 502 | self.0 & Self::KM.0 != 0 |
| 503 | } |
| 504 | } |
| 505 | |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 506 | lazy_static! { |
| 507 | static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new(); |
| 508 | } |
| 509 | |
| 510 | struct KeyIdLockDb { |
| 511 | locked_keys: Mutex<HashSet<i64>>, |
| 512 | cond_var: Condvar, |
| 513 | } |
| 514 | |
| 515 | /// A locked key. While a guard exists for a given key id, the same key cannot be loaded |
| 516 | /// from the database a second time. Most functions manipulating the key blob database |
| 517 | /// require a KeyIdGuard. |
| 518 | #[derive(Debug)] |
| 519 | pub struct KeyIdGuard(i64); |
| 520 | |
| 521 | impl KeyIdLockDb { |
| 522 | fn new() -> Self { |
| 523 | Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() } |
| 524 | } |
| 525 | |
| 526 | /// This function blocks until an exclusive lock for the given key entry id can |
| 527 | /// be acquired. It returns a guard object, that represents the lifecycle of the |
| 528 | /// acquired lock. |
| 529 | pub fn get(&self, key_id: i64) -> KeyIdGuard { |
| 530 | let mut locked_keys = self.locked_keys.lock().unwrap(); |
| 531 | while locked_keys.contains(&key_id) { |
| 532 | locked_keys = self.cond_var.wait(locked_keys).unwrap(); |
| 533 | } |
| 534 | locked_keys.insert(key_id); |
| 535 | KeyIdGuard(key_id) |
| 536 | } |
| 537 | |
| 538 | /// This function attempts to acquire an exclusive lock on a given key id. If the |
| 539 | /// given key id is already taken the function returns None immediately. If a lock |
| 540 | /// can be acquired this function returns a guard object, that represents the |
| 541 | /// lifecycle of the acquired lock. |
| 542 | pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> { |
| 543 | let mut locked_keys = self.locked_keys.lock().unwrap(); |
| 544 | if locked_keys.insert(key_id) { |
| 545 | Some(KeyIdGuard(key_id)) |
| 546 | } else { |
| 547 | None |
| 548 | } |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | impl KeyIdGuard { |
| 553 | /// Get the numeric key id of the locked key. |
| 554 | pub fn id(&self) -> i64 { |
| 555 | self.0 |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | impl Drop for KeyIdGuard { |
| 560 | fn drop(&mut self) { |
| 561 | let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap(); |
| 562 | locked_keys.remove(&self.0); |
Janis Danisevskis | 7fd5358 | 2020-11-23 13:40:34 -0800 | [diff] [blame] | 563 | drop(locked_keys); |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 564 | KEY_ID_LOCK.cond_var.notify_all(); |
| 565 | } |
| 566 | } |
| 567 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 568 | /// This type represents a certificate and certificate chain entry for a key. |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 569 | #[derive(Debug, Default)] |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 570 | pub struct CertificateInfo { |
| 571 | cert: Option<Vec<u8>>, |
| 572 | cert_chain: Option<Vec<u8>>, |
| 573 | } |
| 574 | |
| 575 | impl CertificateInfo { |
| 576 | /// Constructs a new CertificateInfo object from `cert` and `cert_chain` |
| 577 | pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self { |
| 578 | Self { cert, cert_chain } |
| 579 | } |
| 580 | |
| 581 | /// Take the cert |
| 582 | pub fn take_cert(&mut self) -> Option<Vec<u8>> { |
| 583 | self.cert.take() |
| 584 | } |
| 585 | |
| 586 | /// Take the cert chain |
| 587 | pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> { |
| 588 | self.cert_chain.take() |
| 589 | } |
| 590 | } |
| 591 | |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 592 | /// This type represents a certificate chain with a private key corresponding to the leaf |
| 593 | /// certificate. TODO(jbires): This will be used in a follow-on CL, for now it's used in the tests. |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 594 | pub struct CertificateChain { |
Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 595 | /// A KM key blob |
| 596 | pub private_key: ZVec, |
| 597 | /// A batch cert for private_key |
| 598 | pub batch_cert: Vec<u8>, |
| 599 | /// A full certificate chain from root signing authority to private_key, including batch_cert |
| 600 | /// for convenience. |
| 601 | pub cert_chain: Vec<u8>, |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 602 | } |
| 603 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 604 | /// This type represents a Keystore 2.0 key entry. |
| 605 | /// An entry has a unique `id` by which it can be found in the database. |
| 606 | /// It has a security level field, key parameters, and three optional fields |
| 607 | /// for the KeyMint blob, public certificate and a public certificate chain. |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 608 | #[derive(Debug, Default, Eq, PartialEq)] |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 609 | pub struct KeyEntry { |
| 610 | id: i64, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 611 | key_blob_info: Option<(Vec<u8>, BlobMetaData)>, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 612 | cert: Option<Vec<u8>>, |
| 613 | cert_chain: Option<Vec<u8>>, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 614 | km_uuid: Uuid, |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 615 | parameters: Vec<KeyParameter>, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 616 | metadata: KeyMetaData, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 617 | pure_cert: bool, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 618 | } |
| 619 | |
| 620 | impl KeyEntry { |
| 621 | /// Returns the unique id of the Key entry. |
| 622 | pub fn id(&self) -> i64 { |
| 623 | self.id |
| 624 | } |
| 625 | /// Exposes the optional KeyMint blob. |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 626 | pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> { |
| 627 | &self.key_blob_info |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 628 | } |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 629 | /// Extracts the Optional KeyMint blob including its metadata. |
| 630 | pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> { |
| 631 | self.key_blob_info.take() |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 632 | } |
| 633 | /// Exposes the optional public certificate. |
| 634 | pub fn cert(&self) -> &Option<Vec<u8>> { |
| 635 | &self.cert |
| 636 | } |
| 637 | /// Extracts the optional public certificate. |
| 638 | pub fn take_cert(&mut self) -> Option<Vec<u8>> { |
| 639 | self.cert.take() |
| 640 | } |
| 641 | /// Exposes the optional public certificate chain. |
| 642 | pub fn cert_chain(&self) -> &Option<Vec<u8>> { |
| 643 | &self.cert_chain |
| 644 | } |
| 645 | /// Extracts the optional public certificate_chain. |
| 646 | pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> { |
| 647 | self.cert_chain.take() |
| 648 | } |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 649 | /// Returns the uuid of the owning KeyMint instance. |
| 650 | pub fn km_uuid(&self) -> &Uuid { |
| 651 | &self.km_uuid |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 652 | } |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 653 | /// Exposes the key parameters of this key entry. |
| 654 | pub fn key_parameters(&self) -> &Vec<KeyParameter> { |
| 655 | &self.parameters |
| 656 | } |
| 657 | /// Consumes this key entry and extracts the keyparameters from it. |
| 658 | pub fn into_key_parameters(self) -> Vec<KeyParameter> { |
| 659 | self.parameters |
| 660 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 661 | /// Exposes the key metadata of this key entry. |
| 662 | pub fn metadata(&self) -> &KeyMetaData { |
| 663 | &self.metadata |
| 664 | } |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 665 | /// This returns true if the entry is a pure certificate entry with no |
| 666 | /// private key component. |
| 667 | pub fn pure_cert(&self) -> bool { |
| 668 | self.pure_cert |
| 669 | } |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 670 | /// Consumes this key entry and extracts the keyparameters and metadata from it. |
| 671 | pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) { |
| 672 | (self.parameters, self.metadata) |
| 673 | } |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 674 | } |
| 675 | |
| 676 | /// Indicates the sub component of a key entry for persistent storage. |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 677 | #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 678 | pub struct SubComponentType(u32); |
| 679 | impl SubComponentType { |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 680 | /// Persistent identifier for a key blob. |
| 681 | pub const KEY_BLOB: SubComponentType = Self(0); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 682 | /// Persistent identifier for a certificate blob. |
| 683 | pub const CERT: SubComponentType = Self(1); |
| 684 | /// Persistent identifier for a certificate chain blob. |
| 685 | pub const CERT_CHAIN: SubComponentType = Self(2); |
| 686 | } |
| 687 | |
| 688 | impl ToSql for SubComponentType { |
| 689 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 690 | self.0.to_sql() |
| 691 | } |
| 692 | } |
| 693 | |
| 694 | impl FromSql for SubComponentType { |
| 695 | fn column_result(value: ValueRef) -> FromSqlResult<Self> { |
| 696 | Ok(Self(u32::column_result(value)?)) |
| 697 | } |
| 698 | } |
| 699 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 700 | /// This trait is private to the database module. It is used to convey whether or not the garbage |
| 701 | /// collector shall be invoked after a database access. All closures passed to |
| 702 | /// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the |
| 703 | /// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T> |
| 704 | /// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or |
| 705 | /// `.need_gc()`. |
| 706 | trait DoGc<T> { |
| 707 | fn do_gc(self, need_gc: bool) -> Result<(bool, T)>; |
| 708 | |
| 709 | fn no_gc(self) -> Result<(bool, T)>; |
| 710 | |
| 711 | fn need_gc(self) -> Result<(bool, T)>; |
| 712 | } |
| 713 | |
| 714 | impl<T> DoGc<T> for Result<T> { |
| 715 | fn do_gc(self, need_gc: bool) -> Result<(bool, T)> { |
| 716 | self.map(|r| (need_gc, r)) |
| 717 | } |
| 718 | |
| 719 | fn no_gc(self) -> Result<(bool, T)> { |
| 720 | self.do_gc(false) |
| 721 | } |
| 722 | |
| 723 | fn need_gc(self) -> Result<(bool, T)> { |
| 724 | self.do_gc(true) |
| 725 | } |
| 726 | } |
| 727 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 728 | /// KeystoreDB wraps a connection to an SQLite database and tracks its |
| 729 | /// ownership. It also implements all of Keystore 2.0's database functionality. |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 730 | pub struct KeystoreDB { |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 731 | conn: Connection, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 732 | gc: Option<Gc>, |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 733 | } |
| 734 | |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 735 | /// Database representation of the monotonic time retrieved from the system call clock_gettime with |
| 736 | /// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds. |
| 737 | #[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)] |
| 738 | pub struct MonotonicRawTime(i64); |
| 739 | |
| 740 | impl MonotonicRawTime { |
| 741 | /// Constructs a new MonotonicRawTime |
| 742 | pub fn now() -> Self { |
| 743 | Self(get_current_time_in_seconds()) |
| 744 | } |
| 745 | |
David Drysdale | 0e45a61 | 2021-02-25 17:24:36 +0000 | [diff] [blame] | 746 | /// Constructs a new MonotonicRawTime from a given number of seconds. |
| 747 | pub fn from_secs(val: i64) -> Self { |
| 748 | Self(val) |
| 749 | } |
| 750 | |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 751 | /// Returns the integer value of MonotonicRawTime as i64 |
| 752 | pub fn seconds(&self) -> i64 { |
| 753 | self.0 |
| 754 | } |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 755 | |
Hasini Gunasinghe | b3715fb | 2021-02-26 20:34:45 +0000 | [diff] [blame] | 756 | /// Returns the value of MonotonicRawTime in milli seconds as i64 |
| 757 | pub fn milli_seconds(&self) -> i64 { |
| 758 | self.0 * 1000 |
| 759 | } |
| 760 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 761 | /// Like i64::checked_sub. |
| 762 | pub fn checked_sub(&self, other: &Self) -> Option<Self> { |
| 763 | self.0.checked_sub(other.0).map(Self) |
| 764 | } |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 765 | } |
| 766 | |
| 767 | impl ToSql for MonotonicRawTime { |
| 768 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 769 | Ok(ToSqlOutput::Owned(Value::Integer(self.0))) |
| 770 | } |
| 771 | } |
| 772 | |
| 773 | impl FromSql for MonotonicRawTime { |
| 774 | fn column_result(value: ValueRef) -> FromSqlResult<Self> { |
| 775 | Ok(Self(i64::column_result(value)?)) |
| 776 | } |
| 777 | } |
| 778 | |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 779 | /// This struct encapsulates the information to be stored in the database about the auth tokens |
| 780 | /// received by keystore. |
| 781 | pub struct AuthTokenEntry { |
| 782 | auth_token: HardwareAuthToken, |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 783 | time_received: MonotonicRawTime, |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 784 | } |
| 785 | |
| 786 | impl AuthTokenEntry { |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 787 | fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self { |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 788 | AuthTokenEntry { auth_token, time_received } |
| 789 | } |
| 790 | |
| 791 | /// Checks if this auth token satisfies the given authentication information. |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 792 | pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool { |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 793 | user_secure_ids.iter().any(|&sid| { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 794 | (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId) |
| 795 | && (((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] | 796 | }) |
| 797 | } |
| 798 | |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 799 | /// Returns the auth token wrapped by the AuthTokenEntry |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 800 | pub fn auth_token(&self) -> &HardwareAuthToken { |
| 801 | &self.auth_token |
| 802 | } |
| 803 | |
| 804 | /// Returns the auth token wrapped by the AuthTokenEntry |
| 805 | pub fn take_auth_token(self) -> HardwareAuthToken { |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 806 | self.auth_token |
| 807 | } |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 808 | |
| 809 | /// Returns the time that this auth token was received. |
| 810 | pub fn time_received(&self) -> MonotonicRawTime { |
| 811 | self.time_received |
| 812 | } |
Hasini Gunasinghe | b3715fb | 2021-02-26 20:34:45 +0000 | [diff] [blame] | 813 | |
| 814 | /// Returns the challenge value of the auth token. |
| 815 | pub fn challenge(&self) -> i64 { |
| 816 | self.auth_token.challenge |
| 817 | } |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 818 | } |
| 819 | |
Janis Danisevskis | b00ebd0 | 2021-02-02 21:52:24 -0800 | [diff] [blame] | 820 | /// Shared in-memory databases get destroyed as soon as the last connection to them gets closed. |
| 821 | /// This object does not allow access to the database connection. But it keeps a database |
| 822 | /// connection alive in order to keep the in memory per boot database alive. |
| 823 | pub struct PerBootDbKeepAlive(Connection); |
| 824 | |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 825 | impl KeystoreDB { |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 826 | const UNASSIGNED_KEY_ID: i64 = -1i64; |
Janis Danisevskis | b00ebd0 | 2021-02-02 21:52:24 -0800 | [diff] [blame] | 827 | const PERBOOT_DB_FILE_NAME: &'static str = &"file:perboot.sqlite?mode=memory&cache=shared"; |
| 828 | |
| 829 | /// This creates a PerBootDbKeepAlive object to keep the per boot database alive. |
| 830 | pub fn keep_perboot_db_alive() -> Result<PerBootDbKeepAlive> { |
| 831 | let conn = Connection::open_in_memory() |
| 832 | .context("In keep_perboot_db_alive: Failed to initialize SQLite connection.")?; |
| 833 | |
| 834 | conn.execute("ATTACH DATABASE ? as perboot;", params![Self::PERBOOT_DB_FILE_NAME]) |
| 835 | .context("In keep_perboot_db_alive: Failed to attach database perboot.")?; |
| 836 | Ok(PerBootDbKeepAlive(conn)) |
| 837 | } |
| 838 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 839 | /// This will create a new database connection connecting the two |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 840 | /// files persistent.sqlite and perboot.sqlite in the given directory. |
| 841 | /// It also attempts to initialize all of the tables. |
| 842 | /// KeystoreDB cannot be used by multiple threads. |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 843 | /// Each thread should open their own connection using `thread_local!`. |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 844 | pub fn new(db_root: &Path, gc: Option<Gc>) -> Result<Self> { |
Janis Danisevskis | b00ebd0 | 2021-02-02 21:52:24 -0800 | [diff] [blame] | 845 | // Build the path to the sqlite file. |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 846 | let mut persistent_path = db_root.to_path_buf(); |
| 847 | persistent_path.push("persistent.sqlite"); |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 848 | |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 849 | // Now convert them to strings prefixed with "file:" |
| 850 | let mut persistent_path_str = "file:".to_owned(); |
| 851 | persistent_path_str.push_str(&persistent_path.to_string_lossy()); |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 852 | |
Janis Danisevskis | b00ebd0 | 2021-02-02 21:52:24 -0800 | [diff] [blame] | 853 | let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?; |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 854 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 855 | // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite. |
| 856 | conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?; |
| 857 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 858 | let mut db = Self { conn, gc }; |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 859 | db.with_transaction(TransactionBehavior::Immediate, |tx| { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 860 | Self::init_tables(tx).context("Trying to initialize tables.").no_gc() |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 861 | })?; |
| 862 | Ok(db) |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 863 | } |
| 864 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 865 | fn init_tables(tx: &Transaction) -> Result<()> { |
| 866 | tx.execute( |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 867 | "CREATE TABLE IF NOT EXISTS persistent.keyentry ( |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 868 | id INTEGER UNIQUE, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 869 | key_type INTEGER, |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 870 | domain INTEGER, |
| 871 | namespace INTEGER, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 872 | alias BLOB, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 873 | state INTEGER, |
| 874 | km_uuid BLOB);", |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 875 | NO_PARAMS, |
| 876 | ) |
| 877 | .context("Failed to initialize \"keyentry\" table.")?; |
| 878 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 879 | tx.execute( |
Janis Danisevskis | a543818 | 2021-02-02 14:22:59 -0800 | [diff] [blame] | 880 | "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index |
| 881 | ON keyentry(id);", |
| 882 | NO_PARAMS, |
| 883 | ) |
| 884 | .context("Failed to create index keyentry_id_index.")?; |
| 885 | |
| 886 | tx.execute( |
| 887 | "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index |
| 888 | ON keyentry(domain, namespace, alias);", |
| 889 | NO_PARAMS, |
| 890 | ) |
| 891 | .context("Failed to create index keyentry_domain_namespace_index.")?; |
| 892 | |
| 893 | tx.execute( |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 894 | "CREATE TABLE IF NOT EXISTS persistent.blobentry ( |
| 895 | id INTEGER PRIMARY KEY, |
| 896 | subcomponent_type INTEGER, |
| 897 | keyentryid INTEGER, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 898 | blob BLOB);", |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 899 | NO_PARAMS, |
| 900 | ) |
| 901 | .context("Failed to initialize \"blobentry\" table.")?; |
| 902 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 903 | tx.execute( |
Janis Danisevskis | a543818 | 2021-02-02 14:22:59 -0800 | [diff] [blame] | 904 | "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index |
| 905 | ON blobentry(keyentryid);", |
| 906 | NO_PARAMS, |
| 907 | ) |
| 908 | .context("Failed to create index blobentry_keyentryid_index.")?; |
| 909 | |
| 910 | tx.execute( |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 911 | "CREATE TABLE IF NOT EXISTS persistent.blobmetadata ( |
| 912 | id INTEGER PRIMARY KEY, |
| 913 | blobentryid INTEGER, |
| 914 | tag INTEGER, |
| 915 | data ANY, |
| 916 | UNIQUE (blobentryid, tag));", |
| 917 | NO_PARAMS, |
| 918 | ) |
| 919 | .context("Failed to initialize \"blobmetadata\" table.")?; |
| 920 | |
| 921 | tx.execute( |
| 922 | "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index |
| 923 | ON blobmetadata(blobentryid);", |
| 924 | NO_PARAMS, |
| 925 | ) |
| 926 | .context("Failed to create index blobmetadata_blobentryid_index.")?; |
| 927 | |
| 928 | tx.execute( |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 929 | "CREATE TABLE IF NOT EXISTS persistent.keyparameter ( |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 930 | keyentryid INTEGER, |
| 931 | tag INTEGER, |
| 932 | data ANY, |
| 933 | security_level INTEGER);", |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 934 | NO_PARAMS, |
| 935 | ) |
| 936 | .context("Failed to initialize \"keyparameter\" table.")?; |
| 937 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 938 | tx.execute( |
Janis Danisevskis | a543818 | 2021-02-02 14:22:59 -0800 | [diff] [blame] | 939 | "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index |
| 940 | ON keyparameter(keyentryid);", |
| 941 | NO_PARAMS, |
| 942 | ) |
| 943 | .context("Failed to create index keyparameter_keyentryid_index.")?; |
| 944 | |
| 945 | tx.execute( |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 946 | "CREATE TABLE IF NOT EXISTS persistent.keymetadata ( |
| 947 | keyentryid INTEGER, |
| 948 | tag INTEGER, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 949 | data ANY, |
| 950 | UNIQUE (keyentryid, tag));", |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 951 | NO_PARAMS, |
| 952 | ) |
| 953 | .context("Failed to initialize \"keymetadata\" table.")?; |
| 954 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 955 | tx.execute( |
Janis Danisevskis | a543818 | 2021-02-02 14:22:59 -0800 | [diff] [blame] | 956 | "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index |
| 957 | ON keymetadata(keyentryid);", |
| 958 | NO_PARAMS, |
| 959 | ) |
| 960 | .context("Failed to create index keymetadata_keyentryid_index.")?; |
| 961 | |
| 962 | tx.execute( |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 963 | "CREATE TABLE IF NOT EXISTS persistent.grant ( |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 964 | id INTEGER UNIQUE, |
| 965 | grantee INTEGER, |
| 966 | keyentryid INTEGER, |
| 967 | access_vector INTEGER);", |
| 968 | NO_PARAMS, |
| 969 | ) |
| 970 | .context("Failed to initialize \"grant\" table.")?; |
| 971 | |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 972 | //TODO: only drop the following two perboot tables if this is the first start up |
| 973 | //during the boot (b/175716626). |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 974 | // tx.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS) |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 975 | // .context("Failed to drop perboot.authtoken table")?; |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 976 | tx.execute( |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 977 | "CREATE TABLE IF NOT EXISTS perboot.authtoken ( |
| 978 | id INTEGER PRIMARY KEY, |
| 979 | challenge INTEGER, |
| 980 | user_id INTEGER, |
| 981 | auth_id INTEGER, |
| 982 | authenticator_type INTEGER, |
| 983 | timestamp INTEGER, |
| 984 | mac BLOB, |
| 985 | time_received INTEGER, |
| 986 | UNIQUE(user_id, auth_id, authenticator_type));", |
| 987 | NO_PARAMS, |
| 988 | ) |
| 989 | .context("Failed to initialize \"authtoken\" table.")?; |
| 990 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 991 | // tx.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS) |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 992 | // .context("Failed to drop perboot.metadata table")?; |
| 993 | // metadata table stores certain miscellaneous information required for keystore functioning |
| 994 | // during a boot cycle, as key-value pairs. |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 995 | tx.execute( |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 996 | "CREATE TABLE IF NOT EXISTS perboot.metadata ( |
| 997 | key TEXT, |
| 998 | value BLOB, |
| 999 | UNIQUE(key));", |
| 1000 | NO_PARAMS, |
| 1001 | ) |
| 1002 | .context("Failed to initialize \"metadata\" table.")?; |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 1003 | Ok(()) |
| 1004 | } |
| 1005 | |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 1006 | fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> { |
| 1007 | let conn = |
| 1008 | Connection::open_in_memory().context("Failed to initialize SQLite connection.")?; |
| 1009 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1010 | loop { |
| 1011 | if let Err(e) = conn |
| 1012 | .execute("ATTACH DATABASE ? as persistent;", params![persistent_file]) |
| 1013 | .context("Failed to attach database persistent.") |
| 1014 | { |
| 1015 | if Self::is_locked_error(&e) { |
| 1016 | std::thread::sleep(std::time::Duration::from_micros(500)); |
| 1017 | continue; |
| 1018 | } else { |
| 1019 | return Err(e); |
| 1020 | } |
| 1021 | } |
| 1022 | break; |
| 1023 | } |
| 1024 | loop { |
| 1025 | if let Err(e) = conn |
| 1026 | .execute("ATTACH DATABASE ? as perboot;", params![perboot_file]) |
| 1027 | .context("Failed to attach database perboot.") |
| 1028 | { |
| 1029 | if Self::is_locked_error(&e) { |
| 1030 | std::thread::sleep(std::time::Duration::from_micros(500)); |
| 1031 | continue; |
| 1032 | } else { |
| 1033 | return Err(e); |
| 1034 | } |
| 1035 | } |
| 1036 | break; |
| 1037 | } |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 1038 | |
| 1039 | Ok(conn) |
| 1040 | } |
| 1041 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1042 | /// This function is intended to be used by the garbage collector. |
| 1043 | /// It deletes the blob given by `blob_id_to_delete`. It then tries to find a superseded |
| 1044 | /// key blob that might need special handling by the garbage collector. |
| 1045 | /// If no further superseded blobs can be found it deletes all other superseded blobs that don't |
| 1046 | /// need special handling and returns None. |
| 1047 | pub fn handle_next_superseded_blob( |
| 1048 | &mut self, |
| 1049 | blob_id_to_delete: Option<i64>, |
| 1050 | ) -> Result<Option<(i64, Vec<u8>, BlobMetaData)>> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1051 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1052 | // Delete the given blob if one was given. |
| 1053 | if let Some(blob_id_to_delete) = blob_id_to_delete { |
| 1054 | tx.execute( |
| 1055 | "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;", |
| 1056 | params![blob_id_to_delete], |
| 1057 | ) |
| 1058 | .context("Trying to delete blob metadata.")?; |
| 1059 | tx.execute( |
| 1060 | "DELETE FROM persistent.blobentry WHERE id = ?;", |
| 1061 | params![blob_id_to_delete], |
| 1062 | ) |
| 1063 | .context("Trying to blob.")?; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1064 | } |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1065 | |
| 1066 | // Find another superseded keyblob load its metadata and return it. |
| 1067 | if let Some((blob_id, blob)) = tx |
| 1068 | .query_row( |
| 1069 | "SELECT id, blob FROM persistent.blobentry |
| 1070 | WHERE subcomponent_type = ? |
| 1071 | AND ( |
| 1072 | id NOT IN ( |
| 1073 | SELECT MAX(id) FROM persistent.blobentry |
| 1074 | WHERE subcomponent_type = ? |
| 1075 | GROUP BY keyentryid, subcomponent_type |
| 1076 | ) |
| 1077 | OR keyentryid NOT IN (SELECT id FROM persistent.keyentry) |
| 1078 | );", |
| 1079 | params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB], |
| 1080 | |row| Ok((row.get(0)?, row.get(1)?)), |
| 1081 | ) |
| 1082 | .optional() |
| 1083 | .context("Trying to query superseded blob.")? |
| 1084 | { |
| 1085 | let blob_metadata = BlobMetaData::load_from_db(blob_id, tx) |
| 1086 | .context("Trying to load blob metadata.")?; |
| 1087 | return Ok(Some((blob_id, blob, blob_metadata))).no_gc(); |
| 1088 | } |
| 1089 | |
| 1090 | // We did not find any superseded key blob, so let's remove other superseded blob in |
| 1091 | // one transaction. |
| 1092 | tx.execute( |
| 1093 | "DELETE FROM persistent.blobentry |
| 1094 | WHERE NOT subcomponent_type = ? |
| 1095 | AND ( |
| 1096 | id NOT IN ( |
| 1097 | SELECT MAX(id) FROM persistent.blobentry |
| 1098 | WHERE NOT subcomponent_type = ? |
| 1099 | GROUP BY keyentryid, subcomponent_type |
| 1100 | ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry) |
| 1101 | );", |
| 1102 | params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB], |
| 1103 | ) |
| 1104 | .context("Trying to purge superseded blobs.")?; |
| 1105 | |
| 1106 | Ok(None).no_gc() |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1107 | }) |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1108 | .context("In handle_next_superseded_blob.") |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1109 | } |
| 1110 | |
| 1111 | /// This maintenance function should be called only once before the database is used for the |
| 1112 | /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state. |
| 1113 | /// The function transitions all key entries from Existing to Unreferenced unconditionally and |
| 1114 | /// returns the number of rows affected. If this returns a value greater than 0, it means that |
| 1115 | /// Keystore crashed at some point during key generation. Callers may want to log such |
| 1116 | /// occurrences. |
| 1117 | /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made |
| 1118 | /// it to `KeyLifeCycle::Live` may have grants. |
| 1119 | pub fn cleanup_leftovers(&mut self) -> Result<usize> { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1120 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 1121 | tx.execute( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1122 | "UPDATE persistent.keyentry SET state = ? WHERE state = ?;", |
| 1123 | params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing], |
| 1124 | ) |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1125 | .context("Failed to execute query.") |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1126 | .need_gc() |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1127 | }) |
| 1128 | .context("In cleanup_leftovers.") |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1129 | } |
| 1130 | |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1131 | /// Checks if a key exists with given key type and key descriptor properties. |
| 1132 | pub fn key_exists( |
| 1133 | &mut self, |
| 1134 | domain: Domain, |
| 1135 | nspace: i64, |
| 1136 | alias: &str, |
| 1137 | key_type: KeyType, |
| 1138 | ) -> Result<bool> { |
| 1139 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 1140 | let key_descriptor = |
| 1141 | KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None }; |
| 1142 | let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type); |
| 1143 | match result { |
| 1144 | Ok(_) => Ok(true), |
| 1145 | Err(error) => match error.root_cause().downcast_ref::<KsError>() { |
| 1146 | Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false), |
| 1147 | _ => Err(error).context("In key_exists: Failed to find if the key exists."), |
| 1148 | }, |
| 1149 | } |
| 1150 | .no_gc() |
| 1151 | }) |
| 1152 | .context("In key_exists.") |
| 1153 | } |
| 1154 | |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1155 | /// Stores a super key in the database. |
| 1156 | pub fn store_super_key( |
| 1157 | &mut self, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 1158 | user_id: u32, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 1159 | key_type: &SuperKeyType, |
| 1160 | blob: &[u8], |
| 1161 | blob_metadata: &BlobMetaData, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 1162 | key_metadata: &KeyMetaData, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1163 | ) -> Result<KeyEntry> { |
| 1164 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 1165 | let key_id = Self::insert_with_retry(|id| { |
| 1166 | tx.execute( |
| 1167 | "INSERT into persistent.keyentry |
| 1168 | (id, key_type, domain, namespace, alias, state, km_uuid) |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 1169 | VALUES(?, ?, ?, ?, ?, ?, ?);", |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1170 | params![ |
| 1171 | id, |
| 1172 | KeyType::Super, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 1173 | Domain::APP.0, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 1174 | user_id as i64, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 1175 | key_type.alias, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1176 | KeyLifeCycle::Live, |
| 1177 | &KEYSTORE_UUID, |
| 1178 | ], |
| 1179 | ) |
| 1180 | }) |
| 1181 | .context("Failed to insert into keyentry table.")?; |
| 1182 | |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 1183 | key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?; |
| 1184 | |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1185 | Self::set_blob_internal( |
| 1186 | &tx, |
| 1187 | key_id, |
| 1188 | SubComponentType::KEY_BLOB, |
| 1189 | Some(blob), |
| 1190 | Some(blob_metadata), |
| 1191 | ) |
| 1192 | .context("Failed to store key blob.")?; |
| 1193 | |
| 1194 | Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id) |
| 1195 | .context("Trying to load key components.") |
| 1196 | .no_gc() |
| 1197 | }) |
| 1198 | .context("In store_super_key.") |
| 1199 | } |
| 1200 | |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 1201 | /// Loads super key of a given user, if exists |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 1202 | pub fn load_super_key( |
| 1203 | &mut self, |
| 1204 | key_type: &SuperKeyType, |
| 1205 | user_id: u32, |
| 1206 | ) -> Result<Option<(KeyIdGuard, KeyEntry)>> { |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 1207 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 1208 | let key_descriptor = KeyDescriptor { |
| 1209 | domain: Domain::APP, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 1210 | nspace: user_id as i64, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 1211 | alias: Some(key_type.alias.into()), |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 1212 | blob: None, |
| 1213 | }; |
| 1214 | let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super); |
| 1215 | match id { |
| 1216 | Ok(id) => { |
| 1217 | let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id) |
| 1218 | .context("In load_super_key. Failed to load key entry.")?; |
| 1219 | Ok(Some((KEY_ID_LOCK.get(id), key_entry))) |
| 1220 | } |
| 1221 | Err(error) => match error.root_cause().downcast_ref::<KsError>() { |
| 1222 | Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None), |
| 1223 | _ => Err(error).context("In load_super_key."), |
| 1224 | }, |
| 1225 | } |
| 1226 | .no_gc() |
| 1227 | }) |
| 1228 | .context("In load_super_key.") |
| 1229 | } |
| 1230 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1231 | /// Atomically loads a key entry and associated metadata or creates it using the |
| 1232 | /// callback create_new_key callback. The callback is called during a database |
| 1233 | /// transaction. This means that implementers should be mindful about using |
| 1234 | /// blocking operations such as IPC or grabbing mutexes. |
| 1235 | pub fn get_or_create_key_with<F>( |
| 1236 | &mut self, |
| 1237 | domain: Domain, |
| 1238 | namespace: i64, |
| 1239 | alias: &str, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1240 | km_uuid: Uuid, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1241 | create_new_key: F, |
| 1242 | ) -> Result<(KeyIdGuard, KeyEntry)> |
| 1243 | where |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1244 | F: Fn() -> Result<(Vec<u8>, BlobMetaData)>, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1245 | { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1246 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 1247 | let id = { |
| 1248 | let mut stmt = tx |
| 1249 | .prepare( |
| 1250 | "SELECT id FROM persistent.keyentry |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1251 | WHERE |
| 1252 | key_type = ? |
| 1253 | AND domain = ? |
| 1254 | AND namespace = ? |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1255 | AND alias = ? |
| 1256 | AND state = ?;", |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1257 | ) |
| 1258 | .context("In get_or_create_key_with: Failed to select from keyentry table.")?; |
| 1259 | let mut rows = stmt |
| 1260 | .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live]) |
| 1261 | .context("In get_or_create_key_with: Failed to query from keyentry table.")?; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1262 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1263 | db_utils::with_rows_extract_one(&mut rows, |row| { |
| 1264 | Ok(match row { |
| 1265 | Some(r) => r.get(0).context("Failed to unpack id.")?, |
| 1266 | None => None, |
| 1267 | }) |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1268 | }) |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1269 | .context("In get_or_create_key_with.")? |
| 1270 | }; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1271 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1272 | let (id, entry) = match id { |
| 1273 | Some(id) => ( |
| 1274 | id, |
| 1275 | Self::load_key_components(&tx, KeyEntryLoadBits::KM, id) |
| 1276 | .context("In get_or_create_key_with.")?, |
| 1277 | ), |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1278 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1279 | None => { |
| 1280 | let id = Self::insert_with_retry(|id| { |
| 1281 | tx.execute( |
| 1282 | "INSERT into persistent.keyentry |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1283 | (id, key_type, domain, namespace, alias, state, km_uuid) |
| 1284 | VALUES(?, ?, ?, ?, ?, ?, ?);", |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1285 | params![ |
| 1286 | id, |
| 1287 | KeyType::Super, |
| 1288 | domain.0, |
| 1289 | namespace, |
| 1290 | alias, |
| 1291 | KeyLifeCycle::Live, |
| 1292 | km_uuid, |
| 1293 | ], |
| 1294 | ) |
| 1295 | }) |
| 1296 | .context("In get_or_create_key_with.")?; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1297 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1298 | let (blob, metadata) = |
| 1299 | create_new_key().context("In get_or_create_key_with.")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1300 | Self::set_blob_internal( |
| 1301 | &tx, |
| 1302 | id, |
| 1303 | SubComponentType::KEY_BLOB, |
| 1304 | Some(&blob), |
| 1305 | Some(&metadata), |
| 1306 | ) |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 1307 | .context("In get_or_create_key_with.")?; |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1308 | ( |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1309 | id, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1310 | KeyEntry { |
| 1311 | id, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1312 | key_blob_info: Some((blob, metadata)), |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1313 | pure_cert: false, |
| 1314 | ..Default::default() |
| 1315 | }, |
| 1316 | ) |
| 1317 | } |
| 1318 | }; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1319 | Ok((KEY_ID_LOCK.get(id), entry)).no_gc() |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1320 | }) |
| 1321 | .context("In get_or_create_key_with.") |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1322 | } |
| 1323 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1324 | /// SQLite3 seems to hold a shared mutex while running the busy handler when |
| 1325 | /// waiting for the database file to become available. This makes it |
| 1326 | /// impossible to successfully recover from a locked database when the |
| 1327 | /// transaction holding the device busy is in the same process on a |
| 1328 | /// different connection. As a result the busy handler has to time out and |
| 1329 | /// fail in order to make progress. |
| 1330 | /// |
| 1331 | /// Instead, we set the busy handler to None (return immediately). And catch |
| 1332 | /// Busy and Locked errors (the latter occur on in memory databases with |
| 1333 | /// shared cache, e.g., the per-boot database.) and restart the transaction |
| 1334 | /// after a grace period of half a millisecond. |
| 1335 | /// |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1336 | /// Creates a transaction with the given behavior and executes f with the new transaction. |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1337 | /// The transaction is committed only if f returns Ok and retried if DatabaseBusy |
| 1338 | /// or DatabaseLocked is encountered. |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1339 | fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T> |
| 1340 | where |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1341 | F: Fn(&Transaction) -> Result<(bool, T)>, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1342 | { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1343 | loop { |
| 1344 | match self |
| 1345 | .conn |
| 1346 | .transaction_with_behavior(behavior) |
| 1347 | .context("In with_transaction.") |
| 1348 | .and_then(|tx| f(&tx).map(|result| (result, tx))) |
| 1349 | .and_then(|(result, tx)| { |
| 1350 | tx.commit().context("In with_transaction: Failed to commit transaction.")?; |
| 1351 | Ok(result) |
| 1352 | }) { |
| 1353 | Ok(result) => break Ok(result), |
| 1354 | Err(e) => { |
| 1355 | if Self::is_locked_error(&e) { |
| 1356 | std::thread::sleep(std::time::Duration::from_micros(500)); |
| 1357 | continue; |
| 1358 | } else { |
| 1359 | return Err(e).context("In with_transaction."); |
| 1360 | } |
| 1361 | } |
| 1362 | } |
| 1363 | } |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1364 | .map(|(need_gc, result)| { |
| 1365 | if need_gc { |
| 1366 | if let Some(ref gc) = self.gc { |
| 1367 | gc.notify_gc(); |
| 1368 | } |
| 1369 | } |
| 1370 | result |
| 1371 | }) |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1372 | } |
| 1373 | |
| 1374 | fn is_locked_error(e: &anyhow::Error) -> bool { |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 1375 | matches!( |
| 1376 | e.root_cause().downcast_ref::<rusqlite::ffi::Error>(), |
| 1377 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) |
| 1378 | | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. }) |
| 1379 | ) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1380 | } |
| 1381 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1382 | /// Creates a new key entry and allocates a new randomized id for the new key. |
| 1383 | /// The key id gets associated with a domain and namespace but not with an alias. |
| 1384 | /// To complete key generation `rebind_alias` should be called after all of the |
| 1385 | /// key artifacts, i.e., blobs and parameters have been associated with the new |
| 1386 | /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry |
| 1387 | /// atomic even if key generation is not. |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1388 | pub fn create_key_entry( |
| 1389 | &mut self, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1390 | domain: &Domain, |
| 1391 | namespace: &i64, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1392 | km_uuid: &Uuid, |
| 1393 | ) -> Result<KeyIdGuard> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1394 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1395 | Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc() |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1396 | }) |
| 1397 | .context("In create_key_entry.") |
| 1398 | } |
| 1399 | |
| 1400 | fn create_key_entry_internal( |
| 1401 | tx: &Transaction, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1402 | domain: &Domain, |
| 1403 | namespace: &i64, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1404 | km_uuid: &Uuid, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1405 | ) -> Result<KeyIdGuard> { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1406 | match *domain { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1407 | Domain::APP | Domain::SELINUX => {} |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 1408 | _ => { |
| 1409 | return Err(KsError::sys()) |
| 1410 | .context(format!("Domain {:?} must be either App or SELinux.", domain)); |
| 1411 | } |
| 1412 | } |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1413 | Ok(KEY_ID_LOCK.get( |
| 1414 | Self::insert_with_retry(|id| { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1415 | tx.execute( |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1416 | "INSERT into persistent.keyentry |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1417 | (id, key_type, domain, namespace, alias, state, km_uuid) |
| 1418 | VALUES(?, ?, ?, ?, NULL, ?, ?);", |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1419 | params![ |
| 1420 | id, |
| 1421 | KeyType::Client, |
| 1422 | domain.0 as u32, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1423 | *namespace, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1424 | KeyLifeCycle::Existing, |
| 1425 | km_uuid, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1426 | ], |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1427 | ) |
| 1428 | }) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1429 | .context("In create_key_entry_internal")?, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1430 | )) |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 1431 | } |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1432 | |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 1433 | /// Creates a new attestation key entry and allocates a new randomized id for the new key. |
| 1434 | /// The key id gets associated with a domain and namespace later but not with an alias. The |
| 1435 | /// alias will be used to denote if a key has been signed as each key can only be bound to one |
| 1436 | /// domain and namespace pairing so there is no need to use them as a value for indexing into |
| 1437 | /// a key. |
| 1438 | pub fn create_attestation_key_entry( |
| 1439 | &mut self, |
| 1440 | maced_public_key: &[u8], |
| 1441 | raw_public_key: &[u8], |
| 1442 | private_key: &[u8], |
| 1443 | km_uuid: &Uuid, |
| 1444 | ) -> Result<()> { |
| 1445 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 1446 | let key_id = KEY_ID_LOCK.get( |
| 1447 | Self::insert_with_retry(|id| { |
| 1448 | tx.execute( |
| 1449 | "INSERT into persistent.keyentry |
| 1450 | (id, key_type, domain, namespace, alias, state, km_uuid) |
| 1451 | VALUES(?, ?, NULL, NULL, NULL, ?, ?);", |
| 1452 | params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid], |
| 1453 | ) |
| 1454 | }) |
| 1455 | .context("In create_key_entry")?, |
| 1456 | ); |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1457 | Self::set_blob_internal( |
| 1458 | &tx, |
| 1459 | key_id.0, |
| 1460 | SubComponentType::KEY_BLOB, |
| 1461 | Some(private_key), |
| 1462 | None, |
| 1463 | )?; |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 1464 | let mut metadata = KeyMetaData::new(); |
| 1465 | metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec())); |
| 1466 | metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec())); |
| 1467 | metadata.store_in_db(key_id.0, &tx)?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1468 | Ok(()).no_gc() |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 1469 | }) |
| 1470 | .context("In create_attestation_key_entry") |
| 1471 | } |
| 1472 | |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1473 | /// Set a new blob and associates it with the given key id. Each blob |
| 1474 | /// has a sub component type. |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1475 | /// Each key can have one of each sub component type associated. If more |
| 1476 | /// are added only the most recent can be retrieved, and superseded blobs |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1477 | /// will get garbage collected. |
| 1478 | /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be |
| 1479 | /// removed by setting blob to None. |
| 1480 | pub fn set_blob( |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1481 | &mut self, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1482 | key_id: &KeyIdGuard, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1483 | sc_type: SubComponentType, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1484 | blob: Option<&[u8]>, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1485 | blob_metadata: Option<&BlobMetaData>, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1486 | ) -> Result<()> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1487 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1488 | Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc() |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1489 | }) |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1490 | .context("In set_blob.") |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1491 | } |
| 1492 | |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 1493 | /// Why would we insert a deleted blob? This weird function is for the purpose of legacy |
| 1494 | /// key migration in the case where we bulk delete all the keys of an app or even a user. |
| 1495 | /// We use this to insert key blobs into the database which can then be garbage collected |
| 1496 | /// lazily by the key garbage collector. |
| 1497 | pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> { |
| 1498 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 1499 | Self::set_blob_internal( |
| 1500 | &tx, |
| 1501 | Self::UNASSIGNED_KEY_ID, |
| 1502 | SubComponentType::KEY_BLOB, |
| 1503 | Some(blob), |
| 1504 | Some(blob_metadata), |
| 1505 | ) |
| 1506 | .need_gc() |
| 1507 | }) |
| 1508 | .context("In set_deleted_blob.") |
| 1509 | } |
| 1510 | |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1511 | fn set_blob_internal( |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1512 | tx: &Transaction, |
| 1513 | key_id: i64, |
| 1514 | sc_type: SubComponentType, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1515 | blob: Option<&[u8]>, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1516 | blob_metadata: Option<&BlobMetaData>, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1517 | ) -> Result<()> { |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1518 | match (blob, sc_type) { |
| 1519 | (Some(blob), _) => { |
| 1520 | tx.execute( |
| 1521 | "INSERT INTO persistent.blobentry |
| 1522 | (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);", |
| 1523 | params![sc_type, key_id, blob], |
| 1524 | ) |
| 1525 | .context("In set_blob_internal: Failed to insert blob.")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1526 | if let Some(blob_metadata) = blob_metadata { |
| 1527 | let blob_id = tx |
| 1528 | .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| { |
| 1529 | row.get(0) |
| 1530 | }) |
| 1531 | .context("In set_blob_internal: Failed to get new blob id.")?; |
| 1532 | blob_metadata |
| 1533 | .store_in_db(blob_id, tx) |
| 1534 | .context("In set_blob_internal: Trying to store blob metadata.")?; |
| 1535 | } |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1536 | } |
| 1537 | (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => { |
| 1538 | tx.execute( |
| 1539 | "DELETE FROM persistent.blobentry |
| 1540 | WHERE subcomponent_type = ? AND keyentryid = ?;", |
| 1541 | params![sc_type, key_id], |
| 1542 | ) |
| 1543 | .context("In set_blob_internal: Failed to delete blob.")?; |
| 1544 | } |
| 1545 | (None, _) => { |
| 1546 | return Err(KsError::sys()) |
| 1547 | .context("In set_blob_internal: Other blobs cannot be deleted in this way."); |
| 1548 | } |
| 1549 | } |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1550 | Ok(()) |
| 1551 | } |
| 1552 | |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1553 | /// Inserts a collection of key parameters into the `persistent.keyparameter` table |
| 1554 | /// and associates them with the given `key_id`. |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1555 | #[cfg(test)] |
| 1556 | fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1557 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1558 | Self::insert_keyparameter_internal(tx, key_id, params).no_gc() |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1559 | }) |
| 1560 | .context("In insert_keyparameter.") |
| 1561 | } |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1562 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1563 | fn insert_keyparameter_internal( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1564 | tx: &Transaction, |
| 1565 | key_id: &KeyIdGuard, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1566 | params: &[KeyParameter], |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1567 | ) -> Result<()> { |
| 1568 | let mut stmt = tx |
| 1569 | .prepare( |
| 1570 | "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level) |
| 1571 | VALUES (?, ?, ?, ?);", |
| 1572 | ) |
| 1573 | .context("In insert_keyparameter_internal: Failed to prepare statement.")?; |
| 1574 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1575 | for p in params.iter() { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1576 | stmt.insert(params![ |
| 1577 | key_id.0, |
| 1578 | p.get_tag().0, |
| 1579 | p.key_parameter_value(), |
| 1580 | p.security_level().0 |
| 1581 | ]) |
| 1582 | .with_context(|| { |
| 1583 | format!("In insert_keyparameter_internal: Failed to insert {:?}", p) |
| 1584 | })?; |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1585 | } |
| 1586 | Ok(()) |
| 1587 | } |
| 1588 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1589 | /// Insert a set of key entry specific metadata into the database. |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1590 | #[cfg(test)] |
| 1591 | fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1592 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1593 | metadata.store_in_db(key_id.0, &tx).no_gc() |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1594 | }) |
| 1595 | .context("In insert_key_metadata.") |
| 1596 | } |
| 1597 | |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 1598 | /// Stores a signed certificate chain signed by a remote provisioning server, keyed |
| 1599 | /// on the public key. |
| 1600 | pub fn store_signed_attestation_certificate_chain( |
| 1601 | &mut self, |
| 1602 | raw_public_key: &[u8], |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 1603 | batch_cert: &[u8], |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 1604 | cert_chain: &[u8], |
| 1605 | expiration_date: i64, |
| 1606 | km_uuid: &Uuid, |
| 1607 | ) -> Result<()> { |
| 1608 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 1609 | let mut stmt = tx |
| 1610 | .prepare( |
| 1611 | "SELECT keyentryid |
| 1612 | FROM persistent.keymetadata |
| 1613 | WHERE tag = ? AND data = ? AND keyentryid IN |
| 1614 | (SELECT id |
| 1615 | FROM persistent.keyentry |
| 1616 | WHERE |
| 1617 | alias IS NULL AND |
| 1618 | domain IS NULL AND |
| 1619 | namespace IS NULL AND |
| 1620 | key_type = ? AND |
| 1621 | km_uuid = ?);", |
| 1622 | ) |
| 1623 | .context("Failed to store attestation certificate chain.")?; |
| 1624 | let mut rows = stmt |
| 1625 | .query(params![ |
| 1626 | KeyMetaData::AttestationRawPubKey, |
| 1627 | raw_public_key, |
| 1628 | KeyType::Attestation, |
| 1629 | km_uuid |
| 1630 | ]) |
| 1631 | .context("Failed to fetch keyid")?; |
| 1632 | let key_id = db_utils::with_rows_extract_one(&mut rows, |row| { |
| 1633 | row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)? |
| 1634 | .get(0) |
| 1635 | .context("Failed to unpack id.") |
| 1636 | }) |
| 1637 | .context("Failed to get key_id.")?; |
| 1638 | let num_updated = tx |
| 1639 | .execute( |
| 1640 | "UPDATE persistent.keyentry |
| 1641 | SET alias = ? |
| 1642 | WHERE id = ?;", |
| 1643 | params!["signed", key_id], |
| 1644 | ) |
| 1645 | .context("Failed to update alias.")?; |
| 1646 | if num_updated != 1 { |
| 1647 | return Err(KsError::sys()).context("Alias not updated for the key."); |
| 1648 | } |
| 1649 | let mut metadata = KeyMetaData::new(); |
| 1650 | metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch( |
| 1651 | expiration_date, |
| 1652 | ))); |
| 1653 | metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1654 | Self::set_blob_internal( |
| 1655 | &tx, |
| 1656 | key_id, |
| 1657 | SubComponentType::CERT_CHAIN, |
| 1658 | Some(cert_chain), |
| 1659 | None, |
| 1660 | ) |
| 1661 | .context("Failed to insert cert chain")?; |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 1662 | Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None) |
| 1663 | .context("Failed to insert cert")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1664 | Ok(()).no_gc() |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 1665 | }) |
| 1666 | .context("In store_signed_attestation_certificate_chain: ") |
| 1667 | } |
| 1668 | |
| 1669 | /// Assigns the next unassigned attestation key to a domain/namespace combo that does not |
| 1670 | /// currently have a key assigned to it. |
| 1671 | pub fn assign_attestation_key( |
| 1672 | &mut self, |
| 1673 | domain: Domain, |
| 1674 | namespace: i64, |
| 1675 | km_uuid: &Uuid, |
| 1676 | ) -> Result<()> { |
| 1677 | match domain { |
| 1678 | Domain::APP | Domain::SELINUX => {} |
| 1679 | _ => { |
| 1680 | return Err(KsError::sys()).context(format!( |
| 1681 | concat!( |
| 1682 | "In assign_attestation_key: Domain {:?} ", |
| 1683 | "must be either App or SELinux.", |
| 1684 | ), |
| 1685 | domain |
| 1686 | )); |
| 1687 | } |
| 1688 | } |
| 1689 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 1690 | let result = tx |
| 1691 | .execute( |
| 1692 | "UPDATE persistent.keyentry |
| 1693 | SET domain=?1, namespace=?2 |
| 1694 | WHERE |
| 1695 | id = |
| 1696 | (SELECT MIN(id) |
| 1697 | FROM persistent.keyentry |
| 1698 | WHERE ALIAS IS NOT NULL |
| 1699 | AND domain IS NULL |
| 1700 | AND key_type IS ?3 |
| 1701 | AND state IS ?4 |
| 1702 | AND km_uuid IS ?5) |
| 1703 | AND |
| 1704 | (SELECT COUNT(*) |
| 1705 | FROM persistent.keyentry |
| 1706 | WHERE domain=?1 |
| 1707 | AND namespace=?2 |
| 1708 | AND key_type IS ?3 |
| 1709 | AND state IS ?4 |
| 1710 | AND km_uuid IS ?5) = 0;", |
| 1711 | params![ |
| 1712 | domain.0 as u32, |
| 1713 | namespace, |
| 1714 | KeyType::Attestation, |
| 1715 | KeyLifeCycle::Live, |
| 1716 | km_uuid, |
| 1717 | ], |
| 1718 | ) |
| 1719 | .context("Failed to assign attestation key")?; |
Max Bires | 01f8af2 | 2021-03-02 23:24:50 -0800 | [diff] [blame] | 1720 | if result == 0 { |
| 1721 | return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys."); |
| 1722 | } else if result > 1 { |
| 1723 | return Err(KsError::sys()) |
| 1724 | .context(format!("Expected to update 1 entry, instead updated {}", result)); |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 1725 | } |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1726 | Ok(()).no_gc() |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 1727 | }) |
| 1728 | .context("In assign_attestation_key: ") |
| 1729 | } |
| 1730 | |
| 1731 | /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote |
| 1732 | /// provisioning server, or the maximum number available if there are not num_keys number of |
| 1733 | /// entries in the table. |
| 1734 | pub fn fetch_unsigned_attestation_keys( |
| 1735 | &mut self, |
| 1736 | num_keys: i32, |
| 1737 | km_uuid: &Uuid, |
| 1738 | ) -> Result<Vec<Vec<u8>>> { |
| 1739 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 1740 | let mut stmt = tx |
| 1741 | .prepare( |
| 1742 | "SELECT data |
| 1743 | FROM persistent.keymetadata |
| 1744 | WHERE tag = ? AND keyentryid IN |
| 1745 | (SELECT id |
| 1746 | FROM persistent.keyentry |
| 1747 | WHERE |
| 1748 | alias IS NULL AND |
| 1749 | domain IS NULL AND |
| 1750 | namespace IS NULL AND |
| 1751 | key_type = ? AND |
| 1752 | km_uuid = ? |
| 1753 | LIMIT ?);", |
| 1754 | ) |
| 1755 | .context("Failed to prepare statement")?; |
| 1756 | let rows = stmt |
| 1757 | .query_map( |
| 1758 | params![ |
| 1759 | KeyMetaData::AttestationMacedPublicKey, |
| 1760 | KeyType::Attestation, |
| 1761 | km_uuid, |
| 1762 | num_keys |
| 1763 | ], |
| 1764 | |row| Ok(row.get(0)?), |
| 1765 | )? |
| 1766 | .collect::<rusqlite::Result<Vec<Vec<u8>>>>() |
| 1767 | .context("Failed to execute statement")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1768 | Ok(rows).no_gc() |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 1769 | }) |
| 1770 | .context("In fetch_unsigned_attestation_keys") |
| 1771 | } |
| 1772 | |
| 1773 | /// Removes any keys that have expired as of the current time. Returns the number of keys |
| 1774 | /// marked unreferenced that are bound to be garbage collected. |
| 1775 | pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> { |
| 1776 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 1777 | let mut stmt = tx |
| 1778 | .prepare( |
| 1779 | "SELECT keyentryid, data |
| 1780 | FROM persistent.keymetadata |
| 1781 | WHERE tag = ? AND keyentryid IN |
| 1782 | (SELECT id |
| 1783 | FROM persistent.keyentry |
| 1784 | WHERE key_type = ?);", |
| 1785 | ) |
| 1786 | .context("Failed to prepare query")?; |
| 1787 | let key_ids_to_check = stmt |
| 1788 | .query_map( |
| 1789 | params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation], |
| 1790 | |row| Ok((row.get(0)?, row.get(1)?)), |
| 1791 | )? |
| 1792 | .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>() |
| 1793 | .context("Failed to get date metadata")?; |
| 1794 | let curr_time = DateTime::from_millis_epoch( |
| 1795 | SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64, |
| 1796 | ); |
| 1797 | let mut num_deleted = 0; |
| 1798 | for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) { |
| 1799 | if Self::mark_unreferenced(&tx, id)? { |
| 1800 | num_deleted += 1; |
| 1801 | } |
| 1802 | } |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1803 | Ok(num_deleted).do_gc(num_deleted != 0) |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 1804 | }) |
| 1805 | .context("In delete_expired_attestation_keys: ") |
| 1806 | } |
| 1807 | |
Max Bires | 60d7ed1 | 2021-03-05 15:59:22 -0800 | [diff] [blame] | 1808 | /// Deletes all remotely provisioned attestation keys in the system, regardless of the state |
| 1809 | /// they are in. This is useful primarily as a testing mechanism. |
| 1810 | pub fn delete_all_attestation_keys(&mut self) -> Result<i64> { |
| 1811 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 1812 | let mut stmt = tx |
| 1813 | .prepare( |
| 1814 | "SELECT id FROM persistent.keyentry |
| 1815 | WHERE key_type IS ?;", |
| 1816 | ) |
| 1817 | .context("Failed to prepare statement")?; |
| 1818 | let keys_to_delete = stmt |
| 1819 | .query_map(params![KeyType::Attestation], |row| Ok(row.get(0)?))? |
| 1820 | .collect::<rusqlite::Result<Vec<i64>>>() |
| 1821 | .context("Failed to execute statement")?; |
| 1822 | let num_deleted = keys_to_delete |
| 1823 | .iter() |
| 1824 | .map(|id| Self::mark_unreferenced(&tx, *id)) |
| 1825 | .collect::<Result<Vec<bool>>>() |
| 1826 | .context("Failed to execute mark_unreferenced on a keyid")? |
| 1827 | .into_iter() |
| 1828 | .filter(|result| *result) |
| 1829 | .count() as i64; |
| 1830 | Ok(num_deleted).do_gc(num_deleted != 0) |
| 1831 | }) |
| 1832 | .context("In delete_all_attestation_keys: ") |
| 1833 | } |
| 1834 | |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 1835 | /// Counts the number of keys that will expire by the provided epoch date and the number of |
| 1836 | /// keys not currently assigned to a domain. |
| 1837 | pub fn get_attestation_pool_status( |
| 1838 | &mut self, |
| 1839 | date: i64, |
| 1840 | km_uuid: &Uuid, |
| 1841 | ) -> Result<AttestationPoolStatus> { |
| 1842 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 1843 | let mut stmt = tx.prepare( |
| 1844 | "SELECT data |
| 1845 | FROM persistent.keymetadata |
| 1846 | WHERE tag = ? AND keyentryid IN |
| 1847 | (SELECT id |
| 1848 | FROM persistent.keyentry |
| 1849 | WHERE alias IS NOT NULL |
| 1850 | AND key_type = ? |
| 1851 | AND km_uuid = ? |
| 1852 | AND state = ?);", |
| 1853 | )?; |
| 1854 | let times = stmt |
| 1855 | .query_map( |
| 1856 | params![ |
| 1857 | KeyMetaData::AttestationExpirationDate, |
| 1858 | KeyType::Attestation, |
| 1859 | km_uuid, |
| 1860 | KeyLifeCycle::Live |
| 1861 | ], |
| 1862 | |row| Ok(row.get(0)?), |
| 1863 | )? |
| 1864 | .collect::<rusqlite::Result<Vec<DateTime>>>() |
| 1865 | .context("Failed to execute metadata statement")?; |
| 1866 | let expiring = |
| 1867 | times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count() |
| 1868 | as i32; |
| 1869 | stmt = tx.prepare( |
| 1870 | "SELECT alias, domain |
| 1871 | FROM persistent.keyentry |
| 1872 | WHERE key_type = ? AND km_uuid = ? AND state = ?;", |
| 1873 | )?; |
| 1874 | let rows = stmt |
| 1875 | .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| { |
| 1876 | Ok((row.get(0)?, row.get(1)?)) |
| 1877 | })? |
| 1878 | .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>() |
| 1879 | .context("Failed to execute keyentry statement")?; |
| 1880 | let mut unassigned = 0i32; |
| 1881 | let mut attested = 0i32; |
| 1882 | let total = rows.len() as i32; |
| 1883 | for (alias, domain) in rows { |
| 1884 | match (alias, domain) { |
| 1885 | (Some(_alias), None) => { |
| 1886 | attested += 1; |
| 1887 | unassigned += 1; |
| 1888 | } |
| 1889 | (Some(_alias), Some(_domain)) => { |
| 1890 | attested += 1; |
| 1891 | } |
| 1892 | _ => {} |
| 1893 | } |
| 1894 | } |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1895 | Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc() |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 1896 | }) |
| 1897 | .context("In get_attestation_pool_status: ") |
| 1898 | } |
| 1899 | |
| 1900 | /// Fetches the private key and corresponding certificate chain assigned to a |
| 1901 | /// domain/namespace pair. Will either return nothing if the domain/namespace is |
| 1902 | /// not assigned, or one CertificateChain. |
| 1903 | pub fn retrieve_attestation_key_and_cert_chain( |
| 1904 | &mut self, |
| 1905 | domain: Domain, |
| 1906 | namespace: i64, |
| 1907 | km_uuid: &Uuid, |
| 1908 | ) -> Result<Option<CertificateChain>> { |
| 1909 | match domain { |
| 1910 | Domain::APP | Domain::SELINUX => {} |
| 1911 | _ => { |
| 1912 | return Err(KsError::sys()) |
| 1913 | .context(format!("Domain {:?} must be either App or SELinux.", domain)); |
| 1914 | } |
| 1915 | } |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1916 | self.with_transaction(TransactionBehavior::Deferred, |tx| { |
| 1917 | let mut stmt = tx.prepare( |
| 1918 | "SELECT subcomponent_type, blob |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 1919 | FROM persistent.blobentry |
| 1920 | WHERE keyentryid IN |
| 1921 | (SELECT id |
| 1922 | FROM persistent.keyentry |
| 1923 | WHERE key_type = ? |
| 1924 | AND domain = ? |
| 1925 | AND namespace = ? |
| 1926 | AND state = ? |
| 1927 | AND km_uuid = ?);", |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1928 | )?; |
| 1929 | let rows = stmt |
| 1930 | .query_map( |
| 1931 | params![ |
| 1932 | KeyType::Attestation, |
| 1933 | domain.0 as u32, |
| 1934 | namespace, |
| 1935 | KeyLifeCycle::Live, |
| 1936 | km_uuid |
| 1937 | ], |
| 1938 | |row| Ok((row.get(0)?, row.get(1)?)), |
| 1939 | )? |
| 1940 | .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>() |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 1941 | .context("query failed.")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1942 | if rows.is_empty() { |
| 1943 | return Ok(None).no_gc(); |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 1944 | } else if rows.len() != 3 { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1945 | return Err(KsError::sys()).context(format!( |
| 1946 | concat!( |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 1947 | "Expected to get a single attestation", |
| 1948 | "key, cert, and cert chain for a total of 3 entries, but instead got {}." |
| 1949 | ), |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1950 | rows.len() |
| 1951 | )); |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 1952 | } |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1953 | let mut km_blob: Vec<u8> = Vec::new(); |
| 1954 | let mut cert_chain_blob: Vec<u8> = Vec::new(); |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 1955 | let mut batch_cert_blob: Vec<u8> = Vec::new(); |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1956 | for row in rows { |
| 1957 | let sub_type: SubComponentType = row.0; |
| 1958 | match sub_type { |
| 1959 | SubComponentType::KEY_BLOB => { |
| 1960 | km_blob = row.1; |
| 1961 | } |
| 1962 | SubComponentType::CERT_CHAIN => { |
| 1963 | cert_chain_blob = row.1; |
| 1964 | } |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 1965 | SubComponentType::CERT => { |
| 1966 | batch_cert_blob = row.1; |
| 1967 | } |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1968 | _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?, |
| 1969 | } |
| 1970 | } |
| 1971 | Ok(Some(CertificateChain { |
| 1972 | private_key: ZVec::try_from(km_blob)?, |
Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 1973 | batch_cert: batch_cert_blob, |
| 1974 | cert_chain: cert_chain_blob, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1975 | })) |
| 1976 | .no_gc() |
| 1977 | }) |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 1978 | .context("In retrieve_attestation_key_and_cert_chain:") |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 1979 | } |
| 1980 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1981 | /// Updates the alias column of the given key id `newid` with the given alias, |
| 1982 | /// and atomically, removes the alias, domain, and namespace from another row |
| 1983 | /// with the same alias-domain-namespace tuple if such row exits. |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1984 | /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage |
| 1985 | /// collector. |
| 1986 | fn rebind_alias( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1987 | tx: &Transaction, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1988 | newid: &KeyIdGuard, |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1989 | alias: &str, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1990 | domain: &Domain, |
| 1991 | namespace: &i64, |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1992 | ) -> Result<bool> { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1993 | match *domain { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1994 | Domain::APP | Domain::SELINUX => {} |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1995 | _ => { |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1996 | return Err(KsError::sys()).context(format!( |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1997 | "In rebind_alias: Domain {:?} must be either App or SELinux.", |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1998 | domain |
| 1999 | )); |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2000 | } |
| 2001 | } |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2002 | let updated = tx |
| 2003 | .execute( |
| 2004 | "UPDATE persistent.keyentry |
| 2005 | SET alias = NULL, domain = NULL, namespace = NULL, state = ? |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2006 | WHERE alias = ? AND domain = ? AND namespace = ?;", |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2007 | params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace], |
| 2008 | ) |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2009 | .context("In rebind_alias: Failed to rebind existing entry.")?; |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2010 | let result = tx |
| 2011 | .execute( |
| 2012 | "UPDATE persistent.keyentry |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2013 | SET alias = ?, state = ? |
| 2014 | WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;", |
| 2015 | params![ |
| 2016 | alias, |
| 2017 | KeyLifeCycle::Live, |
| 2018 | newid.0, |
| 2019 | domain.0 as u32, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2020 | *namespace, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2021 | KeyLifeCycle::Existing, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2022 | ], |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2023 | ) |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2024 | .context("In rebind_alias: Failed to set alias.")?; |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2025 | if result != 1 { |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2026 | return Err(KsError::sys()).context(format!( |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2027 | "In rebind_alias: Expected to update a single entry but instead updated {}.", |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 2028 | result |
| 2029 | )); |
| 2030 | } |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2031 | Ok(updated != 0) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2032 | } |
| 2033 | |
| 2034 | /// Store a new key in a single transaction. |
| 2035 | /// The function creates a new key entry, populates the blob, key parameter, and metadata |
| 2036 | /// fields, and rebinds the given alias to the new key. |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2037 | /// The boolean returned is a hint for the garbage collector. If true, a key was replaced, |
| 2038 | /// is now unreferenced and needs to be collected. |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2039 | pub fn store_new_key( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2040 | &mut self, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2041 | key: &KeyDescriptor, |
| 2042 | params: &[KeyParameter], |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2043 | blob_info: &(&[u8], &BlobMetaData), |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2044 | cert_info: &CertificateInfo, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2045 | metadata: &KeyMetaData, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2046 | km_uuid: &Uuid, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2047 | ) -> Result<KeyIdGuard> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2048 | let (alias, domain, namespace) = match key { |
| 2049 | KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None } |
| 2050 | | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => { |
| 2051 | (alias, key.domain, nspace) |
| 2052 | } |
| 2053 | _ => { |
| 2054 | return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)) |
| 2055 | .context("In store_new_key: Need alias and domain must be APP or SELINUX.") |
| 2056 | } |
| 2057 | }; |
| 2058 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2059 | 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] | 2060 | .context("Trying to create new key entry.")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2061 | let (blob, blob_metadata) = *blob_info; |
| 2062 | Self::set_blob_internal( |
| 2063 | tx, |
| 2064 | key_id.id(), |
| 2065 | SubComponentType::KEY_BLOB, |
| 2066 | Some(blob), |
| 2067 | Some(&blob_metadata), |
| 2068 | ) |
| 2069 | .context("Trying to insert the key blob.")?; |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2070 | if let Some(cert) = &cert_info.cert { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2071 | Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2072 | .context("Trying to insert the certificate.")?; |
| 2073 | } |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2074 | if let Some(cert_chain) = &cert_info.cert_chain { |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2075 | Self::set_blob_internal( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2076 | tx, |
| 2077 | key_id.id(), |
| 2078 | SubComponentType::CERT_CHAIN, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2079 | Some(&cert_chain), |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2080 | None, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2081 | ) |
| 2082 | .context("Trying to insert the certificate chain.")?; |
| 2083 | } |
| 2084 | Self::insert_keyparameter_internal(tx, &key_id, params) |
| 2085 | .context("Trying to insert key parameters.")?; |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2086 | metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?; |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2087 | let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2088 | .context("Trying to rebind alias.")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2089 | Ok(key_id).do_gc(need_gc) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2090 | }) |
| 2091 | .context("In store_new_key.") |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2092 | } |
| 2093 | |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2094 | /// Store a new certificate |
| 2095 | /// The function creates a new key entry, populates the blob field and metadata, and rebinds |
| 2096 | /// the given alias to the new cert. |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2097 | pub fn store_new_certificate( |
| 2098 | &mut self, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2099 | key: &KeyDescriptor, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2100 | cert: &[u8], |
| 2101 | km_uuid: &Uuid, |
| 2102 | ) -> Result<KeyIdGuard> { |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2103 | let (alias, domain, namespace) = match key { |
| 2104 | KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None } |
| 2105 | | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => { |
| 2106 | (alias, key.domain, nspace) |
| 2107 | } |
| 2108 | _ => { |
| 2109 | return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context( |
| 2110 | "In store_new_certificate: Need alias and domain must be APP or SELINUX.", |
| 2111 | ) |
| 2112 | } |
| 2113 | }; |
| 2114 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2115 | 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] | 2116 | .context("Trying to create new key entry.")?; |
| 2117 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2118 | Self::set_blob_internal( |
| 2119 | tx, |
| 2120 | key_id.id(), |
| 2121 | SubComponentType::CERT_CHAIN, |
| 2122 | Some(cert), |
| 2123 | None, |
| 2124 | ) |
| 2125 | .context("Trying to insert certificate.")?; |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2126 | |
| 2127 | let mut metadata = KeyMetaData::new(); |
| 2128 | metadata.add(KeyMetaEntry::CreationDate( |
| 2129 | DateTime::now().context("Trying to make creation time.")?, |
| 2130 | )); |
| 2131 | |
| 2132 | metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?; |
| 2133 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2134 | let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace) |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2135 | .context("Trying to rebind alias.")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2136 | Ok(key_id).do_gc(need_gc) |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2137 | }) |
| 2138 | .context("In store_new_certificate.") |
| 2139 | } |
| 2140 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2141 | // Helper function loading the key_id given the key descriptor |
| 2142 | // tuple comprising domain, namespace, and alias. |
| 2143 | // Requires a valid transaction. |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2144 | 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] | 2145 | let alias = key |
| 2146 | .alias |
| 2147 | .as_ref() |
| 2148 | .map_or_else(|| Err(KsError::sys()), Ok) |
| 2149 | .context("In load_key_entry_id: Alias must be specified.")?; |
| 2150 | let mut stmt = tx |
| 2151 | .prepare( |
| 2152 | "SELECT id FROM persistent.keyentry |
| 2153 | WHERE |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 2154 | key_type = ? |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2155 | AND domain = ? |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2156 | AND namespace = ? |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2157 | AND alias = ? |
| 2158 | AND state = ?;", |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2159 | ) |
| 2160 | .context("In load_key_entry_id: Failed to select from keyentry table.")?; |
| 2161 | let mut rows = stmt |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2162 | .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] | 2163 | .context("In load_key_entry_id: Failed to read from keyentry table.")?; |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 2164 | db_utils::with_rows_extract_one(&mut rows, |row| { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2165 | row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)? |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2166 | .get(0) |
| 2167 | .context("Failed to unpack id.") |
| 2168 | }) |
| 2169 | .context("In load_key_entry_id.") |
| 2170 | } |
| 2171 | |
| 2172 | /// This helper function completes the access tuple of a key, which is required |
| 2173 | /// to perform access control. The strategy depends on the `domain` field in the |
| 2174 | /// key descriptor. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2175 | /// * Domain::SELINUX: The access tuple is complete and this function only loads |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2176 | /// the key_id for further processing. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2177 | /// * 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] | 2178 | /// which serves as the namespace. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2179 | /// * 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] | 2180 | /// `access_vector`. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2181 | /// * 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] | 2182 | /// `namespace`. |
| 2183 | /// In each case the information returned is sufficient to perform the access |
| 2184 | /// check and the key id can be used to load further key artifacts. |
| 2185 | fn load_access_tuple( |
| 2186 | tx: &Transaction, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2187 | key: &KeyDescriptor, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2188 | key_type: KeyType, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2189 | caller_uid: u32, |
| 2190 | ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> { |
| 2191 | match key.domain { |
| 2192 | // Domain App or SELinux. In this case we load the key_id from |
| 2193 | // the keyentry database for further loading of key components. |
| 2194 | // We already have the full access tuple to perform access control. |
| 2195 | // The only distinction is that we use the caller_uid instead |
| 2196 | // of the caller supplied namespace if the domain field is |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2197 | // Domain::APP. |
| 2198 | Domain::APP | Domain::SELINUX => { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2199 | let mut access_key = key.clone(); |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2200 | if access_key.domain == Domain::APP { |
| 2201 | access_key.nspace = caller_uid as i64; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2202 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2203 | 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] | 2204 | .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2205 | |
| 2206 | Ok((key_id, access_key, None)) |
| 2207 | } |
| 2208 | |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2209 | // 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] | 2210 | // from the grant table. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2211 | Domain::GRANT => { |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2212 | let mut stmt = tx |
| 2213 | .prepare( |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 2214 | "SELECT keyentryid, access_vector FROM persistent.grant |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2215 | WHERE grantee = ? AND id = ?;", |
| 2216 | ) |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2217 | .context("Domain::GRANT prepare statement failed")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2218 | let mut rows = stmt |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2219 | .query(params![caller_uid as i64, key.nspace]) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2220 | .context("Domain:Grant: query failed.")?; |
| 2221 | let (key_id, access_vector): (i64, i32) = |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 2222 | db_utils::with_rows_extract_one(&mut rows, |row| { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2223 | let r = |
| 2224 | row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2225 | Ok(( |
| 2226 | r.get(0).context("Failed to unpack key_id.")?, |
| 2227 | r.get(1).context("Failed to unpack access_vector.")?, |
| 2228 | )) |
| 2229 | }) |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2230 | .context("Domain::GRANT.")?; |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2231 | Ok((key_id, key.clone(), Some(access_vector.into()))) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2232 | } |
| 2233 | |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2234 | // 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] | 2235 | // keyentry database because we need them for access control. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2236 | Domain::KEY_ID => { |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 2237 | let (domain, namespace): (Domain, i64) = { |
| 2238 | let mut stmt = tx |
| 2239 | .prepare( |
| 2240 | "SELECT domain, namespace FROM persistent.keyentry |
| 2241 | WHERE |
| 2242 | id = ? |
| 2243 | AND state = ?;", |
| 2244 | ) |
| 2245 | .context("Domain::KEY_ID: prepare statement failed")?; |
| 2246 | let mut rows = stmt |
| 2247 | .query(params![key.nspace, KeyLifeCycle::Live]) |
| 2248 | .context("Domain::KEY_ID: query failed.")?; |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 2249 | db_utils::with_rows_extract_one(&mut rows, |row| { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2250 | let r = |
| 2251 | row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2252 | Ok(( |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2253 | Domain(r.get(0).context("Failed to unpack domain.")?), |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2254 | r.get(1).context("Failed to unpack namespace.")?, |
| 2255 | )) |
| 2256 | }) |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 2257 | .context("Domain::KEY_ID.")? |
| 2258 | }; |
| 2259 | |
| 2260 | // We may use a key by id after loading it by grant. |
| 2261 | // In this case we have to check if the caller has a grant for this particular |
| 2262 | // key. We can skip this if we already know that the caller is the owner. |
| 2263 | // But we cannot know this if domain is anything but App. E.g. in the case |
| 2264 | // of Domain::SELINUX we have to speculatively check for grants because we have to |
| 2265 | // consult the SEPolicy before we know if the caller is the owner. |
| 2266 | let access_vector: Option<KeyPermSet> = |
| 2267 | if domain != Domain::APP || namespace != caller_uid as i64 { |
| 2268 | let access_vector: Option<i32> = tx |
| 2269 | .query_row( |
| 2270 | "SELECT access_vector FROM persistent.grant |
| 2271 | WHERE grantee = ? AND keyentryid = ?;", |
| 2272 | params![caller_uid as i64, key.nspace], |
| 2273 | |row| row.get(0), |
| 2274 | ) |
| 2275 | .optional() |
| 2276 | .context("Domain::KEY_ID: query grant failed.")?; |
| 2277 | access_vector.map(|p| p.into()) |
| 2278 | } else { |
| 2279 | None |
| 2280 | }; |
| 2281 | |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2282 | let key_id = key.nspace; |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2283 | let mut access_key: KeyDescriptor = key.clone(); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2284 | access_key.domain = domain; |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2285 | access_key.nspace = namespace; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2286 | |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 2287 | Ok((key_id, access_key, access_vector)) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2288 | } |
| 2289 | _ => Err(anyhow!(KsError::sys())), |
| 2290 | } |
| 2291 | } |
| 2292 | |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2293 | fn load_blob_components( |
| 2294 | key_id: i64, |
| 2295 | load_bits: KeyEntryLoadBits, |
| 2296 | tx: &Transaction, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2297 | ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> { |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2298 | let mut stmt = tx |
| 2299 | .prepare( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2300 | "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2301 | WHERE keyentryid = ? GROUP BY subcomponent_type;", |
| 2302 | ) |
| 2303 | .context("In load_blob_components: prepare statement failed.")?; |
| 2304 | |
| 2305 | let mut rows = |
| 2306 | stmt.query(params![key_id]).context("In load_blob_components: query failed.")?; |
| 2307 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2308 | let mut key_blob: Option<(i64, Vec<u8>)> = None; |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2309 | let mut cert_blob: Option<Vec<u8>> = None; |
| 2310 | let mut cert_chain_blob: Option<Vec<u8>> = None; |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2311 | let mut has_km_blob: bool = false; |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 2312 | db_utils::with_rows_extract_all(&mut rows, |row| { |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2313 | let sub_type: SubComponentType = |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2314 | row.get(1).context("Failed to extract subcomponent_type.")?; |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2315 | has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2316 | match (sub_type, load_bits.load_public(), load_bits.load_km()) { |
| 2317 | (SubComponentType::KEY_BLOB, _, true) => { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2318 | key_blob = Some(( |
| 2319 | row.get(0).context("Failed to extract key blob id.")?, |
| 2320 | row.get(2).context("Failed to extract key blob.")?, |
| 2321 | )); |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2322 | } |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2323 | (SubComponentType::CERT, true, _) => { |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2324 | cert_blob = |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2325 | Some(row.get(2).context("Failed to extract public certificate blob.")?); |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2326 | } |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2327 | (SubComponentType::CERT_CHAIN, true, _) => { |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2328 | cert_chain_blob = |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2329 | Some(row.get(2).context("Failed to extract certificate chain blob.")?); |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2330 | } |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2331 | (SubComponentType::CERT, _, _) |
| 2332 | | (SubComponentType::CERT_CHAIN, _, _) |
| 2333 | | (SubComponentType::KEY_BLOB, _, _) => {} |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2334 | _ => Err(KsError::sys()).context("Unknown subcomponent type.")?, |
| 2335 | } |
| 2336 | Ok(()) |
| 2337 | }) |
| 2338 | .context("In load_blob_components.")?; |
| 2339 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2340 | let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| { |
| 2341 | Ok(Some(( |
| 2342 | blob, |
| 2343 | BlobMetaData::load_from_db(blob_id, tx) |
| 2344 | .context("In load_blob_components: Trying to load blob_metadata.")?, |
| 2345 | ))) |
| 2346 | })?; |
| 2347 | |
| 2348 | Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob)) |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2349 | } |
| 2350 | |
| 2351 | fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> { |
| 2352 | let mut stmt = tx |
| 2353 | .prepare( |
| 2354 | "SELECT tag, data, security_level from persistent.keyparameter |
| 2355 | WHERE keyentryid = ?;", |
| 2356 | ) |
| 2357 | .context("In load_key_parameters: prepare statement failed.")?; |
| 2358 | |
| 2359 | let mut parameters: Vec<KeyParameter> = Vec::new(); |
| 2360 | |
| 2361 | let mut rows = |
| 2362 | stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?; |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 2363 | db_utils::with_rows_extract_all(&mut rows, |row| { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2364 | let tag = Tag(row.get(0).context("Failed to read tag.")?); |
| 2365 | 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] | 2366 | parameters.push( |
| 2367 | KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level) |
| 2368 | .context("Failed to read KeyParameter.")?, |
| 2369 | ); |
| 2370 | Ok(()) |
| 2371 | }) |
| 2372 | .context("In load_key_parameters.")?; |
| 2373 | |
| 2374 | Ok(parameters) |
| 2375 | } |
| 2376 | |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2377 | /// Decrements the usage count of a limited use key. This function first checks whether the |
| 2378 | /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches |
| 2379 | /// zero, the key also gets marked unreferenced and scheduled for deletion. |
| 2380 | /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector. |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2381 | pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> { |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2382 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 2383 | let limit: Option<i32> = tx |
| 2384 | .query_row( |
| 2385 | "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;", |
| 2386 | params![key_id, Tag::USAGE_COUNT_LIMIT.0], |
| 2387 | |row| row.get(0), |
| 2388 | ) |
| 2389 | .optional() |
| 2390 | .context("Trying to load usage count")?; |
| 2391 | |
| 2392 | let limit = limit |
| 2393 | .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB)) |
| 2394 | .context("The Key no longer exists. Key is exhausted.")?; |
| 2395 | |
| 2396 | tx.execute( |
| 2397 | "UPDATE persistent.keyparameter |
| 2398 | SET data = data - 1 |
| 2399 | WHERE keyentryid = ? AND tag = ? AND data > 0;", |
| 2400 | params![key_id, Tag::USAGE_COUNT_LIMIT.0], |
| 2401 | ) |
| 2402 | .context("Failed to update key usage count.")?; |
| 2403 | |
| 2404 | match limit { |
| 2405 | 1 => Self::mark_unreferenced(tx, key_id) |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2406 | .map(|need_gc| (need_gc, ())) |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2407 | .context("Trying to mark limited use key for deletion."), |
| 2408 | 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."), |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2409 | _ => Ok(()).no_gc(), |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2410 | } |
| 2411 | }) |
| 2412 | .context("In check_and_update_key_usage_count.") |
| 2413 | } |
| 2414 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2415 | /// Load a key entry by the given key descriptor. |
| 2416 | /// It uses the `check_permission` callback to verify if the access is allowed |
| 2417 | /// given the key access tuple read from the database using `load_access_tuple`. |
| 2418 | /// With `load_bits` the caller may specify which blobs shall be loaded from |
| 2419 | /// the blob database. |
| 2420 | pub fn load_key_entry( |
| 2421 | &mut self, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2422 | key: &KeyDescriptor, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2423 | key_type: KeyType, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2424 | load_bits: KeyEntryLoadBits, |
| 2425 | caller_uid: u32, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2426 | check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>, |
| 2427 | ) -> Result<(KeyIdGuard, KeyEntry)> { |
| 2428 | loop { |
| 2429 | match self.load_key_entry_internal( |
| 2430 | key, |
| 2431 | key_type, |
| 2432 | load_bits, |
| 2433 | caller_uid, |
| 2434 | &check_permission, |
| 2435 | ) { |
| 2436 | Ok(result) => break Ok(result), |
| 2437 | Err(e) => { |
| 2438 | if Self::is_locked_error(&e) { |
| 2439 | std::thread::sleep(std::time::Duration::from_micros(500)); |
| 2440 | continue; |
| 2441 | } else { |
| 2442 | return Err(e).context("In load_key_entry."); |
| 2443 | } |
| 2444 | } |
| 2445 | } |
| 2446 | } |
| 2447 | } |
| 2448 | |
| 2449 | fn load_key_entry_internal( |
| 2450 | &mut self, |
| 2451 | key: &KeyDescriptor, |
| 2452 | key_type: KeyType, |
| 2453 | load_bits: KeyEntryLoadBits, |
| 2454 | caller_uid: u32, |
| 2455 | check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2456 | ) -> Result<(KeyIdGuard, KeyEntry)> { |
| 2457 | // KEY ID LOCK 1/2 |
| 2458 | // If we got a key descriptor with a key id we can get the lock right away. |
| 2459 | // Otherwise we have to defer it until we know the key id. |
| 2460 | let key_id_guard = match key.domain { |
| 2461 | Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)), |
| 2462 | _ => None, |
| 2463 | }; |
| 2464 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2465 | let tx = self |
| 2466 | .conn |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2467 | .unchecked_transaction() |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2468 | .context("In load_key_entry: Failed to initialize transaction.")?; |
| 2469 | |
| 2470 | // Load the key_id and complete the access control tuple. |
| 2471 | let (key_id, access_key_descriptor, access_vector) = |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2472 | Self::load_access_tuple(&tx, key, key_type, caller_uid) |
| 2473 | .context("In load_key_entry.")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2474 | |
| 2475 | // Perform access control. It is vital that we return here if the permission is denied. |
| 2476 | // So do not touch that '?' at the end. |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2477 | check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2478 | |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2479 | // KEY ID LOCK 2/2 |
| 2480 | // If we did not get a key id lock by now, it was because we got a key descriptor |
| 2481 | // without a key id. At this point we got the key id, so we can try and get a lock. |
| 2482 | // However, we cannot block here, because we are in the middle of the transaction. |
| 2483 | // So first we try to get the lock non blocking. If that fails, we roll back the |
| 2484 | // transaction and block until we get the lock. After we successfully got the lock, |
| 2485 | // we start a new transaction and load the access tuple again. |
| 2486 | // |
| 2487 | // We don't need to perform access control again, because we already established |
| 2488 | // that the caller had access to the given key. But we need to make sure that the |
| 2489 | // key id still exists. So we have to load the key entry by key id this time. |
| 2490 | let (key_id_guard, tx) = match key_id_guard { |
| 2491 | None => match KEY_ID_LOCK.try_get(key_id) { |
| 2492 | None => { |
| 2493 | // Roll back the transaction. |
| 2494 | tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2495 | |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2496 | // Block until we have a key id lock. |
| 2497 | let key_id_guard = KEY_ID_LOCK.get(key_id); |
| 2498 | |
| 2499 | // Create a new transaction. |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2500 | let tx = self |
| 2501 | .conn |
| 2502 | .unchecked_transaction() |
| 2503 | .context("In load_key_entry: Failed to initialize transaction.")?; |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2504 | |
| 2505 | Self::load_access_tuple( |
| 2506 | &tx, |
| 2507 | // This time we have to load the key by the retrieved key id, because the |
| 2508 | // alias may have been rebound after we rolled back the transaction. |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2509 | &KeyDescriptor { |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2510 | domain: Domain::KEY_ID, |
| 2511 | nspace: key_id, |
| 2512 | ..Default::default() |
| 2513 | }, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2514 | key_type, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2515 | caller_uid, |
| 2516 | ) |
| 2517 | .context("In load_key_entry. (deferred key lock)")?; |
| 2518 | (key_id_guard, tx) |
| 2519 | } |
| 2520 | Some(l) => (l, tx), |
| 2521 | }, |
| 2522 | Some(key_id_guard) => (key_id_guard, tx), |
| 2523 | }; |
| 2524 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2525 | let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id()) |
| 2526 | .context("In load_key_entry.")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2527 | |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2528 | tx.commit().context("In load_key_entry: Failed to commit transaction.")?; |
| 2529 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2530 | Ok((key_id_guard, key_entry)) |
| 2531 | } |
| 2532 | |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2533 | fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2534 | let updated = tx |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2535 | .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id]) |
| 2536 | .context("Trying to delete keyentry.")?; |
| 2537 | tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id]) |
| 2538 | .context("Trying to delete keymetadata.")?; |
| 2539 | tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id]) |
| 2540 | .context("Trying to delete keyparameters.")?; |
| 2541 | tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id]) |
| 2542 | .context("Trying to delete grants.")?; |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2543 | Ok(updated != 0) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2544 | } |
| 2545 | |
| 2546 | /// 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] | 2547 | /// 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] | 2548 | pub fn unbind_key( |
| 2549 | &mut self, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2550 | key: &KeyDescriptor, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2551 | key_type: KeyType, |
| 2552 | caller_uid: u32, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2553 | check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2554 | ) -> Result<()> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2555 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 2556 | let (key_id, access_key_descriptor, access_vector) = |
| 2557 | Self::load_access_tuple(tx, key, key_type, caller_uid) |
| 2558 | .context("Trying to get access tuple.")?; |
| 2559 | |
| 2560 | // Perform access control. It is vital that we return here if the permission is denied. |
| 2561 | // So do not touch that '?' at the end. |
| 2562 | check_permission(&access_key_descriptor, access_vector) |
| 2563 | .context("While checking permission.")?; |
| 2564 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2565 | Self::mark_unreferenced(tx, key_id) |
| 2566 | .map(|need_gc| (need_gc, ())) |
| 2567 | .context("Trying to mark the key unreferenced.") |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2568 | }) |
| 2569 | .context("In unbind_key.") |
| 2570 | } |
| 2571 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2572 | fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> { |
| 2573 | tx.query_row( |
| 2574 | "SELECT km_uuid FROM persistent.keyentry WHERE id = ?", |
| 2575 | params![key_id], |
| 2576 | |row| row.get(0), |
| 2577 | ) |
| 2578 | .context("In get_key_km_uuid.") |
| 2579 | } |
| 2580 | |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 2581 | /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple. |
| 2582 | /// This leaves all of the blob entries orphaned for subsequent garbage collection. |
| 2583 | pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> { |
| 2584 | if !(domain == Domain::APP || domain == Domain::SELINUX) { |
| 2585 | return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)) |
| 2586 | .context("In unbind_keys_for_namespace."); |
| 2587 | } |
| 2588 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 2589 | tx.execute( |
| 2590 | "DELETE FROM persistent.keymetadata |
| 2591 | WHERE keyentryid IN ( |
| 2592 | SELECT id FROM persistent.keyentry |
| 2593 | WHERE domain = ? AND namespace = ? |
| 2594 | );", |
| 2595 | params![domain.0, namespace], |
| 2596 | ) |
| 2597 | .context("Trying to delete keymetadata.")?; |
| 2598 | tx.execute( |
| 2599 | "DELETE FROM persistent.keyparameter |
| 2600 | WHERE keyentryid IN ( |
| 2601 | SELECT id FROM persistent.keyentry |
| 2602 | WHERE domain = ? AND namespace = ? |
| 2603 | );", |
| 2604 | params![domain.0, namespace], |
| 2605 | ) |
| 2606 | .context("Trying to delete keyparameters.")?; |
| 2607 | tx.execute( |
| 2608 | "DELETE FROM persistent.grant |
| 2609 | WHERE keyentryid IN ( |
| 2610 | SELECT id FROM persistent.keyentry |
| 2611 | WHERE domain = ? AND namespace = ? |
| 2612 | );", |
| 2613 | params![domain.0, namespace], |
| 2614 | ) |
| 2615 | .context("Trying to delete grants.")?; |
| 2616 | tx.execute( |
| 2617 | "DELETE FROM persistent.keyentry WHERE domain = ? AND namespace = ?;", |
| 2618 | params![domain.0, namespace], |
| 2619 | ) |
| 2620 | .context("Trying to delete keyentry.")?; |
| 2621 | Ok(()).need_gc() |
| 2622 | }) |
| 2623 | .context("In unbind_keys_for_namespace") |
| 2624 | } |
| 2625 | |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 2626 | /// Delete the keys created on behalf of the user, denoted by the user id. |
| 2627 | /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true. |
| 2628 | /// Returned boolean is to hint the garbage collector to delete the unbound keys. |
| 2629 | /// The caller of this function should notify the gc if the returned value is true. |
| 2630 | pub fn unbind_keys_for_user( |
| 2631 | &mut self, |
| 2632 | user_id: u32, |
| 2633 | keep_non_super_encrypted_keys: bool, |
| 2634 | ) -> Result<()> { |
| 2635 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 2636 | let mut stmt = tx |
| 2637 | .prepare(&format!( |
| 2638 | "SELECT id from persistent.keyentry |
| 2639 | WHERE ( |
| 2640 | key_type = ? |
| 2641 | AND domain = ? |
| 2642 | AND cast ( (namespace/{aid_user_offset}) as int) = ? |
| 2643 | AND state = ? |
| 2644 | ) OR ( |
| 2645 | key_type = ? |
| 2646 | AND namespace = ? |
| 2647 | AND alias = ? |
| 2648 | AND state = ? |
| 2649 | );", |
| 2650 | aid_user_offset = AID_USER_OFFSET |
| 2651 | )) |
| 2652 | .context(concat!( |
| 2653 | "In unbind_keys_for_user. ", |
| 2654 | "Failed to prepare the query to find the keys created by apps." |
| 2655 | ))?; |
| 2656 | |
| 2657 | let mut rows = stmt |
| 2658 | .query(params![ |
| 2659 | // WHERE client key: |
| 2660 | KeyType::Client, |
| 2661 | Domain::APP.0 as u32, |
| 2662 | user_id, |
| 2663 | KeyLifeCycle::Live, |
| 2664 | // OR super key: |
| 2665 | KeyType::Super, |
| 2666 | user_id, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 2667 | USER_SUPER_KEY.alias, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 2668 | KeyLifeCycle::Live |
| 2669 | ]) |
| 2670 | .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?; |
| 2671 | |
| 2672 | let mut key_ids: Vec<i64> = Vec::new(); |
| 2673 | db_utils::with_rows_extract_all(&mut rows, |row| { |
| 2674 | key_ids |
| 2675 | .push(row.get(0).context("Failed to read key id of a key created by an app.")?); |
| 2676 | Ok(()) |
| 2677 | }) |
| 2678 | .context("In unbind_keys_for_user.")?; |
| 2679 | |
| 2680 | let mut notify_gc = false; |
| 2681 | for key_id in key_ids { |
| 2682 | if keep_non_super_encrypted_keys { |
| 2683 | // Load metadata and filter out non-super-encrypted keys. |
| 2684 | if let (_, Some((_, blob_metadata)), _, _) = |
| 2685 | Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx) |
| 2686 | .context("In unbind_keys_for_user: Trying to load blob info.")? |
| 2687 | { |
| 2688 | if blob_metadata.encrypted_by().is_none() { |
| 2689 | continue; |
| 2690 | } |
| 2691 | } |
| 2692 | } |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 2693 | notify_gc = Self::mark_unreferenced(&tx, key_id) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 2694 | .context("In unbind_keys_for_user.")? |
| 2695 | || notify_gc; |
| 2696 | } |
| 2697 | Ok(()).do_gc(notify_gc) |
| 2698 | }) |
| 2699 | .context("In unbind_keys_for_user.") |
| 2700 | } |
| 2701 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2702 | fn load_key_components( |
| 2703 | tx: &Transaction, |
| 2704 | load_bits: KeyEntryLoadBits, |
| 2705 | key_id: i64, |
| 2706 | ) -> Result<KeyEntry> { |
| 2707 | let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?; |
| 2708 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2709 | let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) = |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2710 | Self::load_blob_components(key_id, load_bits, &tx) |
| 2711 | .context("In load_key_components.")?; |
| 2712 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2713 | let parameters = Self::load_key_parameters(key_id, &tx) |
| 2714 | .context("In load_key_components: Trying to load key parameters.")?; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2715 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2716 | let km_uuid = Self::get_key_km_uuid(&tx, key_id) |
| 2717 | .context("In load_key_components: Trying to get KM uuid.")?; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2718 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2719 | Ok(KeyEntry { |
| 2720 | id: key_id, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2721 | key_blob_info, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2722 | cert: cert_blob, |
| 2723 | cert_chain: cert_chain_blob, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2724 | km_uuid, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2725 | parameters, |
| 2726 | metadata, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2727 | pure_cert: !has_km_blob, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2728 | }) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2729 | } |
| 2730 | |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 2731 | /// Returns a list of KeyDescriptors in the selected domain/namespace. |
| 2732 | /// The key descriptors will have the domain, nspace, and alias field set. |
| 2733 | /// Domain must be APP or SELINUX, the caller must make sure of that. |
| 2734 | pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2735 | self.with_transaction(TransactionBehavior::Deferred, |tx| { |
| 2736 | let mut stmt = tx |
| 2737 | .prepare( |
| 2738 | "SELECT alias FROM persistent.keyentry |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2739 | WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;", |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2740 | ) |
| 2741 | .context("In list: Failed to prepare.")?; |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 2742 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2743 | let mut rows = stmt |
| 2744 | .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live]) |
| 2745 | .context("In list: Failed to query.")?; |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 2746 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2747 | let mut descriptors: Vec<KeyDescriptor> = Vec::new(); |
| 2748 | db_utils::with_rows_extract_all(&mut rows, |row| { |
| 2749 | descriptors.push(KeyDescriptor { |
| 2750 | domain, |
| 2751 | nspace: namespace, |
| 2752 | alias: Some(row.get(0).context("Trying to extract alias.")?), |
| 2753 | blob: None, |
| 2754 | }); |
| 2755 | Ok(()) |
| 2756 | }) |
| 2757 | .context("In list: Failed to extract rows.")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2758 | Ok(descriptors).no_gc() |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 2759 | }) |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 2760 | } |
| 2761 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2762 | /// Adds a grant to the grant table. |
| 2763 | /// Like `load_key_entry` this function loads the access tuple before |
| 2764 | /// it uses the callback for a permission check. Upon success, |
| 2765 | /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the |
| 2766 | /// grant table. The new row will have a randomized id, which is used as |
| 2767 | /// grant id in the namespace field of the resulting KeyDescriptor. |
| 2768 | pub fn grant( |
| 2769 | &mut self, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2770 | key: &KeyDescriptor, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2771 | caller_uid: u32, |
| 2772 | grantee_uid: u32, |
| 2773 | access_vector: KeyPermSet, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2774 | check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2775 | ) -> Result<KeyDescriptor> { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2776 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 2777 | // Load the key_id and complete the access control tuple. |
| 2778 | // We ignore the access vector here because grants cannot be granted. |
| 2779 | // The access vector returned here expresses the permissions the |
| 2780 | // grantee has if key.domain == Domain::GRANT. But this vector |
| 2781 | // cannot include the grant permission by design, so there is no way the |
| 2782 | // subsequent permission check can pass. |
| 2783 | // We could check key.domain == Domain::GRANT and fail early. |
| 2784 | // But even if we load the access tuple by grant here, the permission |
| 2785 | // check denies the attempt to create a grant by grant descriptor. |
| 2786 | let (key_id, access_key_descriptor, _) = |
| 2787 | Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid) |
| 2788 | .context("In grant")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2789 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2790 | // Perform access control. It is vital that we return here if the permission |
| 2791 | // was denied. So do not touch that '?' at the end of the line. |
| 2792 | // This permission check checks if the caller has the grant permission |
| 2793 | // for the given key and in addition to all of the permissions |
| 2794 | // expressed in `access_vector`. |
| 2795 | check_permission(&access_key_descriptor, &access_vector) |
| 2796 | .context("In grant: check_permission failed.")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2797 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2798 | let grant_id = if let Some(grant_id) = tx |
| 2799 | .query_row( |
| 2800 | "SELECT id FROM persistent.grant |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2801 | WHERE keyentryid = ? AND grantee = ?;", |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2802 | params![key_id, grantee_uid], |
| 2803 | |row| row.get(0), |
| 2804 | ) |
| 2805 | .optional() |
| 2806 | .context("In grant: Failed get optional existing grant id.")? |
| 2807 | { |
| 2808 | tx.execute( |
| 2809 | "UPDATE persistent.grant |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2810 | SET access_vector = ? |
| 2811 | WHERE id = ?;", |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2812 | params![i32::from(access_vector), grant_id], |
Joel Galenson | 845f74b | 2020-09-09 14:11:55 -0700 | [diff] [blame] | 2813 | ) |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2814 | .context("In grant: Failed to update existing grant.")?; |
| 2815 | grant_id |
| 2816 | } else { |
| 2817 | Self::insert_with_retry(|id| { |
| 2818 | tx.execute( |
| 2819 | "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector) |
| 2820 | VALUES (?, ?, ?, ?);", |
| 2821 | params![id, grantee_uid, key_id, i32::from(access_vector)], |
| 2822 | ) |
| 2823 | }) |
| 2824 | .context("In grant")? |
| 2825 | }; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2826 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2827 | Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None }) |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2828 | .no_gc() |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2829 | }) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2830 | } |
| 2831 | |
| 2832 | /// This function checks permissions like `grant` and `load_key_entry` |
| 2833 | /// before removing a grant from the grant table. |
| 2834 | pub fn ungrant( |
| 2835 | &mut self, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2836 | key: &KeyDescriptor, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2837 | caller_uid: u32, |
| 2838 | grantee_uid: u32, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2839 | check_permission: impl Fn(&KeyDescriptor) -> Result<()>, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2840 | ) -> Result<()> { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2841 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 2842 | // Load the key_id and complete the access control tuple. |
| 2843 | // We ignore the access vector here because grants cannot be granted. |
| 2844 | let (key_id, access_key_descriptor, _) = |
| 2845 | Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid) |
| 2846 | .context("In ungrant.")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2847 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2848 | // Perform access control. We must return here if the permission |
| 2849 | // was denied. So do not touch the '?' at the end of this line. |
| 2850 | check_permission(&access_key_descriptor) |
| 2851 | .context("In grant: check_permission failed.")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2852 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2853 | tx.execute( |
| 2854 | "DELETE FROM persistent.grant |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2855 | WHERE keyentryid = ? AND grantee = ?;", |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2856 | params![key_id, grantee_uid], |
| 2857 | ) |
| 2858 | .context("Failed to delete grant.")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2859 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2860 | Ok(()).no_gc() |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2861 | }) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2862 | } |
| 2863 | |
Joel Galenson | 845f74b | 2020-09-09 14:11:55 -0700 | [diff] [blame] | 2864 | // Generates a random id and passes it to the given function, which will |
| 2865 | // try to insert it into a database. If that insertion fails, retry; |
| 2866 | // otherwise return the id. |
| 2867 | fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> { |
| 2868 | loop { |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 2869 | let newid: i64 = match random() { |
| 2870 | Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned. |
| 2871 | i => i, |
| 2872 | }; |
Joel Galenson | 845f74b | 2020-09-09 14:11:55 -0700 | [diff] [blame] | 2873 | match inserter(newid) { |
| 2874 | // If the id already existed, try again. |
| 2875 | Err(rusqlite::Error::SqliteFailure( |
| 2876 | libsqlite3_sys::Error { |
| 2877 | code: libsqlite3_sys::ErrorCode::ConstraintViolation, |
| 2878 | extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE, |
| 2879 | }, |
| 2880 | _, |
| 2881 | )) => (), |
| 2882 | Err(e) => { |
| 2883 | return Err(e).context("In insert_with_retry: failed to insert into database.") |
| 2884 | } |
| 2885 | _ => return Ok(newid), |
| 2886 | } |
| 2887 | } |
| 2888 | } |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 2889 | |
| 2890 | /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table |
| 2891 | pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2892 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 2893 | tx.execute( |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 2894 | "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id, |
| 2895 | authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);", |
| 2896 | params![ |
| 2897 | auth_token.challenge, |
| 2898 | auth_token.userId, |
| 2899 | auth_token.authenticatorId, |
| 2900 | auth_token.authenticatorType.0 as i32, |
| 2901 | auth_token.timestamp.milliSeconds as i64, |
| 2902 | auth_token.mac, |
| 2903 | MonotonicRawTime::now(), |
| 2904 | ], |
| 2905 | ) |
| 2906 | .context("In insert_auth_token: failed to insert auth token into the database")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2907 | Ok(()).no_gc() |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2908 | }) |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 2909 | } |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 2910 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 2911 | /// Find the newest auth token matching the given predicate. |
| 2912 | pub fn find_auth_token_entry<F>( |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 2913 | &mut self, |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 2914 | p: F, |
| 2915 | ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>> |
| 2916 | where |
| 2917 | F: Fn(&AuthTokenEntry) -> bool, |
| 2918 | { |
| 2919 | self.with_transaction(TransactionBehavior::Deferred, |tx| { |
| 2920 | let mut stmt = tx |
| 2921 | .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;") |
| 2922 | .context("Prepare statement failed.")?; |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 2923 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 2924 | let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?; |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 2925 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 2926 | while let Some(row) = rows.next().context("Failed to get next row.")? { |
| 2927 | let entry = AuthTokenEntry::new( |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 2928 | HardwareAuthToken { |
| 2929 | challenge: row.get(1)?, |
| 2930 | userId: row.get(2)?, |
| 2931 | authenticatorId: row.get(3)?, |
| 2932 | authenticatorType: HardwareAuthenticatorType(row.get(4)?), |
| 2933 | timestamp: Timestamp { milliSeconds: row.get(5)? }, |
| 2934 | mac: row.get(6)?, |
| 2935 | }, |
| 2936 | row.get(7)?, |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 2937 | ); |
| 2938 | if p(&entry) { |
| 2939 | return Ok(Some(( |
| 2940 | entry, |
| 2941 | Self::get_last_off_body(tx) |
| 2942 | .context("In find_auth_token_entry: Trying to get last off body")?, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2943 | ))) |
| 2944 | .no_gc(); |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 2945 | } |
| 2946 | } |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2947 | Ok(None).no_gc() |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 2948 | }) |
| 2949 | .context("In find_auth_token_entry.") |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 2950 | } |
| 2951 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 2952 | /// Insert last_off_body into the metadata table at the initialization of auth token table |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2953 | pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> { |
| 2954 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 2955 | tx.execute( |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 2956 | "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);", |
| 2957 | params!["last_off_body", last_off_body], |
| 2958 | ) |
| 2959 | .context("In insert_last_off_body: failed to insert.")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2960 | Ok(()).no_gc() |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2961 | }) |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 2962 | } |
| 2963 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 2964 | /// Update last_off_body when on_device_off_body is called |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2965 | pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> { |
| 2966 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 2967 | tx.execute( |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 2968 | "UPDATE perboot.metadata SET value = ? WHERE key = ?;", |
| 2969 | params![last_off_body, "last_off_body"], |
| 2970 | ) |
| 2971 | .context("In update_last_off_body: failed to update.")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2972 | Ok(()).no_gc() |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2973 | }) |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 2974 | } |
| 2975 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 2976 | /// Get last_off_body time when finding auth tokens |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 2977 | fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 2978 | tx.query_row( |
| 2979 | "SELECT value from perboot.metadata WHERE key = ?;", |
| 2980 | params!["last_off_body"], |
| 2981 | |row| Ok(row.get(0)?), |
| 2982 | ) |
| 2983 | .context("In get_last_off_body: query_row failed.") |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 2984 | } |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 2985 | } |
| 2986 | |
| 2987 | #[cfg(test)] |
| 2988 | mod tests { |
| 2989 | |
| 2990 | use super::*; |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2991 | use crate::key_parameter::{ |
| 2992 | Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter, |
| 2993 | KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel, |
| 2994 | }; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2995 | use crate::key_perm_set; |
| 2996 | use crate::permission::{KeyPerm, KeyPermSet}; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 2997 | use crate::super_key::SuperKeyManager; |
Janis Danisevskis | 2a8330a | 2021-01-20 15:34:26 -0800 | [diff] [blame] | 2998 | use keystore2_test_utils::TempDir; |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 2999 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{ |
| 3000 | HardwareAuthToken::HardwareAuthToken, |
| 3001 | HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type, |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 3002 | }; |
| 3003 | use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{ |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 3004 | Timestamp::Timestamp, |
| 3005 | }; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3006 | use rusqlite::NO_PARAMS; |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 3007 | use rusqlite::{Error, TransactionBehavior}; |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3008 | use std::cell::RefCell; |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 3009 | use std::sync::atomic::{AtomicU8, Ordering}; |
| 3010 | use std::sync::Arc; |
| 3011 | use std::thread; |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 3012 | use std::time::{Duration, SystemTime}; |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3013 | #[cfg(disabled)] |
| 3014 | use std::time::Instant; |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3015 | |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 3016 | fn new_test_db() -> Result<KeystoreDB> { |
| 3017 | let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?; |
| 3018 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3019 | let mut db = KeystoreDB { conn, gc: None }; |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3020 | db.with_transaction(TransactionBehavior::Immediate, |tx| { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3021 | KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc() |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3022 | })?; |
| 3023 | Ok(db) |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 3024 | } |
| 3025 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3026 | fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB> |
| 3027 | where |
| 3028 | F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static, |
| 3029 | { |
Paul Crowley | e8826e5 | 2021-03-31 08:33:53 -0700 | [diff] [blame] | 3030 | let super_key: Arc<SuperKeyManager> = Default::default(); |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 3031 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3032 | let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection."); |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 3033 | let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key)); |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3034 | |
| 3035 | KeystoreDB::new(path, Some(gc)) |
| 3036 | } |
| 3037 | |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 3038 | fn rebind_alias( |
| 3039 | db: &mut KeystoreDB, |
| 3040 | newid: &KeyIdGuard, |
| 3041 | alias: &str, |
| 3042 | domain: Domain, |
| 3043 | namespace: i64, |
| 3044 | ) -> Result<bool> { |
| 3045 | db.with_transaction(TransactionBehavior::Immediate, |tx| { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3046 | KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc() |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 3047 | }) |
| 3048 | .context("In rebind_alias.") |
| 3049 | } |
| 3050 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 3051 | #[test] |
| 3052 | fn datetime() -> Result<()> { |
| 3053 | let conn = Connection::open_in_memory()?; |
| 3054 | conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?; |
| 3055 | let now = SystemTime::now(); |
| 3056 | let duration = Duration::from_secs(1000); |
| 3057 | let then = now.checked_sub(duration).unwrap(); |
| 3058 | let soon = now.checked_add(duration).unwrap(); |
| 3059 | conn.execute( |
| 3060 | "INSERT INTO test (ts) VALUES (?), (?), (?);", |
| 3061 | params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?], |
| 3062 | )?; |
| 3063 | let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?; |
| 3064 | let mut rows = stmt.query(NO_PARAMS)?; |
| 3065 | assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?); |
| 3066 | assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?); |
| 3067 | assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?); |
| 3068 | assert!(rows.next()?.is_none()); |
| 3069 | assert!(DateTime::try_from(then)? < DateTime::try_from(now)?); |
| 3070 | assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?); |
| 3071 | assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?); |
| 3072 | Ok(()) |
| 3073 | } |
| 3074 | |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3075 | // Ensure that we're using the "injected" random function, not the real one. |
| 3076 | #[test] |
| 3077 | fn test_mocked_random() { |
| 3078 | let rand1 = random(); |
| 3079 | let rand2 = random(); |
| 3080 | let rand3 = random(); |
| 3081 | if rand1 == rand2 { |
| 3082 | assert_eq!(rand2 + 1, rand3); |
| 3083 | } else { |
| 3084 | assert_eq!(rand1 + 1, rand2); |
| 3085 | assert_eq!(rand2, rand3); |
| 3086 | } |
| 3087 | } |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 3088 | |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 3089 | // Test that we have the correct tables. |
| 3090 | #[test] |
| 3091 | fn test_tables() -> Result<()> { |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 3092 | let db = new_test_db()?; |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 3093 | let tables = db |
| 3094 | .conn |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 3095 | .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] | 3096 | .query_map(params![], |row| row.get(0))? |
| 3097 | .collect::<rusqlite::Result<Vec<String>>>()?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3098 | assert_eq!(tables.len(), 6); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3099 | assert_eq!(tables[0], "blobentry"); |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3100 | assert_eq!(tables[1], "blobmetadata"); |
| 3101 | assert_eq!(tables[2], "grant"); |
| 3102 | assert_eq!(tables[3], "keyentry"); |
| 3103 | assert_eq!(tables[4], "keymetadata"); |
| 3104 | assert_eq!(tables[5], "keyparameter"); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3105 | let tables = db |
| 3106 | .conn |
| 3107 | .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")? |
| 3108 | .query_map(params![], |row| row.get(0))? |
| 3109 | .collect::<rusqlite::Result<Vec<String>>>()?; |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 3110 | |
| 3111 | assert_eq!(tables.len(), 2); |
| 3112 | assert_eq!(tables[0], "authtoken"); |
| 3113 | assert_eq!(tables[1], "metadata"); |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 3114 | Ok(()) |
| 3115 | } |
| 3116 | |
| 3117 | #[test] |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 3118 | fn test_auth_token_table_invariant() -> Result<()> { |
| 3119 | let mut db = new_test_db()?; |
| 3120 | let auth_token1 = HardwareAuthToken { |
| 3121 | challenge: i64::MAX, |
| 3122 | userId: 200, |
| 3123 | authenticatorId: 200, |
| 3124 | authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0), |
| 3125 | timestamp: Timestamp { milliSeconds: 500 }, |
| 3126 | mac: String::from("mac").into_bytes(), |
| 3127 | }; |
| 3128 | db.insert_auth_token(&auth_token1)?; |
| 3129 | let auth_tokens_returned = get_auth_tokens(&mut db)?; |
| 3130 | assert_eq!(auth_tokens_returned.len(), 1); |
| 3131 | |
| 3132 | // insert another auth token with the same values for the columns in the UNIQUE constraint |
| 3133 | // of the auth token table and different value for timestamp |
| 3134 | let auth_token2 = HardwareAuthToken { |
| 3135 | challenge: i64::MAX, |
| 3136 | userId: 200, |
| 3137 | authenticatorId: 200, |
| 3138 | authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0), |
| 3139 | timestamp: Timestamp { milliSeconds: 600 }, |
| 3140 | mac: String::from("mac").into_bytes(), |
| 3141 | }; |
| 3142 | |
| 3143 | db.insert_auth_token(&auth_token2)?; |
| 3144 | let mut auth_tokens_returned = get_auth_tokens(&mut db)?; |
| 3145 | assert_eq!(auth_tokens_returned.len(), 1); |
| 3146 | |
| 3147 | if let Some(auth_token) = auth_tokens_returned.pop() { |
| 3148 | assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600); |
| 3149 | } |
| 3150 | |
| 3151 | // insert another auth token with the different values for the columns in the UNIQUE |
| 3152 | // constraint of the auth token table |
| 3153 | let auth_token3 = HardwareAuthToken { |
| 3154 | challenge: i64::MAX, |
| 3155 | userId: 201, |
| 3156 | authenticatorId: 200, |
| 3157 | authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0), |
| 3158 | timestamp: Timestamp { milliSeconds: 600 }, |
| 3159 | mac: String::from("mac").into_bytes(), |
| 3160 | }; |
| 3161 | |
| 3162 | db.insert_auth_token(&auth_token3)?; |
| 3163 | let auth_tokens_returned = get_auth_tokens(&mut db)?; |
| 3164 | assert_eq!(auth_tokens_returned.len(), 2); |
| 3165 | |
| 3166 | Ok(()) |
| 3167 | } |
| 3168 | |
| 3169 | // utility function for test_auth_token_table_invariant() |
| 3170 | fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> { |
| 3171 | let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?; |
| 3172 | |
| 3173 | let auth_token_entries: Vec<AuthTokenEntry> = stmt |
| 3174 | .query_map(NO_PARAMS, |row| { |
| 3175 | Ok(AuthTokenEntry::new( |
| 3176 | HardwareAuthToken { |
| 3177 | challenge: row.get(1)?, |
| 3178 | userId: row.get(2)?, |
| 3179 | authenticatorId: row.get(3)?, |
| 3180 | authenticatorType: HardwareAuthenticatorType(row.get(4)?), |
| 3181 | timestamp: Timestamp { milliSeconds: row.get(5)? }, |
| 3182 | mac: row.get(6)?, |
| 3183 | }, |
| 3184 | row.get(7)?, |
| 3185 | )) |
| 3186 | })? |
| 3187 | .collect::<Result<Vec<AuthTokenEntry>, Error>>()?; |
| 3188 | Ok(auth_token_entries) |
| 3189 | } |
| 3190 | |
| 3191 | #[test] |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 3192 | fn test_persistence_for_files() -> Result<()> { |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 3193 | let temp_dir = TempDir::new("persistent_db_test")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3194 | let mut db = KeystoreDB::new(temp_dir.path(), None)?; |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 3195 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3196 | db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?; |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 3197 | let entries = get_keyentry(&db)?; |
| 3198 | assert_eq!(entries.len(), 1); |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 3199 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3200 | let db = KeystoreDB::new(temp_dir.path(), None)?; |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 3201 | |
| 3202 | let entries_new = get_keyentry(&db)?; |
| 3203 | assert_eq!(entries, entries_new); |
| 3204 | Ok(()) |
| 3205 | } |
| 3206 | |
| 3207 | #[test] |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3208 | fn test_create_key_entry() -> Result<()> { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3209 | fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) { |
| 3210 | (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] | 3211 | } |
| 3212 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3213 | let mut db = new_test_db()?; |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3214 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3215 | db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?; |
| 3216 | db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?; |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3217 | |
| 3218 | let entries = get_keyentry(&db)?; |
| 3219 | assert_eq!(entries.len(), 2); |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3220 | assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID)); |
| 3221 | assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID)); |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3222 | |
| 3223 | // Test that we must pass in a valid Domain. |
| 3224 | check_result_is_error_containing_string( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3225 | db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID), |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3226 | "Domain Domain(1) must be either App or SELinux.", |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3227 | ); |
| 3228 | check_result_is_error_containing_string( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3229 | db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID), |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3230 | "Domain Domain(3) must be either App or SELinux.", |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3231 | ); |
| 3232 | check_result_is_error_containing_string( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3233 | db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID), |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3234 | "Domain Domain(4) must be either App or SELinux.", |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 3235 | ); |
| 3236 | |
| 3237 | Ok(()) |
| 3238 | } |
| 3239 | |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 3240 | #[test] |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 3241 | fn test_add_unsigned_key() -> Result<()> { |
| 3242 | let mut db = new_test_db()?; |
| 3243 | let public_key: Vec<u8> = vec![0x01, 0x02, 0x03]; |
| 3244 | let private_key: Vec<u8> = vec![0x04, 0x05, 0x06]; |
| 3245 | let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09]; |
| 3246 | db.create_attestation_key_entry( |
| 3247 | &public_key, |
| 3248 | &raw_public_key, |
| 3249 | &private_key, |
| 3250 | &KEYSTORE_UUID, |
| 3251 | )?; |
| 3252 | let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?; |
| 3253 | assert_eq!(keys.len(), 1); |
| 3254 | assert_eq!(keys[0], public_key); |
| 3255 | Ok(()) |
| 3256 | } |
| 3257 | |
| 3258 | #[test] |
| 3259 | fn test_store_signed_attestation_certificate_chain() -> Result<()> { |
| 3260 | let mut db = new_test_db()?; |
| 3261 | let expiration_date: i64 = 20; |
| 3262 | let namespace: i64 = 30; |
| 3263 | let base_byte: u8 = 1; |
| 3264 | let loaded_values = |
| 3265 | load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?; |
| 3266 | let chain = |
| 3267 | db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?; |
| 3268 | assert_eq!(true, chain.is_some()); |
| 3269 | let cert_chain = chain.unwrap(); |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 3270 | assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key); |
Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 3271 | assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert); |
| 3272 | assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain); |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 3273 | Ok(()) |
| 3274 | } |
| 3275 | |
| 3276 | #[test] |
| 3277 | fn test_get_attestation_pool_status() -> Result<()> { |
| 3278 | let mut db = new_test_db()?; |
| 3279 | let namespace: i64 = 30; |
| 3280 | load_attestation_key_pool( |
| 3281 | &mut db, 10, /* expiration */ |
| 3282 | namespace, 0x01, /* base_byte */ |
| 3283 | )?; |
| 3284 | load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?; |
| 3285 | load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?; |
| 3286 | let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?; |
| 3287 | assert_eq!(status.expiring, 0); |
| 3288 | assert_eq!(status.attested, 3); |
| 3289 | assert_eq!(status.unassigned, 0); |
| 3290 | assert_eq!(status.total, 3); |
| 3291 | assert_eq!( |
| 3292 | db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring, |
| 3293 | 1 |
| 3294 | ); |
| 3295 | assert_eq!( |
| 3296 | db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring, |
| 3297 | 2 |
| 3298 | ); |
| 3299 | assert_eq!( |
| 3300 | db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring, |
| 3301 | 3 |
| 3302 | ); |
| 3303 | let public_key: Vec<u8> = vec![0x01, 0x02, 0x03]; |
| 3304 | let private_key: Vec<u8> = vec![0x04, 0x05, 0x06]; |
| 3305 | let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09]; |
| 3306 | let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c]; |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 3307 | let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f]; |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 3308 | db.create_attestation_key_entry( |
| 3309 | &public_key, |
| 3310 | &raw_public_key, |
| 3311 | &private_key, |
| 3312 | &KEYSTORE_UUID, |
| 3313 | )?; |
| 3314 | status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?; |
| 3315 | assert_eq!(status.attested, 3); |
| 3316 | assert_eq!(status.unassigned, 0); |
| 3317 | assert_eq!(status.total, 4); |
| 3318 | db.store_signed_attestation_certificate_chain( |
| 3319 | &raw_public_key, |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 3320 | &batch_cert, |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 3321 | &cert_chain, |
| 3322 | 20, |
| 3323 | &KEYSTORE_UUID, |
| 3324 | )?; |
| 3325 | status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?; |
| 3326 | assert_eq!(status.attested, 4); |
| 3327 | assert_eq!(status.unassigned, 1); |
| 3328 | assert_eq!(status.total, 4); |
| 3329 | Ok(()) |
| 3330 | } |
| 3331 | |
| 3332 | #[test] |
| 3333 | fn test_remove_expired_certs() -> Result<()> { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3334 | let temp_dir = |
| 3335 | TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir."); |
| 3336 | let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?; |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 3337 | let expiration_date: i64 = |
| 3338 | SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000; |
| 3339 | let namespace: i64 = 30; |
| 3340 | let namespace_del1: i64 = 45; |
| 3341 | let namespace_del2: i64 = 60; |
| 3342 | let entry_values = load_attestation_key_pool( |
| 3343 | &mut db, |
| 3344 | expiration_date, |
| 3345 | namespace, |
| 3346 | 0x01, /* base_byte */ |
| 3347 | )?; |
| 3348 | load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?; |
| 3349 | load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3350 | |
| 3351 | let blob_entry_row_count: u32 = db |
| 3352 | .conn |
| 3353 | .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0)) |
| 3354 | .expect("Failed to get blob entry row count."); |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 3355 | // We expect 9 rows here because there are three blobs per attestation key, i.e., |
| 3356 | // one key, one certificate chain, and one certificate. |
| 3357 | assert_eq!(blob_entry_row_count, 9); |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3358 | |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 3359 | assert_eq!(db.delete_expired_attestation_keys()?, 2); |
| 3360 | |
| 3361 | let mut cert_chain = |
| 3362 | db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3363 | assert!(cert_chain.is_some()); |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 3364 | let value = cert_chain.unwrap(); |
Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 3365 | assert_eq!(entry_values.batch_cert, value.batch_cert); |
| 3366 | assert_eq!(entry_values.cert_chain, value.cert_chain); |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 3367 | assert_eq!(entry_values.priv_key, value.private_key.to_vec()); |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 3368 | |
| 3369 | cert_chain = db.retrieve_attestation_key_and_cert_chain( |
| 3370 | Domain::APP, |
| 3371 | namespace_del1, |
| 3372 | &KEYSTORE_UUID, |
| 3373 | )?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3374 | assert!(!cert_chain.is_some()); |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 3375 | cert_chain = db.retrieve_attestation_key_and_cert_chain( |
| 3376 | Domain::APP, |
| 3377 | namespace_del2, |
| 3378 | &KEYSTORE_UUID, |
| 3379 | )?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3380 | assert!(!cert_chain.is_some()); |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 3381 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3382 | // Give the garbage collector half a second to catch up. |
| 3383 | std::thread::sleep(Duration::from_millis(500)); |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 3384 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3385 | let blob_entry_row_count: u32 = db |
| 3386 | .conn |
| 3387 | .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0)) |
| 3388 | .expect("Failed to get blob entry row count."); |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 3389 | // There shound be 3 blob entries left, because we deleted two of the attestation |
| 3390 | // key entries with three blobs each. |
| 3391 | assert_eq!(blob_entry_row_count, 3); |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 3392 | |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 3393 | Ok(()) |
| 3394 | } |
| 3395 | |
| 3396 | #[test] |
Max Bires | 60d7ed1 | 2021-03-05 15:59:22 -0800 | [diff] [blame] | 3397 | fn test_delete_all_attestation_keys() -> Result<()> { |
| 3398 | let mut db = new_test_db()?; |
| 3399 | load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?; |
| 3400 | load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?; |
| 3401 | db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?; |
| 3402 | let result = db.delete_all_attestation_keys()?; |
| 3403 | |
| 3404 | // Give the garbage collector half a second to catch up. |
| 3405 | std::thread::sleep(Duration::from_millis(500)); |
| 3406 | |
| 3407 | // Attestation keys should be deleted, and the regular key should remain. |
| 3408 | assert_eq!(result, 2); |
| 3409 | |
| 3410 | Ok(()) |
| 3411 | } |
| 3412 | |
| 3413 | #[test] |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 3414 | fn test_rebind_alias() -> Result<()> { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3415 | fn extractor( |
| 3416 | ke: &KeyEntryRow, |
| 3417 | ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) { |
| 3418 | (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid) |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 3419 | } |
| 3420 | |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 3421 | let mut db = new_test_db()?; |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3422 | db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?; |
| 3423 | db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?; |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 3424 | let entries = get_keyentry(&db)?; |
| 3425 | assert_eq!(entries.len(), 2); |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3426 | assert_eq!( |
| 3427 | extractor(&entries[0]), |
| 3428 | (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID)) |
| 3429 | ); |
| 3430 | assert_eq!( |
| 3431 | extractor(&entries[1]), |
| 3432 | (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID)) |
| 3433 | ); |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 3434 | |
| 3435 | // Test that the first call to rebind_alias sets the alias. |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 3436 | 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] | 3437 | let entries = get_keyentry(&db)?; |
| 3438 | assert_eq!(entries.len(), 2); |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3439 | assert_eq!( |
| 3440 | extractor(&entries[0]), |
| 3441 | (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID)) |
| 3442 | ); |
| 3443 | assert_eq!( |
| 3444 | extractor(&entries[1]), |
| 3445 | (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID)) |
| 3446 | ); |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 3447 | |
| 3448 | // 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] | 3449 | 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] | 3450 | let entries = get_keyentry(&db)?; |
| 3451 | assert_eq!(entries.len(), 2); |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3452 | assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID))); |
| 3453 | assert_eq!( |
| 3454 | extractor(&entries[1]), |
| 3455 | (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID)) |
| 3456 | ); |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 3457 | |
| 3458 | // Test that we must pass in a valid Domain. |
| 3459 | check_result_is_error_containing_string( |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 3460 | 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] | 3461 | "Domain Domain(1) must be either App or SELinux.", |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 3462 | ); |
| 3463 | check_result_is_error_containing_string( |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 3464 | 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] | 3465 | "Domain Domain(3) must be either App or SELinux.", |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 3466 | ); |
| 3467 | check_result_is_error_containing_string( |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 3468 | 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] | 3469 | "Domain Domain(4) must be either App or SELinux.", |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 3470 | ); |
| 3471 | |
| 3472 | // Test that we correctly handle setting an alias for something that does not exist. |
| 3473 | check_result_is_error_containing_string( |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 3474 | 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] | 3475 | "Expected to update a single entry but instead updated 0", |
| 3476 | ); |
| 3477 | // Test that we correctly abort the transaction in this case. |
| 3478 | let entries = get_keyentry(&db)?; |
| 3479 | assert_eq!(entries.len(), 2); |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3480 | assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID))); |
| 3481 | assert_eq!( |
| 3482 | extractor(&entries[1]), |
| 3483 | (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID)) |
| 3484 | ); |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 3485 | |
| 3486 | Ok(()) |
| 3487 | } |
| 3488 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3489 | #[test] |
| 3490 | fn test_grant_ungrant() -> Result<()> { |
| 3491 | const CALLER_UID: u32 = 15; |
| 3492 | const GRANTEE_UID: u32 = 12; |
| 3493 | const SELINUX_NAMESPACE: i64 = 7; |
| 3494 | |
| 3495 | let mut db = new_test_db()?; |
| 3496 | db.conn.execute( |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3497 | "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid) |
| 3498 | VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);", |
| 3499 | params![KEYSTORE_UUID, KEYSTORE_UUID], |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3500 | )?; |
| 3501 | let app_key = KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3502 | domain: super::Domain::APP, |
| 3503 | nspace: 0, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3504 | alias: Some("key".to_string()), |
| 3505 | blob: None, |
| 3506 | }; |
| 3507 | const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()]; |
| 3508 | const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()]; |
| 3509 | |
| 3510 | // Reset totally predictable random number generator in case we |
| 3511 | // are not the first test running on this thread. |
| 3512 | reset_random(); |
| 3513 | let next_random = 0i64; |
| 3514 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3515 | let app_granted_key = db |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3516 | .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| { |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3517 | assert_eq!(*a, PVEC1); |
| 3518 | assert_eq!( |
| 3519 | *k, |
| 3520 | KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3521 | domain: super::Domain::APP, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3522 | // namespace must be set to the caller_uid. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3523 | nspace: CALLER_UID as i64, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3524 | alias: Some("key".to_string()), |
| 3525 | blob: None, |
| 3526 | } |
| 3527 | ); |
| 3528 | Ok(()) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3529 | }) |
| 3530 | .unwrap(); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3531 | |
| 3532 | assert_eq!( |
| 3533 | app_granted_key, |
| 3534 | KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3535 | domain: super::Domain::GRANT, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3536 | // The grantid is next_random due to the mock random number generator. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3537 | nspace: next_random, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3538 | alias: None, |
| 3539 | blob: None, |
| 3540 | } |
| 3541 | ); |
| 3542 | |
| 3543 | let selinux_key = KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3544 | domain: super::Domain::SELINUX, |
| 3545 | nspace: SELINUX_NAMESPACE, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3546 | alias: Some("yek".to_string()), |
| 3547 | blob: None, |
| 3548 | }; |
| 3549 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3550 | let selinux_granted_key = db |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3551 | .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| { |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3552 | assert_eq!(*a, PVEC1); |
| 3553 | assert_eq!( |
| 3554 | *k, |
| 3555 | KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3556 | domain: super::Domain::SELINUX, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3557 | // namespace must be the supplied SELinux |
| 3558 | // namespace. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3559 | nspace: SELINUX_NAMESPACE, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3560 | alias: Some("yek".to_string()), |
| 3561 | blob: None, |
| 3562 | } |
| 3563 | ); |
| 3564 | Ok(()) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3565 | }) |
| 3566 | .unwrap(); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3567 | |
| 3568 | assert_eq!( |
| 3569 | selinux_granted_key, |
| 3570 | KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3571 | domain: super::Domain::GRANT, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3572 | // 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] | 3573 | nspace: next_random + 1, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3574 | alias: None, |
| 3575 | blob: None, |
| 3576 | } |
| 3577 | ); |
| 3578 | |
| 3579 | // This should update the existing grant with PVEC2. |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3580 | let selinux_granted_key = db |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3581 | .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| { |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3582 | assert_eq!(*a, PVEC2); |
| 3583 | assert_eq!( |
| 3584 | *k, |
| 3585 | KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3586 | domain: super::Domain::SELINUX, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3587 | // namespace must be the supplied SELinux |
| 3588 | // namespace. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3589 | nspace: SELINUX_NAMESPACE, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3590 | alias: Some("yek".to_string()), |
| 3591 | blob: None, |
| 3592 | } |
| 3593 | ); |
| 3594 | Ok(()) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3595 | }) |
| 3596 | .unwrap(); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3597 | |
| 3598 | assert_eq!( |
| 3599 | selinux_granted_key, |
| 3600 | KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3601 | domain: super::Domain::GRANT, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3602 | // Same grant id as before. The entry was only updated. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3603 | nspace: next_random + 1, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3604 | alias: None, |
| 3605 | blob: None, |
| 3606 | } |
| 3607 | ); |
| 3608 | |
| 3609 | { |
| 3610 | // Limiting scope of stmt, because it borrows db. |
| 3611 | let mut stmt = db |
| 3612 | .conn |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 3613 | .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?; |
Janis Danisevskis | ee10b5f | 2020-09-22 16:42:35 -0700 | [diff] [blame] | 3614 | let mut rows = |
| 3615 | stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| { |
| 3616 | Ok(( |
| 3617 | row.get(0)?, |
| 3618 | row.get(1)?, |
| 3619 | row.get(2)?, |
| 3620 | KeyPermSet::from(row.get::<_, i32>(3)?), |
| 3621 | )) |
| 3622 | })?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3623 | |
| 3624 | let r = rows.next().unwrap().unwrap(); |
Janis Danisevskis | ee10b5f | 2020-09-22 16:42:35 -0700 | [diff] [blame] | 3625 | assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1)); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3626 | let r = rows.next().unwrap().unwrap(); |
Janis Danisevskis | ee10b5f | 2020-09-22 16:42:35 -0700 | [diff] [blame] | 3627 | assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2)); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3628 | assert!(rows.next().is_none()); |
| 3629 | } |
| 3630 | |
| 3631 | debug_dump_keyentry_table(&mut db)?; |
| 3632 | println!("app_key {:?}", app_key); |
| 3633 | println!("selinux_key {:?}", selinux_key); |
| 3634 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3635 | db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?; |
| 3636 | db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3637 | |
| 3638 | Ok(()) |
| 3639 | } |
| 3640 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 3641 | static TEST_KEY_BLOB: &[u8] = b"my test blob"; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3642 | static TEST_CERT_BLOB: &[u8] = b"my test cert"; |
| 3643 | static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain"; |
| 3644 | |
| 3645 | #[test] |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 3646 | fn test_set_blob() -> Result<()> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3647 | let key_id = KEY_ID_LOCK.get(3000); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3648 | let mut db = new_test_db()?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3649 | let mut blob_metadata = BlobMetaData::new(); |
| 3650 | blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID)); |
| 3651 | db.set_blob( |
| 3652 | &key_id, |
| 3653 | SubComponentType::KEY_BLOB, |
| 3654 | Some(TEST_KEY_BLOB), |
| 3655 | Some(&blob_metadata), |
| 3656 | )?; |
| 3657 | db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?; |
| 3658 | db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3659 | drop(key_id); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3660 | |
| 3661 | let mut stmt = db.conn.prepare( |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3662 | "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3663 | ORDER BY subcomponent_type ASC;", |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3664 | )?; |
| 3665 | let mut rows = stmt |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3666 | .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| { |
| 3667 | Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?)) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3668 | })?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3669 | let (r, id) = rows.next().unwrap().unwrap(); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3670 | assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec())); |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3671 | let (r, _) = rows.next().unwrap().unwrap(); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3672 | assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec())); |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3673 | let (r, _) = rows.next().unwrap().unwrap(); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3674 | 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] | 3675 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 3676 | drop(rows); |
| 3677 | drop(stmt); |
| 3678 | |
| 3679 | assert_eq!( |
| 3680 | db.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 3681 | BlobMetaData::load_from_db(id, tx).no_gc() |
| 3682 | }) |
| 3683 | .expect("Should find blob metadata."), |
| 3684 | blob_metadata |
| 3685 | ); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3686 | Ok(()) |
| 3687 | } |
| 3688 | |
| 3689 | static TEST_ALIAS: &str = "my super duper key"; |
| 3690 | |
| 3691 | #[test] |
| 3692 | fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> { |
| 3693 | let mut db = new_test_db()?; |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3694 | 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] | 3695 | .context("test_insert_and_load_full_keyentry_domain_app")? |
| 3696 | .0; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3697 | let (_key_guard, key_entry) = db |
| 3698 | .load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3699 | &KeyDescriptor { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3700 | domain: Domain::APP, |
| 3701 | nspace: 0, |
| 3702 | alias: Some(TEST_ALIAS.to_string()), |
| 3703 | blob: None, |
| 3704 | }, |
| 3705 | KeyType::Client, |
| 3706 | KeyEntryLoadBits::BOTH, |
| 3707 | 1, |
| 3708 | |_k, _av| Ok(()), |
| 3709 | ) |
| 3710 | .unwrap(); |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3711 | 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] | 3712 | |
| 3713 | db.unbind_key( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3714 | &KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3715 | domain: Domain::APP, |
| 3716 | nspace: 0, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3717 | alias: Some(TEST_ALIAS.to_string()), |
| 3718 | blob: None, |
| 3719 | }, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 3720 | KeyType::Client, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3721 | 1, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3722 | |_, _| Ok(()), |
| 3723 | ) |
| 3724 | .unwrap(); |
| 3725 | |
| 3726 | assert_eq!( |
| 3727 | Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)), |
| 3728 | db.load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3729 | &KeyDescriptor { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3730 | domain: Domain::APP, |
| 3731 | nspace: 0, |
| 3732 | alias: Some(TEST_ALIAS.to_string()), |
| 3733 | blob: None, |
| 3734 | }, |
| 3735 | KeyType::Client, |
| 3736 | KeyEntryLoadBits::NONE, |
| 3737 | 1, |
| 3738 | |_k, _av| Ok(()), |
| 3739 | ) |
| 3740 | .unwrap_err() |
| 3741 | .root_cause() |
| 3742 | .downcast_ref::<KsError>() |
| 3743 | ); |
| 3744 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3745 | Ok(()) |
| 3746 | } |
| 3747 | |
| 3748 | #[test] |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 3749 | fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> { |
| 3750 | let mut db = new_test_db()?; |
| 3751 | |
| 3752 | db.store_new_certificate( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3753 | &KeyDescriptor { |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 3754 | domain: Domain::APP, |
| 3755 | nspace: 1, |
| 3756 | alias: Some(TEST_ALIAS.to_string()), |
| 3757 | blob: None, |
| 3758 | }, |
| 3759 | TEST_CERT_BLOB, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 3760 | &KEYSTORE_UUID, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 3761 | ) |
| 3762 | .expect("Trying to insert cert."); |
| 3763 | |
| 3764 | let (_key_guard, mut key_entry) = db |
| 3765 | .load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3766 | &KeyDescriptor { |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 3767 | domain: Domain::APP, |
| 3768 | nspace: 1, |
| 3769 | alias: Some(TEST_ALIAS.to_string()), |
| 3770 | blob: None, |
| 3771 | }, |
| 3772 | KeyType::Client, |
| 3773 | KeyEntryLoadBits::PUBLIC, |
| 3774 | 1, |
| 3775 | |_k, _av| Ok(()), |
| 3776 | ) |
| 3777 | .expect("Trying to read certificate entry."); |
| 3778 | |
| 3779 | assert!(key_entry.pure_cert()); |
| 3780 | assert!(key_entry.cert().is_none()); |
| 3781 | assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec())); |
| 3782 | |
| 3783 | db.unbind_key( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3784 | &KeyDescriptor { |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 3785 | domain: Domain::APP, |
| 3786 | nspace: 1, |
| 3787 | alias: Some(TEST_ALIAS.to_string()), |
| 3788 | blob: None, |
| 3789 | }, |
| 3790 | KeyType::Client, |
| 3791 | 1, |
| 3792 | |_, _| Ok(()), |
| 3793 | ) |
| 3794 | .unwrap(); |
| 3795 | |
| 3796 | assert_eq!( |
| 3797 | Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)), |
| 3798 | db.load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3799 | &KeyDescriptor { |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 3800 | domain: Domain::APP, |
| 3801 | nspace: 1, |
| 3802 | alias: Some(TEST_ALIAS.to_string()), |
| 3803 | blob: None, |
| 3804 | }, |
| 3805 | KeyType::Client, |
| 3806 | KeyEntryLoadBits::NONE, |
| 3807 | 1, |
| 3808 | |_k, _av| Ok(()), |
| 3809 | ) |
| 3810 | .unwrap_err() |
| 3811 | .root_cause() |
| 3812 | .downcast_ref::<KsError>() |
| 3813 | ); |
| 3814 | |
| 3815 | Ok(()) |
| 3816 | } |
| 3817 | |
| 3818 | #[test] |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3819 | fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> { |
| 3820 | let mut db = new_test_db()?; |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3821 | 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] | 3822 | .context("test_insert_and_load_full_keyentry_domain_selinux")? |
| 3823 | .0; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3824 | let (_key_guard, key_entry) = db |
| 3825 | .load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3826 | &KeyDescriptor { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3827 | domain: Domain::SELINUX, |
| 3828 | nspace: 1, |
| 3829 | alias: Some(TEST_ALIAS.to_string()), |
| 3830 | blob: None, |
| 3831 | }, |
| 3832 | KeyType::Client, |
| 3833 | KeyEntryLoadBits::BOTH, |
| 3834 | 1, |
| 3835 | |_k, _av| Ok(()), |
| 3836 | ) |
| 3837 | .unwrap(); |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3838 | 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] | 3839 | |
| 3840 | db.unbind_key( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3841 | &KeyDescriptor { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 3842 | domain: Domain::SELINUX, |
| 3843 | nspace: 1, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3844 | alias: Some(TEST_ALIAS.to_string()), |
| 3845 | blob: None, |
| 3846 | }, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 3847 | KeyType::Client, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3848 | 1, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3849 | |_, _| Ok(()), |
| 3850 | ) |
| 3851 | .unwrap(); |
| 3852 | |
| 3853 | assert_eq!( |
| 3854 | Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)), |
| 3855 | db.load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3856 | &KeyDescriptor { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3857 | domain: Domain::SELINUX, |
| 3858 | nspace: 1, |
| 3859 | alias: Some(TEST_ALIAS.to_string()), |
| 3860 | blob: None, |
| 3861 | }, |
| 3862 | KeyType::Client, |
| 3863 | KeyEntryLoadBits::NONE, |
| 3864 | 1, |
| 3865 | |_k, _av| Ok(()), |
| 3866 | ) |
| 3867 | .unwrap_err() |
| 3868 | .root_cause() |
| 3869 | .downcast_ref::<KsError>() |
| 3870 | ); |
| 3871 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3872 | Ok(()) |
| 3873 | } |
| 3874 | |
| 3875 | #[test] |
| 3876 | fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> { |
| 3877 | let mut db = new_test_db()?; |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3878 | 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] | 3879 | .context("test_insert_and_load_full_keyentry_domain_key_id")? |
| 3880 | .0; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3881 | let (_, key_entry) = db |
| 3882 | .load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3883 | &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None }, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3884 | KeyType::Client, |
| 3885 | KeyEntryLoadBits::BOTH, |
| 3886 | 1, |
| 3887 | |_k, _av| Ok(()), |
| 3888 | ) |
| 3889 | .unwrap(); |
| 3890 | |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3891 | 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] | 3892 | |
| 3893 | db.unbind_key( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3894 | &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None }, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 3895 | KeyType::Client, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3896 | 1, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3897 | |_, _| Ok(()), |
| 3898 | ) |
| 3899 | .unwrap(); |
| 3900 | |
| 3901 | assert_eq!( |
| 3902 | Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)), |
| 3903 | db.load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3904 | &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None }, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3905 | KeyType::Client, |
| 3906 | KeyEntryLoadBits::NONE, |
| 3907 | 1, |
| 3908 | |_k, _av| Ok(()), |
| 3909 | ) |
| 3910 | .unwrap_err() |
| 3911 | .root_cause() |
| 3912 | .downcast_ref::<KsError>() |
| 3913 | ); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3914 | |
| 3915 | Ok(()) |
| 3916 | } |
| 3917 | |
| 3918 | #[test] |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3919 | fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> { |
| 3920 | let mut db = new_test_db()?; |
| 3921 | let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123)) |
| 3922 | .context("test_check_and_update_key_usage_count_with_limited_use_key")? |
| 3923 | .0; |
| 3924 | // Update the usage count of the limited use key. |
| 3925 | db.check_and_update_key_usage_count(key_id)?; |
| 3926 | |
| 3927 | let (_key_guard, key_entry) = db.load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3928 | &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None }, |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3929 | KeyType::Client, |
| 3930 | KeyEntryLoadBits::BOTH, |
| 3931 | 1, |
| 3932 | |_k, _av| Ok(()), |
| 3933 | )?; |
| 3934 | |
| 3935 | // The usage count is decremented now. |
| 3936 | assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122))); |
| 3937 | |
| 3938 | Ok(()) |
| 3939 | } |
| 3940 | |
| 3941 | #[test] |
| 3942 | fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> { |
| 3943 | let mut db = new_test_db()?; |
| 3944 | let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1)) |
| 3945 | .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")? |
| 3946 | .0; |
| 3947 | // Update the usage count of the limited use key. |
| 3948 | db.check_and_update_key_usage_count(key_id).expect(concat!( |
| 3949 | "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ", |
| 3950 | "This should succeed." |
| 3951 | )); |
| 3952 | |
| 3953 | // Try to update the exhausted limited use key. |
| 3954 | let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!( |
| 3955 | "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ", |
| 3956 | "This should fail." |
| 3957 | )); |
| 3958 | assert_eq!( |
| 3959 | &KsError::Km(ErrorCode::INVALID_KEY_BLOB), |
| 3960 | e.root_cause().downcast_ref::<KsError>().unwrap() |
| 3961 | ); |
| 3962 | |
| 3963 | Ok(()) |
| 3964 | } |
| 3965 | |
| 3966 | #[test] |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3967 | fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> { |
| 3968 | let mut db = new_test_db()?; |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3969 | 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] | 3970 | .context("test_insert_and_load_full_keyentry_from_grant")? |
| 3971 | .0; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3972 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3973 | let granted_key = db |
| 3974 | .grant( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3975 | &KeyDescriptor { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3976 | domain: Domain::APP, |
| 3977 | nspace: 0, |
| 3978 | alias: Some(TEST_ALIAS.to_string()), |
| 3979 | blob: None, |
| 3980 | }, |
| 3981 | 1, |
| 3982 | 2, |
| 3983 | key_perm_set![KeyPerm::use_()], |
| 3984 | |_k, _av| Ok(()), |
| 3985 | ) |
| 3986 | .unwrap(); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3987 | |
| 3988 | debug_dump_grant_table(&mut db)?; |
| 3989 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3990 | let (_key_guard, key_entry) = db |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 3991 | .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| { |
| 3992 | assert_eq!(Domain::GRANT, k.domain); |
| 3993 | assert!(av.unwrap().includes(KeyPerm::use_())); |
| 3994 | Ok(()) |
| 3995 | }) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 3996 | .unwrap(); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 3997 | |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 3998 | 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] | 3999 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 4000 | db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap(); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 4001 | |
| 4002 | assert_eq!( |
| 4003 | Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)), |
| 4004 | db.load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 4005 | &granted_key, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 4006 | KeyType::Client, |
| 4007 | KeyEntryLoadBits::NONE, |
| 4008 | 2, |
| 4009 | |_k, _av| Ok(()), |
| 4010 | ) |
| 4011 | .unwrap_err() |
| 4012 | .root_cause() |
| 4013 | .downcast_ref::<KsError>() |
| 4014 | ); |
| 4015 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 4016 | Ok(()) |
| 4017 | } |
| 4018 | |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 4019 | // This test attempts to load a key by key id while the caller is not the owner |
| 4020 | // but a grant exists for the given key and the caller. |
| 4021 | #[test] |
| 4022 | fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> { |
| 4023 | let mut db = new_test_db()?; |
| 4024 | const OWNER_UID: u32 = 1u32; |
| 4025 | const GRANTEE_UID: u32 = 2u32; |
| 4026 | const SOMEONE_ELSE_UID: u32 = 3u32; |
| 4027 | let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None) |
| 4028 | .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")? |
| 4029 | .0; |
| 4030 | |
| 4031 | db.grant( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 4032 | &KeyDescriptor { |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 4033 | domain: Domain::APP, |
| 4034 | nspace: 0, |
| 4035 | alias: Some(TEST_ALIAS.to_string()), |
| 4036 | blob: None, |
| 4037 | }, |
| 4038 | OWNER_UID, |
| 4039 | GRANTEE_UID, |
| 4040 | key_perm_set![KeyPerm::use_()], |
| 4041 | |_k, _av| Ok(()), |
| 4042 | ) |
| 4043 | .unwrap(); |
| 4044 | |
| 4045 | debug_dump_grant_table(&mut db)?; |
| 4046 | |
| 4047 | let id_descriptor = |
| 4048 | KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() }; |
| 4049 | |
| 4050 | let (_, key_entry) = db |
| 4051 | .load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 4052 | &id_descriptor, |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 4053 | KeyType::Client, |
| 4054 | KeyEntryLoadBits::BOTH, |
| 4055 | GRANTEE_UID, |
| 4056 | |k, av| { |
| 4057 | assert_eq!(Domain::APP, k.domain); |
| 4058 | assert_eq!(OWNER_UID as i64, k.nspace); |
| 4059 | assert!(av.unwrap().includes(KeyPerm::use_())); |
| 4060 | Ok(()) |
| 4061 | }, |
| 4062 | ) |
| 4063 | .unwrap(); |
| 4064 | |
| 4065 | assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None)); |
| 4066 | |
| 4067 | let (_, key_entry) = db |
| 4068 | .load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 4069 | &id_descriptor, |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 4070 | KeyType::Client, |
| 4071 | KeyEntryLoadBits::BOTH, |
| 4072 | SOMEONE_ELSE_UID, |
| 4073 | |k, av| { |
| 4074 | assert_eq!(Domain::APP, k.domain); |
| 4075 | assert_eq!(OWNER_UID as i64, k.nspace); |
| 4076 | assert!(av.is_none()); |
| 4077 | Ok(()) |
| 4078 | }, |
| 4079 | ) |
| 4080 | .unwrap(); |
| 4081 | |
| 4082 | assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None)); |
| 4083 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 4084 | db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap(); |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 4085 | |
| 4086 | assert_eq!( |
| 4087 | Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)), |
| 4088 | db.load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 4089 | &id_descriptor, |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 4090 | KeyType::Client, |
| 4091 | KeyEntryLoadBits::NONE, |
| 4092 | GRANTEE_UID, |
| 4093 | |_k, _av| Ok(()), |
| 4094 | ) |
| 4095 | .unwrap_err() |
| 4096 | .root_cause() |
| 4097 | .downcast_ref::<KsError>() |
| 4098 | ); |
| 4099 | |
| 4100 | Ok(()) |
| 4101 | } |
| 4102 | |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 4103 | static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key"; |
| 4104 | |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 4105 | #[test] |
| 4106 | fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> { |
| 4107 | let handle = { |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 4108 | let temp_dir = Arc::new(TempDir::new("id_lock_test")?); |
| 4109 | let temp_dir_clone = temp_dir.clone(); |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 4110 | let mut db = KeystoreDB::new(temp_dir.path(), None)?; |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 4111 | 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] | 4112 | .context("test_insert_and_load_full_keyentry_domain_app")? |
| 4113 | .0; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 4114 | let (_key_guard, key_entry) = db |
| 4115 | .load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 4116 | &KeyDescriptor { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 4117 | domain: Domain::APP, |
| 4118 | nspace: 0, |
| 4119 | alias: Some(KEY_LOCK_TEST_ALIAS.to_string()), |
| 4120 | blob: None, |
| 4121 | }, |
| 4122 | KeyType::Client, |
| 4123 | KeyEntryLoadBits::BOTH, |
| 4124 | 33, |
| 4125 | |_k, _av| Ok(()), |
| 4126 | ) |
| 4127 | .unwrap(); |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 4128 | 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] | 4129 | let state = Arc::new(AtomicU8::new(1)); |
| 4130 | let state2 = state.clone(); |
| 4131 | |
| 4132 | // Spawning a second thread that attempts to acquire the key id lock |
| 4133 | // for the same key as the primary thread. The primary thread then |
| 4134 | // waits, thereby forcing the secondary thread into the second stage |
| 4135 | // of acquiring the lock (see KEY ID LOCK 2/2 above). |
| 4136 | // The test succeeds if the secondary thread observes the transition |
| 4137 | // of `state` from 1 to 2, despite having a whole second to overtake |
| 4138 | // the primary thread. |
| 4139 | let handle = thread::spawn(move || { |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 4140 | let temp_dir = temp_dir_clone; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 4141 | let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap(); |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 4142 | assert!(db |
| 4143 | .load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 4144 | &KeyDescriptor { |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 4145 | domain: Domain::APP, |
| 4146 | nspace: 0, |
| 4147 | alias: Some(KEY_LOCK_TEST_ALIAS.to_string()), |
| 4148 | blob: None, |
| 4149 | }, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 4150 | KeyType::Client, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 4151 | KeyEntryLoadBits::BOTH, |
| 4152 | 33, |
| 4153 | |_k, _av| Ok(()), |
| 4154 | ) |
| 4155 | .is_ok()); |
| 4156 | // We should only see a 2 here because we can only return |
| 4157 | // from load_key_entry when the `_key_guard` expires, |
| 4158 | // which happens at the end of the scope. |
| 4159 | assert_eq!(2, state2.load(Ordering::Relaxed)); |
| 4160 | }); |
| 4161 | |
| 4162 | thread::sleep(std::time::Duration::from_millis(1000)); |
| 4163 | |
| 4164 | assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed)); |
| 4165 | |
| 4166 | // Return the handle from this scope so we can join with the |
| 4167 | // secondary thread after the key id lock has expired. |
| 4168 | handle |
| 4169 | // This is where the `_key_guard` goes out of scope, |
| 4170 | // which is the reason for concurrent load_key_entry on the same key |
| 4171 | // to unblock. |
| 4172 | }; |
| 4173 | // Join with the secondary thread and unwrap, to propagate failing asserts to the |
| 4174 | // main test thread. We will not see failing asserts in secondary threads otherwise. |
| 4175 | handle.join().unwrap(); |
| 4176 | Ok(()) |
| 4177 | } |
| 4178 | |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 4179 | #[test] |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 4180 | fn teset_database_busy_error_code() { |
| 4181 | let temp_dir = |
| 4182 | TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir."); |
| 4183 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 4184 | let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1."); |
| 4185 | let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2."); |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 4186 | |
| 4187 | let _tx1 = db1 |
| 4188 | .conn |
| 4189 | .transaction_with_behavior(TransactionBehavior::Immediate) |
| 4190 | .expect("Failed to create first transaction."); |
| 4191 | |
| 4192 | let error = db2 |
| 4193 | .conn |
| 4194 | .transaction_with_behavior(TransactionBehavior::Immediate) |
| 4195 | .context("Transaction begin failed.") |
| 4196 | .expect_err("This should fail."); |
| 4197 | let root_cause = error.root_cause(); |
| 4198 | if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) = |
| 4199 | root_cause.downcast_ref::<rusqlite::ffi::Error>() |
| 4200 | { |
| 4201 | return; |
| 4202 | } |
| 4203 | panic!( |
| 4204 | "Unexpected error {:?} \n{:?} \n{:?}", |
| 4205 | error, |
| 4206 | root_cause, |
| 4207 | root_cause.downcast_ref::<rusqlite::ffi::Error>() |
| 4208 | ) |
| 4209 | } |
| 4210 | |
| 4211 | #[cfg(disabled)] |
| 4212 | #[test] |
| 4213 | fn test_large_number_of_concurrent_db_manipulations() -> Result<()> { |
| 4214 | let temp_dir = Arc::new( |
| 4215 | TempDir::new("test_large_number_of_concurrent_db_manipulations_") |
| 4216 | .expect("Failed to create temp dir."), |
| 4217 | ); |
| 4218 | |
| 4219 | let test_begin = Instant::now(); |
| 4220 | |
| 4221 | let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database."); |
| 4222 | const KEY_COUNT: u32 = 500u32; |
| 4223 | const OPEN_DB_COUNT: u32 = 50u32; |
| 4224 | |
| 4225 | let mut actual_key_count = KEY_COUNT; |
| 4226 | // First insert KEY_COUNT keys. |
| 4227 | for count in 0..KEY_COUNT { |
| 4228 | if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) { |
| 4229 | actual_key_count = count; |
| 4230 | break; |
| 4231 | } |
| 4232 | let alias = format!("test_alias_{}", count); |
| 4233 | make_test_key_entry(&mut db, Domain::APP, 1, &alias, None) |
| 4234 | .expect("Failed to make key entry."); |
| 4235 | } |
| 4236 | |
| 4237 | // Insert more keys from a different thread and into a different namespace. |
| 4238 | let temp_dir1 = temp_dir.clone(); |
| 4239 | let handle1 = thread::spawn(move || { |
| 4240 | let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database."); |
| 4241 | |
| 4242 | for count in 0..actual_key_count { |
| 4243 | if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) { |
| 4244 | return; |
| 4245 | } |
| 4246 | let alias = format!("test_alias_{}", count); |
| 4247 | make_test_key_entry(&mut db, Domain::APP, 2, &alias, None) |
| 4248 | .expect("Failed to make key entry."); |
| 4249 | } |
| 4250 | |
| 4251 | // then unbind them again. |
| 4252 | for count in 0..actual_key_count { |
| 4253 | if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) { |
| 4254 | return; |
| 4255 | } |
| 4256 | let key = KeyDescriptor { |
| 4257 | domain: Domain::APP, |
| 4258 | nspace: -1, |
| 4259 | alias: Some(format!("test_alias_{}", count)), |
| 4260 | blob: None, |
| 4261 | }; |
| 4262 | db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed."); |
| 4263 | } |
| 4264 | }); |
| 4265 | |
| 4266 | // And start unbinding the first set of keys. |
| 4267 | let temp_dir2 = temp_dir.clone(); |
| 4268 | let handle2 = thread::spawn(move || { |
| 4269 | let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database."); |
| 4270 | |
| 4271 | for count in 0..actual_key_count { |
| 4272 | if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) { |
| 4273 | return; |
| 4274 | } |
| 4275 | let key = KeyDescriptor { |
| 4276 | domain: Domain::APP, |
| 4277 | nspace: -1, |
| 4278 | alias: Some(format!("test_alias_{}", count)), |
| 4279 | blob: None, |
| 4280 | }; |
| 4281 | db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed."); |
| 4282 | } |
| 4283 | }); |
| 4284 | |
| 4285 | let stop_deleting = Arc::new(AtomicU8::new(0)); |
| 4286 | let stop_deleting2 = stop_deleting.clone(); |
| 4287 | |
| 4288 | // And delete anything that is unreferenced keys. |
| 4289 | let temp_dir3 = temp_dir.clone(); |
| 4290 | let handle3 = thread::spawn(move || { |
| 4291 | let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database."); |
| 4292 | |
| 4293 | while stop_deleting2.load(Ordering::Relaxed) != 1 { |
| 4294 | while let Some((key_guard, _key)) = |
| 4295 | db.get_unreferenced_key().expect("Failed to get unreferenced Key.") |
| 4296 | { |
| 4297 | if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) { |
| 4298 | return; |
| 4299 | } |
| 4300 | db.purge_key_entry(key_guard).expect("Failed to purge key."); |
| 4301 | } |
| 4302 | std::thread::sleep(std::time::Duration::from_millis(100)); |
| 4303 | } |
| 4304 | }); |
| 4305 | |
| 4306 | // While a lot of inserting and deleting is going on we have to open database connections |
| 4307 | // successfully and use them. |
| 4308 | // This clone is not redundant, because temp_dir needs to be kept alive until db goes |
| 4309 | // out of scope. |
| 4310 | #[allow(clippy::redundant_clone)] |
| 4311 | let temp_dir4 = temp_dir.clone(); |
| 4312 | let handle4 = thread::spawn(move || { |
| 4313 | for count in 0..OPEN_DB_COUNT { |
| 4314 | if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) { |
| 4315 | return; |
| 4316 | } |
| 4317 | let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database."); |
| 4318 | |
| 4319 | let alias = format!("test_alias_{}", count); |
| 4320 | make_test_key_entry(&mut db, Domain::APP, 3, &alias, None) |
| 4321 | .expect("Failed to make key entry."); |
| 4322 | let key = KeyDescriptor { |
| 4323 | domain: Domain::APP, |
| 4324 | nspace: -1, |
| 4325 | alias: Some(alias), |
| 4326 | blob: None, |
| 4327 | }; |
| 4328 | db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed."); |
| 4329 | } |
| 4330 | }); |
| 4331 | |
| 4332 | handle1.join().expect("Thread 1 panicked."); |
| 4333 | handle2.join().expect("Thread 2 panicked."); |
| 4334 | handle4.join().expect("Thread 4 panicked."); |
| 4335 | |
| 4336 | stop_deleting.store(1, Ordering::Relaxed); |
| 4337 | handle3.join().expect("Thread 3 panicked."); |
| 4338 | |
| 4339 | Ok(()) |
| 4340 | } |
| 4341 | |
| 4342 | #[test] |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 4343 | fn list() -> Result<()> { |
| 4344 | let temp_dir = TempDir::new("list_test")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 4345 | let mut db = KeystoreDB::new(temp_dir.path(), None)?; |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 4346 | static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[ |
| 4347 | (Domain::APP, 1, "test1"), |
| 4348 | (Domain::APP, 1, "test2"), |
| 4349 | (Domain::APP, 1, "test3"), |
| 4350 | (Domain::APP, 1, "test4"), |
| 4351 | (Domain::APP, 1, "test5"), |
| 4352 | (Domain::APP, 1, "test6"), |
| 4353 | (Domain::APP, 1, "test7"), |
| 4354 | (Domain::APP, 2, "test1"), |
| 4355 | (Domain::APP, 2, "test2"), |
| 4356 | (Domain::APP, 2, "test3"), |
| 4357 | (Domain::APP, 2, "test4"), |
| 4358 | (Domain::APP, 2, "test5"), |
| 4359 | (Domain::APP, 2, "test6"), |
| 4360 | (Domain::APP, 2, "test8"), |
| 4361 | (Domain::SELINUX, 100, "test1"), |
| 4362 | (Domain::SELINUX, 100, "test2"), |
| 4363 | (Domain::SELINUX, 100, "test3"), |
| 4364 | (Domain::SELINUX, 100, "test4"), |
| 4365 | (Domain::SELINUX, 100, "test5"), |
| 4366 | (Domain::SELINUX, 100, "test6"), |
| 4367 | (Domain::SELINUX, 100, "test9"), |
| 4368 | ]; |
| 4369 | |
| 4370 | let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES |
| 4371 | .iter() |
| 4372 | .map(|(domain, ns, alias)| { |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 4373 | let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None) |
| 4374 | .unwrap_or_else(|e| { |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 4375 | panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e) |
| 4376 | }); |
| 4377 | (entry.id(), *ns) |
| 4378 | }) |
| 4379 | .collect(); |
| 4380 | |
| 4381 | for (domain, namespace) in |
| 4382 | &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)] |
| 4383 | { |
| 4384 | let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES |
| 4385 | .iter() |
| 4386 | .filter_map(|(domain, ns, alias)| match ns { |
| 4387 | ns if *ns == *namespace => Some(KeyDescriptor { |
| 4388 | domain: *domain, |
| 4389 | nspace: *ns, |
| 4390 | alias: Some(alias.to_string()), |
| 4391 | blob: None, |
| 4392 | }), |
| 4393 | _ => None, |
| 4394 | }) |
| 4395 | .collect(); |
| 4396 | list_o_descriptors.sort(); |
| 4397 | let mut list_result = db.list(*domain, *namespace)?; |
| 4398 | list_result.sort(); |
| 4399 | assert_eq!(list_o_descriptors, list_result); |
| 4400 | |
| 4401 | let mut list_o_ids: Vec<i64> = list_o_descriptors |
| 4402 | .into_iter() |
| 4403 | .map(|d| { |
| 4404 | let (_, entry) = db |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 4405 | .load_key_entry( |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 4406 | &d, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 4407 | KeyType::Client, |
| 4408 | KeyEntryLoadBits::NONE, |
| 4409 | *namespace as u32, |
| 4410 | |_, _| Ok(()), |
| 4411 | ) |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 4412 | .unwrap(); |
| 4413 | entry.id() |
| 4414 | }) |
| 4415 | .collect(); |
| 4416 | list_o_ids.sort_unstable(); |
| 4417 | let mut loaded_entries: Vec<i64> = list_o_keys |
| 4418 | .iter() |
| 4419 | .filter_map(|(id, ns)| match ns { |
| 4420 | ns if *ns == *namespace => Some(*id), |
| 4421 | _ => None, |
| 4422 | }) |
| 4423 | .collect(); |
| 4424 | loaded_entries.sort_unstable(); |
| 4425 | assert_eq!(list_o_ids, loaded_entries); |
| 4426 | } |
| 4427 | assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?); |
| 4428 | |
| 4429 | Ok(()) |
| 4430 | } |
| 4431 | |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 4432 | // Helpers |
| 4433 | |
| 4434 | // Checks that the given result is an error containing the given string. |
| 4435 | fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) { |
| 4436 | let error_str = format!( |
| 4437 | "{:#?}", |
| 4438 | result.err().unwrap_or_else(|| panic!("Expected the error: {}", target)) |
| 4439 | ); |
| 4440 | assert!( |
| 4441 | error_str.contains(target), |
| 4442 | "The string \"{}\" should contain \"{}\"", |
| 4443 | error_str, |
| 4444 | target |
| 4445 | ); |
| 4446 | } |
| 4447 | |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 4448 | #[derive(Debug, PartialEq)] |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 4449 | struct KeyEntryRow { |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 4450 | id: i64, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 4451 | key_type: KeyType, |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 4452 | domain: Option<Domain>, |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 4453 | namespace: Option<i64>, |
| 4454 | alias: Option<String>, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 4455 | state: KeyLifeCycle, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 4456 | km_uuid: Option<Uuid>, |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 4457 | } |
| 4458 | |
| 4459 | fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> { |
| 4460 | db.conn |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 4461 | .prepare("SELECT * FROM persistent.keyentry;")? |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 4462 | .query_map(NO_PARAMS, |row| { |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 4463 | Ok(KeyEntryRow { |
| 4464 | id: row.get(0)?, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 4465 | key_type: row.get(1)?, |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 4466 | domain: match row.get(2)? { |
| 4467 | Some(i) => Some(Domain(i)), |
| 4468 | None => None, |
| 4469 | }, |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 4470 | namespace: row.get(3)?, |
| 4471 | alias: row.get(4)?, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 4472 | state: row.get(5)?, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 4473 | km_uuid: row.get(6)?, |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 4474 | }) |
| 4475 | })? |
| 4476 | .map(|r| r.context("Could not read keyentry row.")) |
| 4477 | .collect::<Result<Vec<_>>>() |
| 4478 | } |
| 4479 | |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 4480 | struct RemoteProvValues { |
| 4481 | cert_chain: Vec<u8>, |
| 4482 | priv_key: Vec<u8>, |
| 4483 | batch_cert: Vec<u8>, |
| 4484 | } |
| 4485 | |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 4486 | fn load_attestation_key_pool( |
| 4487 | db: &mut KeystoreDB, |
| 4488 | expiration_date: i64, |
| 4489 | namespace: i64, |
| 4490 | base_byte: u8, |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 4491 | ) -> Result<RemoteProvValues> { |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 4492 | let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte]; |
| 4493 | let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte]; |
| 4494 | let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte]; |
| 4495 | let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte]; |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 4496 | let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e]; |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 4497 | db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?; |
| 4498 | db.store_signed_attestation_certificate_chain( |
| 4499 | &raw_public_key, |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 4500 | &batch_cert, |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 4501 | &cert_chain, |
| 4502 | expiration_date, |
| 4503 | &KEYSTORE_UUID, |
| 4504 | )?; |
| 4505 | db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?; |
Max Bires | b2e1d03 | 2021-02-08 21:35:05 -0800 | [diff] [blame] | 4506 | Ok(RemoteProvValues { cert_chain, priv_key, batch_cert }) |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 4507 | } |
| 4508 | |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 4509 | // Note: The parameters and SecurityLevel associations are nonsensical. This |
| 4510 | // collection is only used to check if the parameters are preserved as expected by the |
| 4511 | // database. |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 4512 | fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> { |
| 4513 | let mut params = vec![ |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 4514 | KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT), |
| 4515 | KeyParameter::new( |
| 4516 | KeyParameterValue::KeyPurpose(KeyPurpose::SIGN), |
| 4517 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4518 | ), |
| 4519 | KeyParameter::new( |
| 4520 | KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT), |
| 4521 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4522 | ), |
| 4523 | KeyParameter::new( |
| 4524 | KeyParameterValue::Algorithm(Algorithm::RSA), |
| 4525 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4526 | ), |
| 4527 | KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT), |
| 4528 | KeyParameter::new( |
| 4529 | KeyParameterValue::BlockMode(BlockMode::ECB), |
| 4530 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4531 | ), |
| 4532 | KeyParameter::new( |
| 4533 | KeyParameterValue::BlockMode(BlockMode::GCM), |
| 4534 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4535 | ), |
| 4536 | KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX), |
| 4537 | KeyParameter::new( |
| 4538 | KeyParameterValue::Digest(Digest::MD5), |
| 4539 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4540 | ), |
| 4541 | KeyParameter::new( |
| 4542 | KeyParameterValue::Digest(Digest::SHA_2_224), |
| 4543 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4544 | ), |
| 4545 | KeyParameter::new( |
| 4546 | KeyParameterValue::Digest(Digest::SHA_2_256), |
| 4547 | SecurityLevel::STRONGBOX, |
| 4548 | ), |
| 4549 | KeyParameter::new( |
| 4550 | KeyParameterValue::PaddingMode(PaddingMode::NONE), |
| 4551 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4552 | ), |
| 4553 | KeyParameter::new( |
| 4554 | KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP), |
| 4555 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4556 | ), |
| 4557 | KeyParameter::new( |
| 4558 | KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS), |
| 4559 | SecurityLevel::STRONGBOX, |
| 4560 | ), |
| 4561 | KeyParameter::new( |
| 4562 | KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN), |
| 4563 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4564 | ), |
| 4565 | KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT), |
| 4566 | KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX), |
| 4567 | KeyParameter::new( |
| 4568 | KeyParameterValue::EcCurve(EcCurve::P_224), |
| 4569 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4570 | ), |
| 4571 | KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX), |
| 4572 | KeyParameter::new( |
| 4573 | KeyParameterValue::EcCurve(EcCurve::P_384), |
| 4574 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4575 | ), |
| 4576 | KeyParameter::new( |
| 4577 | KeyParameterValue::EcCurve(EcCurve::P_521), |
| 4578 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4579 | ), |
| 4580 | KeyParameter::new( |
| 4581 | KeyParameterValue::RSAPublicExponent(3), |
| 4582 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4583 | ), |
| 4584 | KeyParameter::new( |
| 4585 | KeyParameterValue::IncludeUniqueID, |
| 4586 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4587 | ), |
| 4588 | KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX), |
| 4589 | KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX), |
| 4590 | KeyParameter::new( |
| 4591 | KeyParameterValue::ActiveDateTime(1234567890), |
| 4592 | SecurityLevel::STRONGBOX, |
| 4593 | ), |
| 4594 | KeyParameter::new( |
| 4595 | KeyParameterValue::OriginationExpireDateTime(1234567890), |
| 4596 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4597 | ), |
| 4598 | KeyParameter::new( |
| 4599 | KeyParameterValue::UsageExpireDateTime(1234567890), |
| 4600 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4601 | ), |
| 4602 | KeyParameter::new( |
| 4603 | KeyParameterValue::MinSecondsBetweenOps(1234567890), |
| 4604 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4605 | ), |
| 4606 | KeyParameter::new( |
| 4607 | KeyParameterValue::MaxUsesPerBoot(1234567890), |
| 4608 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4609 | ), |
| 4610 | KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX), |
| 4611 | KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX), |
| 4612 | KeyParameter::new( |
| 4613 | KeyParameterValue::NoAuthRequired, |
| 4614 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4615 | ), |
| 4616 | KeyParameter::new( |
| 4617 | KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD), |
| 4618 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4619 | ), |
| 4620 | KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE), |
| 4621 | KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE), |
| 4622 | KeyParameter::new( |
| 4623 | KeyParameterValue::TrustedUserPresenceRequired, |
| 4624 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4625 | ), |
| 4626 | KeyParameter::new( |
| 4627 | KeyParameterValue::TrustedConfirmationRequired, |
| 4628 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4629 | ), |
| 4630 | KeyParameter::new( |
| 4631 | KeyParameterValue::UnlockedDeviceRequired, |
| 4632 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4633 | ), |
| 4634 | KeyParameter::new( |
| 4635 | KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]), |
| 4636 | SecurityLevel::SOFTWARE, |
| 4637 | ), |
| 4638 | KeyParameter::new( |
| 4639 | KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]), |
| 4640 | SecurityLevel::SOFTWARE, |
| 4641 | ), |
| 4642 | KeyParameter::new( |
| 4643 | KeyParameterValue::CreationDateTime(12345677890), |
| 4644 | SecurityLevel::SOFTWARE, |
| 4645 | ), |
| 4646 | KeyParameter::new( |
| 4647 | KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED), |
| 4648 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4649 | ), |
| 4650 | KeyParameter::new( |
| 4651 | KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]), |
| 4652 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4653 | ), |
| 4654 | KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT), |
| 4655 | KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE), |
| 4656 | KeyParameter::new( |
| 4657 | KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]), |
| 4658 | SecurityLevel::SOFTWARE, |
| 4659 | ), |
| 4660 | KeyParameter::new( |
| 4661 | KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]), |
| 4662 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4663 | ), |
| 4664 | KeyParameter::new( |
| 4665 | KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]), |
| 4666 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4667 | ), |
| 4668 | KeyParameter::new( |
| 4669 | KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]), |
| 4670 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4671 | ), |
| 4672 | KeyParameter::new( |
| 4673 | KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]), |
| 4674 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4675 | ), |
| 4676 | KeyParameter::new( |
| 4677 | KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]), |
| 4678 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4679 | ), |
| 4680 | KeyParameter::new( |
| 4681 | KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]), |
| 4682 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4683 | ), |
| 4684 | KeyParameter::new( |
| 4685 | KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]), |
| 4686 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4687 | ), |
| 4688 | KeyParameter::new( |
| 4689 | KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]), |
| 4690 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4691 | ), |
| 4692 | KeyParameter::new( |
| 4693 | KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]), |
| 4694 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4695 | ), |
| 4696 | KeyParameter::new( |
| 4697 | KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]), |
| 4698 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4699 | ), |
| 4700 | KeyParameter::new( |
| 4701 | KeyParameterValue::VendorPatchLevel(3), |
| 4702 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4703 | ), |
| 4704 | KeyParameter::new( |
| 4705 | KeyParameterValue::BootPatchLevel(4), |
| 4706 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4707 | ), |
| 4708 | KeyParameter::new( |
| 4709 | KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]), |
| 4710 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4711 | ), |
| 4712 | KeyParameter::new( |
| 4713 | KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]), |
| 4714 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4715 | ), |
| 4716 | KeyParameter::new( |
| 4717 | KeyParameterValue::MacLength(256), |
| 4718 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4719 | ), |
| 4720 | KeyParameter::new( |
| 4721 | KeyParameterValue::ResetSinceIdRotation, |
| 4722 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4723 | ), |
| 4724 | KeyParameter::new( |
| 4725 | KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]), |
| 4726 | SecurityLevel::TRUSTED_ENVIRONMENT, |
| 4727 | ), |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 4728 | ]; |
| 4729 | if let Some(value) = max_usage_count { |
| 4730 | params.push(KeyParameter::new( |
| 4731 | KeyParameterValue::UsageCountLimit(value), |
| 4732 | SecurityLevel::SOFTWARE, |
| 4733 | )); |
| 4734 | } |
| 4735 | params |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 4736 | } |
| 4737 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 4738 | fn make_test_key_entry( |
| 4739 | db: &mut KeystoreDB, |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 4740 | domain: Domain, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 4741 | namespace: i64, |
| 4742 | alias: &str, |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 4743 | max_usage_count: Option<i32>, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 4744 | ) -> Result<KeyIdGuard> { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 4745 | let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 4746 | let mut blob_metadata = BlobMetaData::new(); |
| 4747 | blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password)); |
| 4748 | blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3])); |
| 4749 | blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1])); |
| 4750 | blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2])); |
| 4751 | blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID)); |
| 4752 | |
| 4753 | db.set_blob( |
| 4754 | &key_id, |
| 4755 | SubComponentType::KEY_BLOB, |
| 4756 | Some(TEST_KEY_BLOB), |
| 4757 | Some(&blob_metadata), |
| 4758 | )?; |
| 4759 | db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?; |
| 4760 | db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?; |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 4761 | |
| 4762 | let params = make_test_params(max_usage_count); |
| 4763 | db.insert_keyparameter(&key_id, ¶ms)?; |
| 4764 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 4765 | let mut metadata = KeyMetaData::new(); |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 4766 | metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789))); |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 4767 | db.insert_key_metadata(&key_id, &metadata)?; |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 4768 | rebind_alias(db, &key_id, alias, domain, namespace)?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 4769 | Ok(key_id) |
| 4770 | } |
| 4771 | |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 4772 | fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry { |
| 4773 | let params = make_test_params(max_usage_count); |
| 4774 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 4775 | let mut blob_metadata = BlobMetaData::new(); |
| 4776 | blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password)); |
| 4777 | blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3])); |
| 4778 | blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1])); |
| 4779 | blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2])); |
| 4780 | blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID)); |
| 4781 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 4782 | let mut metadata = KeyMetaData::new(); |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 4783 | metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789))); |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 4784 | |
| 4785 | KeyEntry { |
| 4786 | id: key_id, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 4787 | key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)), |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 4788 | cert: Some(TEST_CERT_BLOB.to_vec()), |
| 4789 | cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()), |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 4790 | km_uuid: KEYSTORE_UUID, |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 4791 | parameters: params, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 4792 | metadata, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 4793 | pure_cert: false, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 4794 | } |
| 4795 | } |
| 4796 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 4797 | fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 4798 | let mut stmt = db.conn.prepare( |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 4799 | "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] | 4800 | )?; |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 4801 | let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 4802 | NO_PARAMS, |
| 4803 | |row| { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 4804 | Ok(( |
| 4805 | row.get(0)?, |
| 4806 | row.get(1)?, |
| 4807 | row.get(2)?, |
| 4808 | row.get(3)?, |
| 4809 | row.get(4)?, |
| 4810 | row.get(5)?, |
| 4811 | row.get(6)?, |
| 4812 | )) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 4813 | }, |
| 4814 | )?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 4815 | |
| 4816 | println!("Key entry table rows:"); |
| 4817 | for r in rows { |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 4818 | let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap(); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 4819 | println!( |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 4820 | " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}", |
| 4821 | id, key_type, domain, namespace, alias, state, km_uuid |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 4822 | ); |
| 4823 | } |
| 4824 | Ok(()) |
| 4825 | } |
| 4826 | |
| 4827 | fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> { |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 4828 | let mut stmt = db |
| 4829 | .conn |
| 4830 | .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 4831 | let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| { |
| 4832 | Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)) |
| 4833 | })?; |
| 4834 | |
| 4835 | println!("Grant table rows:"); |
| 4836 | for r in rows { |
| 4837 | let (id, gt, ki, av) = r.unwrap(); |
| 4838 | println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av); |
| 4839 | } |
| 4840 | Ok(()) |
| 4841 | } |
| 4842 | |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 4843 | // Use a custom random number generator that repeats each number once. |
| 4844 | // This allows us to test repeated elements. |
| 4845 | |
| 4846 | thread_local! { |
| 4847 | static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0); |
| 4848 | } |
| 4849 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 4850 | fn reset_random() { |
| 4851 | RANDOM_COUNTER.with(|counter| { |
| 4852 | *counter.borrow_mut() = 0; |
| 4853 | }) |
| 4854 | } |
| 4855 | |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 4856 | pub fn random() -> i64 { |
| 4857 | RANDOM_COUNTER.with(|counter| { |
| 4858 | let result = *counter.borrow() / 2; |
| 4859 | *counter.borrow_mut() += 1; |
| 4860 | result |
| 4861 | }) |
| 4862 | } |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 4863 | |
| 4864 | #[test] |
| 4865 | fn test_last_off_body() -> Result<()> { |
| 4866 | let mut db = new_test_db()?; |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 4867 | db.insert_last_off_body(MonotonicRawTime::now())?; |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 4868 | let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?; |
| 4869 | let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?; |
| 4870 | tx.commit()?; |
| 4871 | let one_second = Duration::from_secs(1); |
| 4872 | thread::sleep(one_second); |
| 4873 | db.update_last_off_body(MonotonicRawTime::now())?; |
| 4874 | let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?; |
| 4875 | let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?; |
| 4876 | tx2.commit()?; |
| 4877 | assert!(last_off_body_1.seconds() < last_off_body_2.seconds()); |
| 4878 | Ok(()) |
| 4879 | } |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 4880 | |
| 4881 | #[test] |
| 4882 | fn test_unbind_keys_for_user() -> Result<()> { |
| 4883 | let mut db = new_test_db()?; |
| 4884 | db.unbind_keys_for_user(1, false)?; |
| 4885 | |
| 4886 | make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?; |
| 4887 | make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?; |
| 4888 | db.unbind_keys_for_user(2, false)?; |
| 4889 | |
| 4890 | assert_eq!(1, db.list(Domain::APP, 110000)?.len()); |
| 4891 | assert_eq!(0, db.list(Domain::APP, 210000)?.len()); |
| 4892 | |
| 4893 | db.unbind_keys_for_user(1, true)?; |
| 4894 | assert_eq!(0, db.list(Domain::APP, 110000)?.len()); |
| 4895 | |
| 4896 | Ok(()) |
| 4897 | } |
| 4898 | |
| 4899 | #[test] |
| 4900 | fn test_store_super_key() -> Result<()> { |
| 4901 | let mut db = new_test_db()?; |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 4902 | let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into(); |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 4903 | let super_key = keystore2_crypto::generate_aes256_key()?; |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 4904 | let secret_bytes = b"keystore2 is great."; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 4905 | let (encrypted_secret, iv, tag) = |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 4906 | keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 4907 | |
| 4908 | let (encrypted_super_key, metadata) = |
| 4909 | SuperKeyManager::encrypt_with_password(&super_key, &pw)?; |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 4910 | db.store_super_key( |
| 4911 | 1, |
| 4912 | &USER_SUPER_KEY, |
| 4913 | &encrypted_super_key, |
| 4914 | &metadata, |
| 4915 | &KeyMetaData::new(), |
| 4916 | )?; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 4917 | |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 4918 | //check if super key exists |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 4919 | assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?); |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 4920 | |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 4921 | let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap(); |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 4922 | let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry( |
| 4923 | USER_SUPER_KEY.algorithm, |
| 4924 | key_entry, |
| 4925 | &pw, |
| 4926 | None, |
| 4927 | )?; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 4928 | |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 4929 | let decrypted_secret_bytes = |
| 4930 | loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?; |
| 4931 | assert_eq!(secret_bytes, &*decrypted_secret_bytes); |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 4932 | Ok(()) |
| 4933 | } |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 4934 | } |