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 | |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 44 | mod perboot; |
Janis Danisevskis | 030ba02 | 2021-05-26 11:15:30 -0700 | [diff] [blame] | 45 | pub(crate) mod utils; |
Janis Danisevskis | cfaf919 | 2021-05-26 16:31:02 -0700 | [diff] [blame] | 46 | mod versioning; |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 47 | |
David Drysdale | 2566fb3 | 2024-07-09 14:46:37 +0100 | [diff] [blame] | 48 | #[cfg(test)] |
| 49 | pub mod tests; |
| 50 | |
Janis Danisevskis | 11bd259 | 2022-01-04 19:59:26 -0800 | [diff] [blame] | 51 | use crate::gc::Gc; |
David Drysdale | f1ba381 | 2024-05-08 17:50:13 +0100 | [diff] [blame] | 52 | use crate::impl_metadata; // This is in database/utils.rs |
Eric Biggers | b0478cf | 2023-10-27 03:55:29 +0000 | [diff] [blame] | 53 | use crate::key_parameter::{KeyParameter, KeyParameterValue, Tag}; |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 54 | use crate::ks_err; |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 55 | use crate::permission::KeyPermSet; |
Hasini Gunasinghe | 66a2460 | 2021-05-12 19:03:12 +0000 | [diff] [blame] | 56 | use crate::utils::{get_current_time_in_milliseconds, watchdog as wd, AID_USER_OFFSET}; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 57 | use crate::{ |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 58 | error::{Error as KsError, ErrorCode, ResponseCode}, |
| 59 | super_key::SuperKeyType, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 60 | }; |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 61 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{ |
Tri Vo | a1634bb | 2022-12-01 15:54:19 -0800 | [diff] [blame] | 62 | HardwareAuthToken::HardwareAuthToken, HardwareAuthenticatorType::HardwareAuthenticatorType, |
| 63 | SecurityLevel::SecurityLevel, |
| 64 | }; |
| 65 | use android_security_metrics::aidl::android::security::metrics::{ |
Tri Vo | 0346bbe | 2023-05-12 14:16:31 -0400 | [diff] [blame] | 66 | Storage::Storage as MetricsStorage, StorageStats::StorageStats, |
Janis Danisevskis | c3a496b | 2021-01-05 10:37:22 -0800 | [diff] [blame] | 67 | }; |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 68 | use android_system_keystore2::aidl::android::system::keystore2::{ |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 69 | Domain::Domain, KeyDescriptor::KeyDescriptor, |
Janis Danisevskis | 60400fe | 2020-08-26 15:24:42 -0700 | [diff] [blame] | 70 | }; |
Shaquille Johnson | 7f5a815 | 2023-09-27 18:46:27 +0100 | [diff] [blame] | 71 | use anyhow::{anyhow, Context, Result}; |
| 72 | use keystore2_flags; |
| 73 | use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError}; |
| 74 | use utils as db_utils; |
| 75 | use utils::SqlField; |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 76 | |
| 77 | use keystore2_crypto::ZVec; |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 78 | use lazy_static::lazy_static; |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 79 | use log::error; |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 80 | #[cfg(not(test))] |
| 81 | use rand::prelude::random; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 82 | use rusqlite::{ |
Joel Galenson | ff79e36 | 2021-05-25 16:30:17 -0700 | [diff] [blame] | 83 | params, params_from_iter, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 84 | types::FromSql, |
| 85 | types::FromSqlResult, |
| 86 | types::ToSqlOutput, |
| 87 | types::{FromSqlError, Value, ValueRef}, |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 88 | Connection, OptionalExtension, ToSql, Transaction, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 89 | }; |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 90 | |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 91 | use std::{ |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 92 | collections::{HashMap, HashSet}, |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 93 | path::Path, |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 94 | sync::{Arc, Condvar, Mutex}, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 95 | time::{Duration, SystemTime}, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 96 | }; |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 97 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 98 | use TransactionBehavior::Immediate; |
| 99 | |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 100 | #[cfg(test)] |
| 101 | use tests::random; |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 102 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 103 | /// Wrapper for `rusqlite::TransactionBehavior` which includes information about the transaction |
| 104 | /// being performed. |
| 105 | #[derive(Clone, Copy)] |
| 106 | enum TransactionBehavior { |
| 107 | Deferred, |
| 108 | Immediate(&'static str), |
| 109 | } |
| 110 | |
| 111 | impl From<TransactionBehavior> for rusqlite::TransactionBehavior { |
| 112 | fn from(val: TransactionBehavior) -> Self { |
| 113 | match val { |
| 114 | TransactionBehavior::Deferred => rusqlite::TransactionBehavior::Deferred, |
| 115 | TransactionBehavior::Immediate(_) => rusqlite::TransactionBehavior::Immediate, |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | impl TransactionBehavior { |
| 121 | fn name(&self) -> Option<&'static str> { |
| 122 | match self { |
| 123 | TransactionBehavior::Deferred => None, |
| 124 | TransactionBehavior::Immediate(v) => Some(v), |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | |
David Drysdale | 115c472 | 2024-04-15 14:11:52 +0100 | [diff] [blame] | 129 | /// If the database returns a busy error code, retry after this interval. |
| 130 | const DB_BUSY_RETRY_INTERVAL: Duration = Duration::from_micros(500); |
David Drysdale | 115c472 | 2024-04-15 14:11:52 +0100 | [diff] [blame] | 131 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 132 | impl_metadata!( |
| 133 | /// A set of metadata for key entries. |
| 134 | #[derive(Debug, Default, Eq, PartialEq)] |
| 135 | pub struct KeyMetaData; |
| 136 | /// A metadata entry for key entries. |
| 137 | #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)] |
| 138 | pub enum KeyMetaEntry { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 139 | /// Date of the creation of the key entry. |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 140 | CreationDate(DateTime) with accessor creation_date, |
| 141 | /// Expiration date for attestation keys. |
| 142 | AttestationExpirationDate(DateTime) with accessor attestation_expiration_date, |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 143 | /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote |
| 144 | /// provisioning |
| 145 | AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key, |
| 146 | /// Vector representing the raw public key so results from the server can be matched |
| 147 | /// to the right entry |
| 148 | AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 149 | /// SEC1 public key for ECDH encryption |
| 150 | Sec1PublicKey(Vec<u8>) with accessor sec1_public_key, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 151 | // --- ADD NEW META DATA FIELDS HERE --- |
| 152 | // For backwards compatibility add new entries only to |
| 153 | // end of this list and above this comment. |
| 154 | }; |
| 155 | ); |
| 156 | |
| 157 | impl KeyMetaData { |
| 158 | fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> { |
| 159 | let mut stmt = tx |
| 160 | .prepare( |
| 161 | "SELECT tag, data from persistent.keymetadata |
| 162 | WHERE keyentryid = ?;", |
| 163 | ) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 164 | .context(ks_err!("KeyMetaData::load_from_db: prepare statement failed."))?; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 165 | |
| 166 | let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default(); |
| 167 | |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 168 | let mut rows = stmt |
| 169 | .query(params![key_id]) |
| 170 | .context(ks_err!("KeyMetaData::load_from_db: query failed."))?; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 171 | db_utils::with_rows_extract_all(&mut rows, |row| { |
| 172 | let db_tag: i64 = row.get(0).context("Failed to read tag.")?; |
| 173 | metadata.insert( |
| 174 | db_tag, |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 175 | KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row)) |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 176 | .context("Failed to read KeyMetaEntry.")?, |
| 177 | ); |
| 178 | Ok(()) |
| 179 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 180 | .context(ks_err!("KeyMetaData::load_from_db."))?; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 181 | |
| 182 | Ok(Self { data: metadata }) |
| 183 | } |
| 184 | |
| 185 | fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> { |
| 186 | let mut stmt = tx |
| 187 | .prepare( |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 188 | "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data) |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 189 | VALUES (?, ?, ?);", |
| 190 | ) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 191 | .context(ks_err!("KeyMetaData::store_in_db: Failed to prepare statement."))?; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 192 | |
| 193 | let iter = self.data.iter(); |
| 194 | for (tag, entry) in iter { |
| 195 | stmt.insert(params![key_id, tag, entry,]).with_context(|| { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 196 | ks_err!("KeyMetaData::store_in_db: Failed to insert {:?}", entry) |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 197 | })?; |
| 198 | } |
| 199 | Ok(()) |
| 200 | } |
| 201 | } |
| 202 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 203 | impl_metadata!( |
| 204 | /// A set of metadata for key blobs. |
| 205 | #[derive(Debug, Default, Eq, PartialEq)] |
| 206 | pub struct BlobMetaData; |
| 207 | /// A metadata entry for key blobs. |
| 208 | #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)] |
| 209 | pub enum BlobMetaEntry { |
| 210 | /// If present, indicates that the blob is encrypted with another key or a key derived |
| 211 | /// from a password. |
| 212 | EncryptedBy(EncryptedBy) with accessor encrypted_by, |
| 213 | /// If the blob is password encrypted this field is set to the |
| 214 | /// salt used for the key derivation. |
| 215 | Salt(Vec<u8>) with accessor salt, |
| 216 | /// If the blob is encrypted, this field is set to the initialization vector. |
| 217 | Iv(Vec<u8>) with accessor iv, |
| 218 | /// If the blob is encrypted, this field holds the AEAD TAG. |
| 219 | AeadTag(Vec<u8>) with accessor aead_tag, |
| 220 | /// The uuid of the owning KeyMint instance. |
| 221 | KmUuid(Uuid) with accessor km_uuid, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 222 | /// If the key is ECDH encrypted, this is the ephemeral public key |
| 223 | PublicKey(Vec<u8>) with accessor public_key, |
Paul Crowley | 44c02da | 2021-04-08 17:04:43 +0000 | [diff] [blame] | 224 | /// If the key is encrypted with a MaxBootLevel key, this is the boot level |
| 225 | /// of that key |
| 226 | MaxBootLevel(i32) with accessor max_boot_level, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 227 | // --- ADD NEW META DATA FIELDS HERE --- |
| 228 | // For backwards compatibility add new entries only to |
| 229 | // end of this list and above this comment. |
| 230 | }; |
| 231 | ); |
| 232 | |
| 233 | impl BlobMetaData { |
| 234 | fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> { |
| 235 | let mut stmt = tx |
| 236 | .prepare( |
| 237 | "SELECT tag, data from persistent.blobmetadata |
| 238 | WHERE blobentryid = ?;", |
| 239 | ) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 240 | .context(ks_err!("BlobMetaData::load_from_db: prepare statement failed."))?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 241 | |
| 242 | let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default(); |
| 243 | |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 244 | let mut rows = stmt.query(params![blob_id]).context(ks_err!("query failed."))?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 245 | db_utils::with_rows_extract_all(&mut rows, |row| { |
| 246 | let db_tag: i64 = row.get(0).context("Failed to read tag.")?; |
| 247 | metadata.insert( |
| 248 | db_tag, |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 249 | BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row)) |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 250 | .context("Failed to read BlobMetaEntry.")?, |
| 251 | ); |
| 252 | Ok(()) |
| 253 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 254 | .context(ks_err!("BlobMetaData::load_from_db"))?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 255 | |
| 256 | Ok(Self { data: metadata }) |
| 257 | } |
| 258 | |
| 259 | fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> { |
| 260 | let mut stmt = tx |
| 261 | .prepare( |
| 262 | "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data) |
| 263 | VALUES (?, ?, ?);", |
| 264 | ) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 265 | .context(ks_err!("BlobMetaData::store_in_db: Failed to prepare statement.",))?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 266 | |
| 267 | let iter = self.data.iter(); |
| 268 | for (tag, entry) in iter { |
| 269 | stmt.insert(params![blob_id, tag, entry,]).with_context(|| { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 270 | ks_err!("BlobMetaData::store_in_db: Failed to insert {:?}", entry) |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 271 | })?; |
| 272 | } |
| 273 | Ok(()) |
| 274 | } |
| 275 | } |
| 276 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 277 | /// Indicates the type of the keyentry. |
| 278 | #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] |
| 279 | pub enum KeyType { |
| 280 | /// This is a client key type. These keys are created or imported through the Keystore 2.0 |
| 281 | /// AIDL interface android.system.keystore2. |
| 282 | Client, |
| 283 | /// This is a super key type. These keys are created by keystore itself and used to encrypt |
| 284 | /// other key blobs to provide LSKF binding. |
| 285 | Super, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 286 | } |
| 287 | |
| 288 | impl ToSql for KeyType { |
| 289 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 290 | Ok(ToSqlOutput::Owned(Value::Integer(match self { |
| 291 | KeyType::Client => 0, |
| 292 | KeyType::Super => 1, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 293 | }))) |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | impl FromSql for KeyType { |
| 298 | fn column_result(value: ValueRef) -> FromSqlResult<Self> { |
| 299 | match i64::column_result(value)? { |
| 300 | 0 => Ok(KeyType::Client), |
| 301 | 1 => Ok(KeyType::Super), |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 302 | v => Err(FromSqlError::OutOfRange(v)), |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 307 | /// Uuid representation that can be stored in the database. |
| 308 | /// Right now it can only be initialized from SecurityLevel. |
| 309 | /// Once KeyMint provides a UUID type a corresponding From impl shall be added. |
| 310 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 311 | pub struct Uuid([u8; 16]); |
| 312 | |
| 313 | impl Deref for Uuid { |
| 314 | type Target = [u8; 16]; |
| 315 | |
| 316 | fn deref(&self) -> &Self::Target { |
| 317 | &self.0 |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | impl From<SecurityLevel> for Uuid { |
| 322 | fn from(sec_level: SecurityLevel) -> Self { |
| 323 | Self((sec_level.0 as u128).to_be_bytes()) |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | impl ToSql for Uuid { |
| 328 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 329 | self.0.to_sql() |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | impl FromSql for Uuid { |
| 334 | fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> { |
| 335 | let blob = Vec::<u8>::column_result(value)?; |
| 336 | if blob.len() != 16 { |
| 337 | return Err(FromSqlError::OutOfRange(blob.len() as i64)); |
| 338 | } |
| 339 | let mut arr = [0u8; 16]; |
| 340 | arr.copy_from_slice(&blob); |
| 341 | Ok(Self(arr)) |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | /// Key entries that are not associated with any KeyMint instance, such as pure certificate |
| 346 | /// entries are associated with this UUID. |
| 347 | pub static KEYSTORE_UUID: Uuid = Uuid([ |
| 348 | 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11, |
| 349 | ]); |
| 350 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 351 | /// Indicates how the sensitive part of this key blob is encrypted. |
| 352 | #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)] |
| 353 | pub enum EncryptedBy { |
| 354 | /// The keyblob is encrypted by a user password. |
| 355 | /// In the database this variant is represented as NULL. |
| 356 | Password, |
| 357 | /// The keyblob is encrypted by another key with wrapped key id. |
| 358 | /// In the database this variant is represented as non NULL value |
| 359 | /// that is convertible to i64, typically NUMERIC. |
| 360 | KeyId(i64), |
| 361 | } |
| 362 | |
| 363 | impl ToSql for EncryptedBy { |
| 364 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 365 | match self { |
| 366 | Self::Password => Ok(ToSqlOutput::Owned(Value::Null)), |
| 367 | Self::KeyId(id) => id.to_sql(), |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | impl FromSql for EncryptedBy { |
| 373 | fn column_result(value: ValueRef) -> FromSqlResult<Self> { |
| 374 | match value { |
| 375 | ValueRef::Null => Ok(Self::Password), |
| 376 | _ => Ok(Self::KeyId(i64::column_result(value)?)), |
| 377 | } |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | /// A database representation of wall clock time. DateTime stores unix epoch time as |
| 382 | /// i64 in milliseconds. |
| 383 | #[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)] |
| 384 | pub struct DateTime(i64); |
| 385 | |
| 386 | /// Error type returned when creating DateTime or converting it from and to |
| 387 | /// SystemTime. |
| 388 | #[derive(thiserror::Error, Debug)] |
| 389 | pub enum DateTimeError { |
| 390 | /// This is returned when SystemTime and Duration computations fail. |
| 391 | #[error(transparent)] |
| 392 | SystemTimeError(#[from] SystemTimeError), |
| 393 | |
| 394 | /// This is returned when type conversions fail. |
| 395 | #[error(transparent)] |
| 396 | TypeConversion(#[from] std::num::TryFromIntError), |
| 397 | |
| 398 | /// This is returned when checked time arithmetic failed. |
| 399 | #[error("Time arithmetic failed.")] |
| 400 | TimeArithmetic, |
| 401 | } |
| 402 | |
| 403 | impl DateTime { |
| 404 | /// Constructs a new DateTime object denoting the current time. This may fail during |
| 405 | /// conversion to unix epoch time and during conversion to the internal i64 representation. |
| 406 | pub fn now() -> Result<Self, DateTimeError> { |
| 407 | Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?)) |
| 408 | } |
| 409 | |
| 410 | /// Constructs a new DateTime object from milliseconds. |
| 411 | pub fn from_millis_epoch(millis: i64) -> Self { |
| 412 | Self(millis) |
| 413 | } |
| 414 | |
| 415 | /// Returns unix epoch time in milliseconds. |
Chris Wailes | 3877f29 | 2021-07-26 19:24:18 -0700 | [diff] [blame] | 416 | pub fn to_millis_epoch(self) -> i64 { |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 417 | self.0 |
| 418 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 419 | } |
| 420 | |
| 421 | impl ToSql for DateTime { |
| 422 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 423 | Ok(ToSqlOutput::Owned(Value::Integer(self.0))) |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | impl FromSql for DateTime { |
| 428 | fn column_result(value: ValueRef) -> FromSqlResult<Self> { |
| 429 | Ok(Self(i64::column_result(value)?)) |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | impl TryInto<SystemTime> for DateTime { |
| 434 | type Error = DateTimeError; |
| 435 | |
| 436 | fn try_into(self) -> Result<SystemTime, Self::Error> { |
| 437 | // We want to construct a SystemTime representation equivalent to self, denoting |
| 438 | // a point in time THEN, but we cannot set the time directly. We can only construct |
| 439 | // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW, |
| 440 | // and between EPOCH and THEN. With this common reference we can construct the |
| 441 | // duration between NOW and THEN which we can add to our SystemTime representation |
| 442 | // of NOW to get a SystemTime representation of THEN. |
| 443 | // Durations can only be positive, thus the if statement below. |
| 444 | let now = SystemTime::now(); |
| 445 | let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?; |
| 446 | let then_epoch = Duration::from_millis(self.0.try_into()?); |
| 447 | Ok(if now_epoch > then_epoch { |
| 448 | // then = now - (now_epoch - then_epoch) |
| 449 | now_epoch |
| 450 | .checked_sub(then_epoch) |
| 451 | .and_then(|d| now.checked_sub(d)) |
| 452 | .ok_or(DateTimeError::TimeArithmetic)? |
| 453 | } else { |
| 454 | // then = now + (then_epoch - now_epoch) |
| 455 | then_epoch |
| 456 | .checked_sub(now_epoch) |
| 457 | .and_then(|d| now.checked_add(d)) |
| 458 | .ok_or(DateTimeError::TimeArithmetic)? |
| 459 | }) |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | impl TryFrom<SystemTime> for DateTime { |
| 464 | type Error = DateTimeError; |
| 465 | |
| 466 | fn try_from(t: SystemTime) -> Result<Self, Self::Error> { |
| 467 | Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?)) |
| 468 | } |
| 469 | } |
| 470 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 471 | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] |
| 472 | enum KeyLifeCycle { |
| 473 | /// Existing keys have a key ID but are not fully populated yet. |
| 474 | /// This is a transient state. If Keystore finds any such keys when it starts up, it must move |
| 475 | /// them to Unreferenced for garbage collection. |
| 476 | Existing, |
| 477 | /// A live key is fully populated and usable by clients. |
| 478 | Live, |
| 479 | /// An unreferenced key is scheduled for garbage collection. |
| 480 | Unreferenced, |
| 481 | } |
| 482 | |
| 483 | impl ToSql for KeyLifeCycle { |
| 484 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 485 | match self { |
| 486 | Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))), |
| 487 | Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))), |
| 488 | Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))), |
| 489 | } |
| 490 | } |
| 491 | } |
| 492 | |
| 493 | impl FromSql for KeyLifeCycle { |
| 494 | fn column_result(value: ValueRef) -> FromSqlResult<Self> { |
| 495 | match i64::column_result(value)? { |
| 496 | 0 => Ok(KeyLifeCycle::Existing), |
| 497 | 1 => Ok(KeyLifeCycle::Live), |
| 498 | 2 => Ok(KeyLifeCycle::Unreferenced), |
| 499 | v => Err(FromSqlError::OutOfRange(v)), |
| 500 | } |
| 501 | } |
| 502 | } |
| 503 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 504 | /// Keys have a KeyMint blob component and optional public certificate and |
| 505 | /// certificate chain components. |
| 506 | /// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry` |
| 507 | /// which components shall be loaded from the database if present. |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 508 | #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 509 | pub struct KeyEntryLoadBits(u32); |
| 510 | |
| 511 | impl KeyEntryLoadBits { |
| 512 | /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded. |
| 513 | pub const NONE: KeyEntryLoadBits = Self(0); |
| 514 | /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded. |
| 515 | pub const KM: KeyEntryLoadBits = Self(1); |
| 516 | /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded. |
| 517 | pub const PUBLIC: KeyEntryLoadBits = Self(2); |
| 518 | /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded. |
| 519 | pub const BOTH: KeyEntryLoadBits = Self(3); |
| 520 | |
| 521 | /// Returns true if this object indicates that the public components shall be loaded. |
| 522 | pub const fn load_public(&self) -> bool { |
| 523 | self.0 & Self::PUBLIC.0 != 0 |
| 524 | } |
| 525 | |
| 526 | /// Returns true if the object indicates that the KeyMint component shall be loaded. |
| 527 | pub const fn load_km(&self) -> bool { |
| 528 | self.0 & Self::KM.0 != 0 |
| 529 | } |
| 530 | } |
| 531 | |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 532 | lazy_static! { |
| 533 | static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new(); |
| 534 | } |
| 535 | |
| 536 | struct KeyIdLockDb { |
| 537 | locked_keys: Mutex<HashSet<i64>>, |
| 538 | cond_var: Condvar, |
| 539 | } |
| 540 | |
| 541 | /// A locked key. While a guard exists for a given key id, the same key cannot be loaded |
| 542 | /// from the database a second time. Most functions manipulating the key blob database |
| 543 | /// require a KeyIdGuard. |
| 544 | #[derive(Debug)] |
| 545 | pub struct KeyIdGuard(i64); |
| 546 | |
| 547 | impl KeyIdLockDb { |
| 548 | fn new() -> Self { |
| 549 | Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() } |
| 550 | } |
| 551 | |
| 552 | /// This function blocks until an exclusive lock for the given key entry id can |
| 553 | /// be acquired. It returns a guard object, that represents the lifecycle of the |
| 554 | /// acquired lock. |
David Drysdale | 8c4c4f3 | 2023-10-31 12:14:11 +0000 | [diff] [blame] | 555 | fn get(&self, key_id: i64) -> KeyIdGuard { |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 556 | let mut locked_keys = self.locked_keys.lock().unwrap(); |
| 557 | while locked_keys.contains(&key_id) { |
| 558 | locked_keys = self.cond_var.wait(locked_keys).unwrap(); |
| 559 | } |
| 560 | locked_keys.insert(key_id); |
| 561 | KeyIdGuard(key_id) |
| 562 | } |
| 563 | |
| 564 | /// This function attempts to acquire an exclusive lock on a given key id. If the |
| 565 | /// given key id is already taken the function returns None immediately. If a lock |
| 566 | /// can be acquired this function returns a guard object, that represents the |
| 567 | /// lifecycle of the acquired lock. |
David Drysdale | 8c4c4f3 | 2023-10-31 12:14:11 +0000 | [diff] [blame] | 568 | fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> { |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 569 | let mut locked_keys = self.locked_keys.lock().unwrap(); |
| 570 | if locked_keys.insert(key_id) { |
| 571 | Some(KeyIdGuard(key_id)) |
| 572 | } else { |
| 573 | None |
| 574 | } |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | impl KeyIdGuard { |
| 579 | /// Get the numeric key id of the locked key. |
| 580 | pub fn id(&self) -> i64 { |
| 581 | self.0 |
| 582 | } |
| 583 | } |
| 584 | |
| 585 | impl Drop for KeyIdGuard { |
| 586 | fn drop(&mut self) { |
| 587 | let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap(); |
| 588 | locked_keys.remove(&self.0); |
Janis Danisevskis | 7fd5358 | 2020-11-23 13:40:34 -0800 | [diff] [blame] | 589 | drop(locked_keys); |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 590 | KEY_ID_LOCK.cond_var.notify_all(); |
| 591 | } |
| 592 | } |
| 593 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 594 | /// This type represents a certificate and certificate chain entry for a key. |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 595 | #[derive(Debug, Default)] |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 596 | pub struct CertificateInfo { |
| 597 | cert: Option<Vec<u8>>, |
| 598 | cert_chain: Option<Vec<u8>>, |
| 599 | } |
| 600 | |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 601 | /// This type represents a Blob with its metadata and an optional superseded blob. |
| 602 | #[derive(Debug)] |
| 603 | pub struct BlobInfo<'a> { |
| 604 | blob: &'a [u8], |
| 605 | metadata: &'a BlobMetaData, |
| 606 | /// Superseded blobs are an artifact of legacy import. In some rare occasions |
| 607 | /// the key blob needs to be upgraded during import. In that case two |
| 608 | /// blob are imported, the superseded one will have to be imported first, |
| 609 | /// so that the garbage collector can reap it. |
| 610 | superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>, |
| 611 | } |
| 612 | |
| 613 | impl<'a> BlobInfo<'a> { |
| 614 | /// Create a new instance of blob info with blob and corresponding metadata |
| 615 | /// and no superseded blob info. |
| 616 | pub fn new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self { |
| 617 | Self { blob, metadata, superseded_blob: None } |
| 618 | } |
| 619 | |
| 620 | /// Create a new instance of blob info with blob and corresponding metadata |
| 621 | /// as well as superseded blob info. |
| 622 | pub fn new_with_superseded( |
| 623 | blob: &'a [u8], |
| 624 | metadata: &'a BlobMetaData, |
| 625 | superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>, |
| 626 | ) -> Self { |
| 627 | Self { blob, metadata, superseded_blob } |
| 628 | } |
| 629 | } |
| 630 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 631 | impl CertificateInfo { |
| 632 | /// Constructs a new CertificateInfo object from `cert` and `cert_chain` |
| 633 | pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self { |
| 634 | Self { cert, cert_chain } |
| 635 | } |
| 636 | |
| 637 | /// Take the cert |
| 638 | pub fn take_cert(&mut self) -> Option<Vec<u8>> { |
| 639 | self.cert.take() |
| 640 | } |
| 641 | |
| 642 | /// Take the cert chain |
| 643 | pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> { |
| 644 | self.cert_chain.take() |
| 645 | } |
| 646 | } |
| 647 | |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 648 | /// This type represents a certificate chain with a private key corresponding to the leaf |
| 649 | /// 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] | 650 | pub struct CertificateChain { |
Max Bires | 97f9681 | 2021-02-23 23:44:57 -0800 | [diff] [blame] | 651 | /// A KM key blob |
| 652 | pub private_key: ZVec, |
| 653 | /// A batch cert for private_key |
| 654 | pub batch_cert: Vec<u8>, |
| 655 | /// A full certificate chain from root signing authority to private_key, including batch_cert |
| 656 | /// for convenience. |
| 657 | pub cert_chain: Vec<u8>, |
Max Bires | 2b2e656 | 2020-09-22 11:22:36 -0700 | [diff] [blame] | 658 | } |
| 659 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 660 | /// This type represents a Keystore 2.0 key entry. |
| 661 | /// An entry has a unique `id` by which it can be found in the database. |
| 662 | /// It has a security level field, key parameters, and three optional fields |
| 663 | /// for the KeyMint blob, public certificate and a public certificate chain. |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 664 | #[derive(Debug, Default, Eq, PartialEq)] |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 665 | pub struct KeyEntry { |
| 666 | id: i64, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 667 | key_blob_info: Option<(Vec<u8>, BlobMetaData)>, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 668 | cert: Option<Vec<u8>>, |
| 669 | cert_chain: Option<Vec<u8>>, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 670 | km_uuid: Uuid, |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 671 | parameters: Vec<KeyParameter>, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 672 | metadata: KeyMetaData, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 673 | pure_cert: bool, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 674 | } |
| 675 | |
| 676 | impl KeyEntry { |
| 677 | /// Returns the unique id of the Key entry. |
| 678 | pub fn id(&self) -> i64 { |
| 679 | self.id |
| 680 | } |
| 681 | /// Exposes the optional KeyMint blob. |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 682 | pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> { |
| 683 | &self.key_blob_info |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 684 | } |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 685 | /// Extracts the Optional KeyMint blob including its metadata. |
| 686 | pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> { |
| 687 | self.key_blob_info.take() |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 688 | } |
| 689 | /// Exposes the optional public certificate. |
| 690 | pub fn cert(&self) -> &Option<Vec<u8>> { |
| 691 | &self.cert |
| 692 | } |
| 693 | /// Extracts the optional public certificate. |
| 694 | pub fn take_cert(&mut self) -> Option<Vec<u8>> { |
| 695 | self.cert.take() |
| 696 | } |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 697 | /// Extracts the optional public certificate_chain. |
| 698 | pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> { |
| 699 | self.cert_chain.take() |
| 700 | } |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 701 | /// Returns the uuid of the owning KeyMint instance. |
| 702 | pub fn km_uuid(&self) -> &Uuid { |
| 703 | &self.km_uuid |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 704 | } |
Janis Danisevskis | 04b0283 | 2020-10-26 09:21:40 -0700 | [diff] [blame] | 705 | /// Consumes this key entry and extracts the keyparameters from it. |
| 706 | pub fn into_key_parameters(self) -> Vec<KeyParameter> { |
| 707 | self.parameters |
| 708 | } |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 709 | /// Exposes the key metadata of this key entry. |
| 710 | pub fn metadata(&self) -> &KeyMetaData { |
| 711 | &self.metadata |
| 712 | } |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 713 | /// This returns true if the entry is a pure certificate entry with no |
| 714 | /// private key component. |
| 715 | pub fn pure_cert(&self) -> bool { |
| 716 | self.pure_cert |
| 717 | } |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 718 | } |
| 719 | |
| 720 | /// Indicates the sub component of a key entry for persistent storage. |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 721 | #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 722 | pub struct SubComponentType(u32); |
| 723 | impl SubComponentType { |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 724 | /// Persistent identifier for a key blob. |
| 725 | pub const KEY_BLOB: SubComponentType = Self(0); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 726 | /// Persistent identifier for a certificate blob. |
| 727 | pub const CERT: SubComponentType = Self(1); |
| 728 | /// Persistent identifier for a certificate chain blob. |
| 729 | pub const CERT_CHAIN: SubComponentType = Self(2); |
| 730 | } |
| 731 | |
| 732 | impl ToSql for SubComponentType { |
| 733 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 734 | self.0.to_sql() |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | impl FromSql for SubComponentType { |
| 739 | fn column_result(value: ValueRef) -> FromSqlResult<Self> { |
| 740 | Ok(Self(u32::column_result(value)?)) |
| 741 | } |
| 742 | } |
| 743 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 744 | /// This trait is private to the database module. It is used to convey whether or not the garbage |
| 745 | /// collector shall be invoked after a database access. All closures passed to |
| 746 | /// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the |
| 747 | /// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T> |
| 748 | /// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or |
| 749 | /// `.need_gc()`. |
| 750 | trait DoGc<T> { |
| 751 | fn do_gc(self, need_gc: bool) -> Result<(bool, T)>; |
| 752 | |
| 753 | fn no_gc(self) -> Result<(bool, T)>; |
| 754 | |
| 755 | fn need_gc(self) -> Result<(bool, T)>; |
| 756 | } |
| 757 | |
| 758 | impl<T> DoGc<T> for Result<T> { |
| 759 | fn do_gc(self, need_gc: bool) -> Result<(bool, T)> { |
| 760 | self.map(|r| (need_gc, r)) |
| 761 | } |
| 762 | |
| 763 | fn no_gc(self) -> Result<(bool, T)> { |
| 764 | self.do_gc(false) |
| 765 | } |
| 766 | |
| 767 | fn need_gc(self) -> Result<(bool, T)> { |
| 768 | self.do_gc(true) |
| 769 | } |
| 770 | } |
| 771 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 772 | /// KeystoreDB wraps a connection to an SQLite database and tracks its |
| 773 | /// ownership. It also implements all of Keystore 2.0's database functionality. |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 774 | pub struct KeystoreDB { |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 775 | conn: Connection, |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 776 | gc: Option<Arc<Gc>>, |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 777 | perboot: Arc<perboot::PerbootDB>, |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 778 | } |
| 779 | |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 780 | /// Database representation of the monotonic time retrieved from the system call clock_gettime with |
Eric Biggers | 19b3b0d | 2024-01-31 22:46:47 +0000 | [diff] [blame] | 781 | /// CLOCK_BOOTTIME. Stores monotonic time as i64 in milliseconds. |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 782 | #[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)] |
Eric Biggers | 19b3b0d | 2024-01-31 22:46:47 +0000 | [diff] [blame] | 783 | pub struct BootTime(i64); |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 784 | |
Eric Biggers | 19b3b0d | 2024-01-31 22:46:47 +0000 | [diff] [blame] | 785 | impl BootTime { |
| 786 | /// Constructs a new BootTime |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 787 | pub fn now() -> Self { |
Hasini Gunasinghe | 66a2460 | 2021-05-12 19:03:12 +0000 | [diff] [blame] | 788 | Self(get_current_time_in_milliseconds()) |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 789 | } |
| 790 | |
Eric Biggers | 19b3b0d | 2024-01-31 22:46:47 +0000 | [diff] [blame] | 791 | /// Returns the value of BootTime in milliseconds as i64 |
Hasini Gunasinghe | 66a2460 | 2021-05-12 19:03:12 +0000 | [diff] [blame] | 792 | pub fn milliseconds(&self) -> i64 { |
| 793 | self.0 |
David Drysdale | 0e45a61 | 2021-02-25 17:24:36 +0000 | [diff] [blame] | 794 | } |
| 795 | |
Eric Biggers | 19b3b0d | 2024-01-31 22:46:47 +0000 | [diff] [blame] | 796 | /// Returns the integer value of BootTime as i64 |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 797 | pub fn seconds(&self) -> i64 { |
Hasini Gunasinghe | 66a2460 | 2021-05-12 19:03:12 +0000 | [diff] [blame] | 798 | self.0 / 1000 |
Hasini Gunasinghe | b3715fb | 2021-02-26 20:34:45 +0000 | [diff] [blame] | 799 | } |
| 800 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 801 | /// Like i64::checked_sub. |
| 802 | pub fn checked_sub(&self, other: &Self) -> Option<Self> { |
| 803 | self.0.checked_sub(other.0).map(Self) |
| 804 | } |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 805 | } |
| 806 | |
Eric Biggers | 19b3b0d | 2024-01-31 22:46:47 +0000 | [diff] [blame] | 807 | impl ToSql for BootTime { |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 808 | fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { |
| 809 | Ok(ToSqlOutput::Owned(Value::Integer(self.0))) |
| 810 | } |
| 811 | } |
| 812 | |
Eric Biggers | 19b3b0d | 2024-01-31 22:46:47 +0000 | [diff] [blame] | 813 | impl FromSql for BootTime { |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 814 | fn column_result(value: ValueRef) -> FromSqlResult<Self> { |
| 815 | Ok(Self(i64::column_result(value)?)) |
| 816 | } |
| 817 | } |
| 818 | |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 819 | /// This struct encapsulates the information to be stored in the database about the auth tokens |
| 820 | /// received by keystore. |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 821 | #[derive(Clone)] |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 822 | pub struct AuthTokenEntry { |
| 823 | auth_token: HardwareAuthToken, |
Hasini Gunasinghe | 66a2460 | 2021-05-12 19:03:12 +0000 | [diff] [blame] | 824 | // Time received in milliseconds |
Eric Biggers | 19b3b0d | 2024-01-31 22:46:47 +0000 | [diff] [blame] | 825 | time_received: BootTime, |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 826 | } |
| 827 | |
| 828 | impl AuthTokenEntry { |
Eric Biggers | 19b3b0d | 2024-01-31 22:46:47 +0000 | [diff] [blame] | 829 | fn new(auth_token: HardwareAuthToken, time_received: BootTime) -> Self { |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 830 | AuthTokenEntry { auth_token, time_received } |
| 831 | } |
| 832 | |
| 833 | /// Checks if this auth token satisfies the given authentication information. |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 834 | pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool { |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 835 | user_secure_ids.iter().any(|&sid| { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 836 | (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId) |
Charisee | 03e0084 | 2023-01-25 01:41:23 +0000 | [diff] [blame] | 837 | && ((auth_type.0 & self.auth_token.authenticatorType.0) != 0) |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 838 | }) |
| 839 | } |
| 840 | |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 841 | /// Returns the auth token wrapped by the AuthTokenEntry |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 842 | pub fn auth_token(&self) -> &HardwareAuthToken { |
| 843 | &self.auth_token |
| 844 | } |
| 845 | |
| 846 | /// Returns the auth token wrapped by the AuthTokenEntry |
| 847 | pub fn take_auth_token(self) -> HardwareAuthToken { |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 848 | self.auth_token |
| 849 | } |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 850 | |
| 851 | /// Returns the time that this auth token was received. |
Eric Biggers | 19b3b0d | 2024-01-31 22:46:47 +0000 | [diff] [blame] | 852 | pub fn time_received(&self) -> BootTime { |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 853 | self.time_received |
| 854 | } |
Hasini Gunasinghe | b3715fb | 2021-02-26 20:34:45 +0000 | [diff] [blame] | 855 | |
| 856 | /// Returns the challenge value of the auth token. |
| 857 | pub fn challenge(&self) -> i64 { |
| 858 | self.auth_token.challenge |
| 859 | } |
Hasini Gunasinghe | 52333ba | 2020-11-06 01:24:16 +0000 | [diff] [blame] | 860 | } |
| 861 | |
David Drysdale | f1ba381 | 2024-05-08 17:50:13 +0100 | [diff] [blame] | 862 | /// Information about a superseded blob (a blob that is no longer the |
| 863 | /// most recent blob of that type for a given key, due to upgrade or |
| 864 | /// replacement). |
| 865 | pub struct SupersededBlob { |
| 866 | /// ID |
| 867 | pub blob_id: i64, |
| 868 | /// Contents. |
| 869 | pub blob: Vec<u8>, |
| 870 | /// Metadata. |
| 871 | pub metadata: BlobMetaData, |
| 872 | } |
| 873 | |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 874 | impl KeystoreDB { |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 875 | const UNASSIGNED_KEY_ID: i64 = -1i64; |
Janis Danisevskis | cfaf919 | 2021-05-26 16:31:02 -0700 | [diff] [blame] | 876 | const CURRENT_DB_VERSION: u32 = 1; |
| 877 | const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1]; |
Janis Danisevskis | b00ebd0 | 2021-02-02 21:52:24 -0800 | [diff] [blame] | 878 | |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 879 | /// Name of the file that holds the cross-boot persistent database. |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 880 | pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite"; |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 881 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 882 | /// This will create a new database connection connecting the two |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 883 | /// files persistent.sqlite and perboot.sqlite in the given directory. |
| 884 | /// It also attempts to initialize all of the tables. |
| 885 | /// KeystoreDB cannot be used by multiple threads. |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 886 | /// Each thread should open their own connection using `thread_local!`. |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 887 | pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 888 | let _wp = wd::watch("KeystoreDB::new"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 889 | |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 890 | let persistent_path = Self::make_persistent_path(db_root)?; |
Seth Moore | 472fcbb | 2021-05-12 10:07:51 -0700 | [diff] [blame] | 891 | let conn = Self::make_connection(&persistent_path)?; |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 892 | |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 893 | let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() }; |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 894 | db.with_transaction(Immediate("TX_new"), |tx| { |
Janis Danisevskis | cfaf919 | 2021-05-26 16:31:02 -0700 | [diff] [blame] | 895 | versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 896 | .context(ks_err!("KeystoreDB::new: trying to upgrade database."))?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 897 | Self::init_tables(tx).context("Trying to initialize tables.").no_gc() |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 898 | })?; |
| 899 | Ok(db) |
Joel Galenson | 2aab443 | 2020-07-22 15:27:57 -0700 | [diff] [blame] | 900 | } |
| 901 | |
Janis Danisevskis | cfaf919 | 2021-05-26 16:31:02 -0700 | [diff] [blame] | 902 | // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before |
| 903 | // cryptographic binding to the boot level keys was implemented. |
| 904 | fn from_0_to_1(tx: &Transaction) -> Result<u32> { |
| 905 | tx.execute( |
| 906 | "UPDATE persistent.keyentry SET state = ? |
| 907 | WHERE |
| 908 | id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?) |
| 909 | AND |
| 910 | id NOT IN ( |
| 911 | SELECT keyentryid FROM persistent.blobentry |
| 912 | WHERE id IN ( |
| 913 | SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ? |
| 914 | ) |
| 915 | );", |
| 916 | params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel], |
| 917 | ) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 918 | .context(ks_err!("Failed to delete logical boot level keys."))?; |
Janis Danisevskis | cfaf919 | 2021-05-26 16:31:02 -0700 | [diff] [blame] | 919 | Ok(1) |
| 920 | } |
| 921 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 922 | fn init_tables(tx: &Transaction) -> Result<()> { |
| 923 | tx.execute( |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 924 | "CREATE TABLE IF NOT EXISTS persistent.keyentry ( |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 925 | id INTEGER UNIQUE, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 926 | key_type INTEGER, |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 927 | domain INTEGER, |
| 928 | namespace INTEGER, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 929 | alias BLOB, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 930 | state INTEGER, |
| 931 | km_uuid BLOB);", |
Andrew Walbran | 78abb1e | 2023-05-30 16:20:56 +0000 | [diff] [blame] | 932 | [], |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 933 | ) |
| 934 | .context("Failed to initialize \"keyentry\" table.")?; |
| 935 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 936 | tx.execute( |
Janis Danisevskis | a543818 | 2021-02-02 14:22:59 -0800 | [diff] [blame] | 937 | "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index |
| 938 | ON keyentry(id);", |
Andrew Walbran | 78abb1e | 2023-05-30 16:20:56 +0000 | [diff] [blame] | 939 | [], |
Janis Danisevskis | a543818 | 2021-02-02 14:22:59 -0800 | [diff] [blame] | 940 | ) |
| 941 | .context("Failed to create index keyentry_id_index.")?; |
| 942 | |
| 943 | tx.execute( |
| 944 | "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index |
| 945 | ON keyentry(domain, namespace, alias);", |
Andrew Walbran | 78abb1e | 2023-05-30 16:20:56 +0000 | [diff] [blame] | 946 | [], |
Janis Danisevskis | a543818 | 2021-02-02 14:22:59 -0800 | [diff] [blame] | 947 | ) |
| 948 | .context("Failed to create index keyentry_domain_namespace_index.")?; |
| 949 | |
| 950 | tx.execute( |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 951 | "CREATE TABLE IF NOT EXISTS persistent.blobentry ( |
| 952 | id INTEGER PRIMARY KEY, |
| 953 | subcomponent_type INTEGER, |
| 954 | keyentryid INTEGER, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 955 | blob BLOB);", |
Andrew Walbran | 78abb1e | 2023-05-30 16:20:56 +0000 | [diff] [blame] | 956 | [], |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 957 | ) |
| 958 | .context("Failed to initialize \"blobentry\" table.")?; |
| 959 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 960 | tx.execute( |
Janis Danisevskis | a543818 | 2021-02-02 14:22:59 -0800 | [diff] [blame] | 961 | "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index |
| 962 | ON blobentry(keyentryid);", |
Andrew Walbran | 78abb1e | 2023-05-30 16:20:56 +0000 | [diff] [blame] | 963 | [], |
Janis Danisevskis | a543818 | 2021-02-02 14:22:59 -0800 | [diff] [blame] | 964 | ) |
| 965 | .context("Failed to create index blobentry_keyentryid_index.")?; |
| 966 | |
| 967 | tx.execute( |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 968 | "CREATE TABLE IF NOT EXISTS persistent.blobmetadata ( |
| 969 | id INTEGER PRIMARY KEY, |
| 970 | blobentryid INTEGER, |
| 971 | tag INTEGER, |
| 972 | data ANY, |
| 973 | UNIQUE (blobentryid, tag));", |
Andrew Walbran | 78abb1e | 2023-05-30 16:20:56 +0000 | [diff] [blame] | 974 | [], |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 975 | ) |
| 976 | .context("Failed to initialize \"blobmetadata\" table.")?; |
| 977 | |
| 978 | tx.execute( |
| 979 | "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index |
| 980 | ON blobmetadata(blobentryid);", |
Andrew Walbran | 78abb1e | 2023-05-30 16:20:56 +0000 | [diff] [blame] | 981 | [], |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 982 | ) |
| 983 | .context("Failed to create index blobmetadata_blobentryid_index.")?; |
| 984 | |
| 985 | tx.execute( |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 986 | "CREATE TABLE IF NOT EXISTS persistent.keyparameter ( |
Hasini Gunasinghe | af99366 | 2020-07-24 18:40:20 +0000 | [diff] [blame] | 987 | keyentryid INTEGER, |
| 988 | tag INTEGER, |
| 989 | data ANY, |
| 990 | security_level INTEGER);", |
Andrew Walbran | 78abb1e | 2023-05-30 16:20:56 +0000 | [diff] [blame] | 991 | [], |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 992 | ) |
| 993 | .context("Failed to initialize \"keyparameter\" table.")?; |
| 994 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 995 | tx.execute( |
Janis Danisevskis | a543818 | 2021-02-02 14:22:59 -0800 | [diff] [blame] | 996 | "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index |
| 997 | ON keyparameter(keyentryid);", |
Andrew Walbran | 78abb1e | 2023-05-30 16:20:56 +0000 | [diff] [blame] | 998 | [], |
Janis Danisevskis | a543818 | 2021-02-02 14:22:59 -0800 | [diff] [blame] | 999 | ) |
| 1000 | .context("Failed to create index keyparameter_keyentryid_index.")?; |
| 1001 | |
| 1002 | tx.execute( |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1003 | "CREATE TABLE IF NOT EXISTS persistent.keymetadata ( |
| 1004 | keyentryid INTEGER, |
| 1005 | tag INTEGER, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 1006 | data ANY, |
| 1007 | UNIQUE (keyentryid, tag));", |
Andrew Walbran | 78abb1e | 2023-05-30 16:20:56 +0000 | [diff] [blame] | 1008 | [], |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1009 | ) |
| 1010 | .context("Failed to initialize \"keymetadata\" table.")?; |
| 1011 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1012 | tx.execute( |
Janis Danisevskis | a543818 | 2021-02-02 14:22:59 -0800 | [diff] [blame] | 1013 | "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index |
| 1014 | ON keymetadata(keyentryid);", |
Andrew Walbran | 78abb1e | 2023-05-30 16:20:56 +0000 | [diff] [blame] | 1015 | [], |
Janis Danisevskis | a543818 | 2021-02-02 14:22:59 -0800 | [diff] [blame] | 1016 | ) |
| 1017 | .context("Failed to create index keymetadata_keyentryid_index.")?; |
| 1018 | |
| 1019 | tx.execute( |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 1020 | "CREATE TABLE IF NOT EXISTS persistent.grant ( |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1021 | id INTEGER UNIQUE, |
| 1022 | grantee INTEGER, |
| 1023 | keyentryid INTEGER, |
| 1024 | access_vector INTEGER);", |
Andrew Walbran | 78abb1e | 2023-05-30 16:20:56 +0000 | [diff] [blame] | 1025 | [], |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1026 | ) |
| 1027 | .context("Failed to initialize \"grant\" table.")?; |
| 1028 | |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 1029 | Ok(()) |
| 1030 | } |
| 1031 | |
Seth Moore | 472fcbb | 2021-05-12 10:07:51 -0700 | [diff] [blame] | 1032 | fn make_persistent_path(db_root: &Path) -> Result<String> { |
| 1033 | // Build the path to the sqlite file. |
| 1034 | let mut persistent_path = db_root.to_path_buf(); |
| 1035 | persistent_path.push(Self::PERSISTENT_DB_FILENAME); |
| 1036 | |
| 1037 | // Now convert them to strings prefixed with "file:" |
| 1038 | let mut persistent_path_str = "file:".to_owned(); |
| 1039 | persistent_path_str.push_str(&persistent_path.to_string_lossy()); |
| 1040 | |
Shaquille Johnson | 52b8c93 | 2023-12-19 19:45:32 +0000 | [diff] [blame] | 1041 | // Connect to database in specific mode |
| 1042 | let persistent_path_mode = if keystore2_flags::wal_db_journalmode_v3() { |
| 1043 | "?journal_mode=WAL".to_owned() |
| 1044 | } else { |
| 1045 | "?journal_mode=DELETE".to_owned() |
| 1046 | }; |
| 1047 | persistent_path_str.push_str(&persistent_path_mode); |
| 1048 | |
Seth Moore | 472fcbb | 2021-05-12 10:07:51 -0700 | [diff] [blame] | 1049 | Ok(persistent_path_str) |
| 1050 | } |
| 1051 | |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 1052 | fn make_connection(persistent_file: &str) -> Result<Connection> { |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 1053 | let conn = |
| 1054 | Connection::open_in_memory().context("Failed to initialize SQLite connection.")?; |
| 1055 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1056 | loop { |
| 1057 | if let Err(e) = conn |
| 1058 | .execute("ATTACH DATABASE ? as persistent;", params![persistent_file]) |
| 1059 | .context("Failed to attach database persistent.") |
| 1060 | { |
| 1061 | if Self::is_locked_error(&e) { |
David Drysdale | 115c472 | 2024-04-15 14:11:52 +0100 | [diff] [blame] | 1062 | std::thread::sleep(DB_BUSY_RETRY_INTERVAL); |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1063 | continue; |
| 1064 | } else { |
| 1065 | return Err(e); |
| 1066 | } |
| 1067 | } |
| 1068 | break; |
| 1069 | } |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 1070 | |
Matthew Maurer | 4fb1911 | 2021-05-06 15:40:44 -0700 | [diff] [blame] | 1071 | // Drop the cache size from default (2M) to 0.5M |
| 1072 | conn.execute("PRAGMA persistent.cache_size = -500;", params![]) |
| 1073 | .context("Failed to decrease cache size for persistent db")?; |
Matthew Maurer | 4fb1911 | 2021-05-06 15:40:44 -0700 | [diff] [blame] | 1074 | |
Janis Danisevskis | 4df44f4 | 2020-08-26 14:40:03 -0700 | [diff] [blame] | 1075 | Ok(conn) |
| 1076 | } |
| 1077 | |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1078 | fn do_table_size_query( |
| 1079 | &mut self, |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1080 | storage_type: MetricsStorage, |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1081 | query: &str, |
| 1082 | params: &[&str], |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1083 | ) -> Result<StorageStats> { |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1084 | let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| { |
Joel Galenson | ff79e36 | 2021-05-25 16:30:17 -0700 | [diff] [blame] | 1085 | tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?))) |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1086 | .with_context(|| { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1087 | ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0) |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1088 | }) |
| 1089 | .no_gc() |
| 1090 | })?; |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1091 | Ok(StorageStats { storage_type, size: total, unused_size: unused }) |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1092 | } |
| 1093 | |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1094 | fn get_total_size(&mut self) -> Result<StorageStats> { |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1095 | self.do_table_size_query( |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1096 | MetricsStorage::DATABASE, |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1097 | "SELECT page_count * page_size, freelist_count * page_size |
| 1098 | FROM pragma_page_count('persistent'), |
| 1099 | pragma_page_size('persistent'), |
| 1100 | persistent.pragma_freelist_count();", |
| 1101 | &[], |
| 1102 | ) |
| 1103 | } |
| 1104 | |
| 1105 | fn get_table_size( |
| 1106 | &mut self, |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1107 | storage_type: MetricsStorage, |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1108 | schema: &str, |
| 1109 | table: &str, |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1110 | ) -> Result<StorageStats> { |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1111 | self.do_table_size_query( |
| 1112 | storage_type, |
| 1113 | "SELECT pgsize,unused FROM dbstat(?1) |
| 1114 | WHERE name=?2 AND aggregate=TRUE;", |
| 1115 | &[schema, table], |
| 1116 | ) |
| 1117 | } |
| 1118 | |
| 1119 | /// Fetches a storage statisitics atom for a given storage type. For storage |
| 1120 | /// types that map to a table, information about the table's storage is |
| 1121 | /// returned. Requests for storage types that are not DB tables return None. |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1122 | pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 1123 | let _wp = wd::watch("KeystoreDB::get_storage_stat"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 1124 | |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1125 | match storage_type { |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1126 | MetricsStorage::DATABASE => self.get_total_size(), |
| 1127 | MetricsStorage::KEY_ENTRY => { |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1128 | self.get_table_size(storage_type, "persistent", "keyentry") |
| 1129 | } |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1130 | MetricsStorage::KEY_ENTRY_ID_INDEX => { |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1131 | self.get_table_size(storage_type, "persistent", "keyentry_id_index") |
| 1132 | } |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1133 | MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => { |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1134 | self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index") |
| 1135 | } |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1136 | MetricsStorage::BLOB_ENTRY => { |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1137 | self.get_table_size(storage_type, "persistent", "blobentry") |
| 1138 | } |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1139 | MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => { |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1140 | self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index") |
| 1141 | } |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1142 | MetricsStorage::KEY_PARAMETER => { |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1143 | self.get_table_size(storage_type, "persistent", "keyparameter") |
| 1144 | } |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1145 | MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => { |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1146 | self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index") |
| 1147 | } |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1148 | MetricsStorage::KEY_METADATA => { |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1149 | self.get_table_size(storage_type, "persistent", "keymetadata") |
| 1150 | } |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1151 | MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => { |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1152 | self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index") |
| 1153 | } |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1154 | MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"), |
| 1155 | MetricsStorage::AUTH_TOKEN => { |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 1156 | // Since the table is actually a BTreeMap now, unused_size is not meaningfully |
| 1157 | // reportable |
| 1158 | // Size provided is only an approximation |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1159 | Ok(StorageStats { |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 1160 | storage_type, |
| 1161 | size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>()) |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1162 | as i32, |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 1163 | unused_size: 0, |
| 1164 | }) |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1165 | } |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1166 | MetricsStorage::BLOB_METADATA => { |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1167 | self.get_table_size(storage_type, "persistent", "blobmetadata") |
| 1168 | } |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1169 | MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => { |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1170 | self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index") |
| 1171 | } |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1172 | _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))), |
Seth Moore | 78c091f | 2021-04-09 21:38:30 +0000 | [diff] [blame] | 1173 | } |
| 1174 | } |
| 1175 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1176 | /// This function is intended to be used by the garbage collector. |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 1177 | /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs` |
| 1178 | /// superseded key blobs that might need special handling by the garbage collector. |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1179 | /// If no further superseded blobs can be found it deletes all other superseded blobs that don't |
| 1180 | /// need special handling and returns None. |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 1181 | pub fn handle_next_superseded_blobs( |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1182 | &mut self, |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 1183 | blob_ids_to_delete: &[i64], |
| 1184 | max_blobs: usize, |
David Drysdale | f1ba381 | 2024-05-08 17:50:13 +0100 | [diff] [blame] | 1185 | ) -> Result<Vec<SupersededBlob>> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 1186 | let _wp = wd::watch("KeystoreDB::handle_next_superseded_blob"); |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 1187 | self.with_transaction(Immediate("TX_handle_next_superseded_blob"), |tx| { |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 1188 | // Delete the given blobs. |
| 1189 | for blob_id in blob_ids_to_delete { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1190 | tx.execute( |
| 1191 | "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;", |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 1192 | params![blob_id], |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1193 | ) |
Shaquille Johnson | f23fc94 | 2024-02-13 17:01:29 +0000 | [diff] [blame] | 1194 | .context(ks_err!("Trying to delete blob metadata: {:?}", blob_id))?; |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 1195 | tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id]) |
Shaquille Johnson | f23fc94 | 2024-02-13 17:01:29 +0000 | [diff] [blame] | 1196 | .context(ks_err!("Trying to delete blob: {:?}", blob_id))?; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1197 | } |
Janis Danisevskis | 3cba10d | 2021-05-06 17:02:19 -0700 | [diff] [blame] | 1198 | |
| 1199 | Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?; |
| 1200 | |
David Drysdale | f1ba381 | 2024-05-08 17:50:13 +0100 | [diff] [blame] | 1201 | // Find up to `max_blobs` more superseded key blobs, load their metadata and return it. |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 1202 | let result: Vec<(i64, Vec<u8>)> = { |
David Drysdale | c652f6c | 2024-07-18 13:01:23 +0100 | [diff] [blame] | 1203 | let _wp = wd::watch("KeystoreDB::handle_next_superseded_blob find_next"); |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 1204 | let mut stmt = tx |
| 1205 | .prepare( |
| 1206 | "SELECT id, blob FROM persistent.blobentry |
| 1207 | WHERE subcomponent_type = ? |
| 1208 | AND ( |
| 1209 | id NOT IN ( |
| 1210 | SELECT MAX(id) FROM persistent.blobentry |
| 1211 | WHERE subcomponent_type = ? |
| 1212 | GROUP BY keyentryid, subcomponent_type |
| 1213 | ) |
| 1214 | OR keyentryid NOT IN (SELECT id FROM persistent.keyentry) |
| 1215 | ) LIMIT ?;", |
| 1216 | ) |
| 1217 | .context("Trying to prepare query for superseded blobs.")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1218 | |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 1219 | let rows = stmt |
| 1220 | .query_map( |
| 1221 | params![ |
| 1222 | SubComponentType::KEY_BLOB, |
| 1223 | SubComponentType::KEY_BLOB, |
| 1224 | max_blobs as i64, |
| 1225 | ], |
| 1226 | |row| Ok((row.get(0)?, row.get(1)?)), |
| 1227 | ) |
| 1228 | .context("Trying to query superseded blob.")?; |
| 1229 | |
| 1230 | rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>() |
| 1231 | .context("Trying to extract superseded blobs.")? |
| 1232 | }; |
| 1233 | |
David Drysdale | c652f6c | 2024-07-18 13:01:23 +0100 | [diff] [blame] | 1234 | let _wp = wd::watch("KeystoreDB::handle_next_superseded_blob load_metadata"); |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 1235 | let result = result |
| 1236 | .into_iter() |
| 1237 | .map(|(blob_id, blob)| { |
David Drysdale | f1ba381 | 2024-05-08 17:50:13 +0100 | [diff] [blame] | 1238 | Ok(SupersededBlob { |
| 1239 | blob_id, |
| 1240 | blob, |
| 1241 | metadata: BlobMetaData::load_from_db(blob_id, tx)?, |
| 1242 | }) |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 1243 | }) |
David Drysdale | f1ba381 | 2024-05-08 17:50:13 +0100 | [diff] [blame] | 1244 | .collect::<Result<Vec<_>>>() |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 1245 | .context("Trying to load blob metadata.")?; |
| 1246 | if !result.is_empty() { |
| 1247 | return Ok(result).no_gc(); |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1248 | } |
| 1249 | |
| 1250 | // We did not find any superseded key blob, so let's remove other superseded blob in |
| 1251 | // one transaction. |
David Drysdale | c652f6c | 2024-07-18 13:01:23 +0100 | [diff] [blame] | 1252 | let _wp = wd::watch("KeystoreDB::handle_next_superseded_blob delete"); |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1253 | tx.execute( |
| 1254 | "DELETE FROM persistent.blobentry |
| 1255 | WHERE NOT subcomponent_type = ? |
| 1256 | AND ( |
| 1257 | id NOT IN ( |
| 1258 | SELECT MAX(id) FROM persistent.blobentry |
| 1259 | WHERE NOT subcomponent_type = ? |
| 1260 | GROUP BY keyentryid, subcomponent_type |
| 1261 | ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry) |
| 1262 | );", |
| 1263 | params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB], |
| 1264 | ) |
| 1265 | .context("Trying to purge superseded blobs.")?; |
| 1266 | |
Janis Danisevskis | 3395f86 | 2021-05-06 10:54:17 -0700 | [diff] [blame] | 1267 | Ok(vec![]).no_gc() |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1268 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1269 | .context(ks_err!()) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1270 | } |
| 1271 | |
| 1272 | /// This maintenance function should be called only once before the database is used for the |
| 1273 | /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state. |
| 1274 | /// The function transitions all key entries from Existing to Unreferenced unconditionally and |
| 1275 | /// returns the number of rows affected. If this returns a value greater than 0, it means that |
| 1276 | /// Keystore crashed at some point during key generation. Callers may want to log such |
| 1277 | /// occurrences. |
| 1278 | /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made |
| 1279 | /// it to `KeyLifeCycle::Live` may have grants. |
| 1280 | pub fn cleanup_leftovers(&mut self) -> Result<usize> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 1281 | let _wp = wd::watch("KeystoreDB::cleanup_leftovers"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 1282 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 1283 | self.with_transaction(Immediate("TX_cleanup_leftovers"), |tx| { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1284 | tx.execute( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1285 | "UPDATE persistent.keyentry SET state = ? WHERE state = ?;", |
| 1286 | params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing], |
| 1287 | ) |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1288 | .context("Failed to execute query.") |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1289 | .need_gc() |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1290 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1291 | .context(ks_err!()) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1292 | } |
| 1293 | |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1294 | /// Checks if a key exists with given key type and key descriptor properties. |
| 1295 | pub fn key_exists( |
| 1296 | &mut self, |
| 1297 | domain: Domain, |
| 1298 | nspace: i64, |
| 1299 | alias: &str, |
| 1300 | key_type: KeyType, |
| 1301 | ) -> Result<bool> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 1302 | let _wp = wd::watch("KeystoreDB::key_exists"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 1303 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 1304 | self.with_transaction(Immediate("TX_key_exists"), |tx| { |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1305 | let key_descriptor = |
| 1306 | KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None }; |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 1307 | let result = Self::load_key_entry_id(tx, &key_descriptor, key_type); |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1308 | match result { |
| 1309 | Ok(_) => Ok(true), |
| 1310 | Err(error) => match error.root_cause().downcast_ref::<KsError>() { |
| 1311 | Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false), |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1312 | _ => Err(error).context(ks_err!("Failed to find if the key exists.")), |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1313 | }, |
| 1314 | } |
| 1315 | .no_gc() |
| 1316 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1317 | .context(ks_err!()) |
Hasini Gunasinghe | 0e16145 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1318 | } |
| 1319 | |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1320 | /// Stores a super key in the database. |
| 1321 | pub fn store_super_key( |
| 1322 | &mut self, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 1323 | user_id: u32, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 1324 | key_type: &SuperKeyType, |
| 1325 | blob: &[u8], |
| 1326 | blob_metadata: &BlobMetaData, |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 1327 | key_metadata: &KeyMetaData, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1328 | ) -> Result<KeyEntry> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 1329 | let _wp = wd::watch("KeystoreDB::store_super_key"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 1330 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 1331 | self.with_transaction(Immediate("TX_store_super_key"), |tx| { |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1332 | let key_id = Self::insert_with_retry(|id| { |
| 1333 | tx.execute( |
| 1334 | "INSERT into persistent.keyentry |
| 1335 | (id, key_type, domain, namespace, alias, state, km_uuid) |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 1336 | VALUES(?, ?, ?, ?, ?, ?, ?);", |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1337 | params![ |
| 1338 | id, |
| 1339 | KeyType::Super, |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 1340 | Domain::APP.0, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 1341 | user_id as i64, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 1342 | key_type.alias, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1343 | KeyLifeCycle::Live, |
| 1344 | &KEYSTORE_UUID, |
| 1345 | ], |
| 1346 | ) |
| 1347 | }) |
| 1348 | .context("Failed to insert into keyentry table.")?; |
| 1349 | |
Paul Crowley | 8d5b253 | 2021-03-19 10:53:07 -0700 | [diff] [blame] | 1350 | key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?; |
| 1351 | |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1352 | Self::set_blob_internal( |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 1353 | tx, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1354 | key_id, |
| 1355 | SubComponentType::KEY_BLOB, |
| 1356 | Some(blob), |
| 1357 | Some(blob_metadata), |
| 1358 | ) |
| 1359 | .context("Failed to store key blob.")?; |
| 1360 | |
| 1361 | Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id) |
| 1362 | .context("Trying to load key components.") |
| 1363 | .no_gc() |
| 1364 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1365 | .context(ks_err!()) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 1366 | } |
| 1367 | |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 1368 | /// Loads super key of a given user, if exists |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 1369 | pub fn load_super_key( |
| 1370 | &mut self, |
| 1371 | key_type: &SuperKeyType, |
| 1372 | user_id: u32, |
| 1373 | ) -> Result<Option<(KeyIdGuard, KeyEntry)>> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 1374 | let _wp = wd::watch("KeystoreDB::load_super_key"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 1375 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 1376 | self.with_transaction(Immediate("TX_load_super_key"), |tx| { |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 1377 | let key_descriptor = KeyDescriptor { |
| 1378 | domain: Domain::APP, |
Hasini Gunasinghe | 3ed5da7 | 2021-02-04 15:18:54 +0000 | [diff] [blame] | 1379 | nspace: user_id as i64, |
Paul Crowley | 7a65839 | 2021-03-18 17:08:20 -0700 | [diff] [blame] | 1380 | alias: Some(key_type.alias.into()), |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 1381 | blob: None, |
| 1382 | }; |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 1383 | let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super); |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 1384 | match id { |
| 1385 | Ok(id) => { |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 1386 | let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1387 | .context(ks_err!("Failed to load key entry."))?; |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 1388 | Ok(Some((KEY_ID_LOCK.get(id), key_entry))) |
| 1389 | } |
| 1390 | Err(error) => match error.root_cause().downcast_ref::<KsError>() { |
| 1391 | Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None), |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1392 | _ => Err(error).context(ks_err!()), |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 1393 | }, |
| 1394 | } |
| 1395 | .no_gc() |
| 1396 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1397 | .context(ks_err!()) |
Hasini Gunasinghe | 731e3c8 | 2021-02-06 00:56:28 +0000 | [diff] [blame] | 1398 | } |
| 1399 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1400 | /// 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] | 1401 | /// The transaction is committed only if f returns Ok and retried if DatabaseBusy |
| 1402 | /// or DatabaseLocked is encountered. |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1403 | fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T> |
| 1404 | where |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1405 | F: Fn(&Transaction) -> Result<(bool, T)>, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1406 | { |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 1407 | let name = behavior.name(); |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1408 | loop { |
James Farrell | efe1a2f | 2024-02-28 21:36:47 +0000 | [diff] [blame] | 1409 | let result = self |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1410 | .conn |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 1411 | .transaction_with_behavior(behavior.into()) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1412 | .context(ks_err!()) |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 1413 | .and_then(|tx| { |
| 1414 | let _wp = name.map(wd::watch); |
| 1415 | f(&tx).map(|result| (result, tx)) |
| 1416 | }) |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1417 | .and_then(|(result, tx)| { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1418 | tx.commit().context(ks_err!("Failed to commit transaction."))?; |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1419 | Ok(result) |
James Farrell | efe1a2f | 2024-02-28 21:36:47 +0000 | [diff] [blame] | 1420 | }); |
| 1421 | match result { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1422 | Ok(result) => break Ok(result), |
| 1423 | Err(e) => { |
| 1424 | if Self::is_locked_error(&e) { |
David Drysdale | 115c472 | 2024-04-15 14:11:52 +0100 | [diff] [blame] | 1425 | std::thread::sleep(DB_BUSY_RETRY_INTERVAL); |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1426 | continue; |
| 1427 | } else { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1428 | return Err(e).context(ks_err!()); |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1429 | } |
| 1430 | } |
| 1431 | } |
| 1432 | } |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1433 | .map(|(need_gc, result)| { |
| 1434 | if need_gc { |
| 1435 | if let Some(ref gc) = self.gc { |
| 1436 | gc.notify_gc(); |
| 1437 | } |
| 1438 | } |
| 1439 | result |
| 1440 | }) |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1441 | } |
| 1442 | |
| 1443 | fn is_locked_error(e: &anyhow::Error) -> bool { |
Paul Crowley | f61fee7 | 2021-03-17 14:38:44 -0700 | [diff] [blame] | 1444 | matches!( |
| 1445 | e.root_cause().downcast_ref::<rusqlite::ffi::Error>(), |
| 1446 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) |
| 1447 | | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. }) |
| 1448 | ) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1449 | } |
| 1450 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1451 | fn create_key_entry_internal( |
| 1452 | tx: &Transaction, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1453 | domain: &Domain, |
| 1454 | namespace: &i64, |
Janis Danisevskis | 0cabd71 | 2021-05-25 11:07:10 -0700 | [diff] [blame] | 1455 | key_type: KeyType, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1456 | km_uuid: &Uuid, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1457 | ) -> Result<KeyIdGuard> { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1458 | match *domain { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1459 | Domain::APP | Domain::SELINUX => {} |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 1460 | _ => { |
| 1461 | return Err(KsError::sys()) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1462 | .context(ks_err!("Domain {:?} must be either App or SELinux.", domain)); |
Joel Galenson | 0891bc1 | 2020-07-20 10:37:03 -0700 | [diff] [blame] | 1463 | } |
| 1464 | } |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1465 | Ok(KEY_ID_LOCK.get( |
| 1466 | Self::insert_with_retry(|id| { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1467 | tx.execute( |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1468 | "INSERT into persistent.keyentry |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1469 | (id, key_type, domain, namespace, alias, state, km_uuid) |
| 1470 | VALUES(?, ?, ?, ?, NULL, ?, ?);", |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1471 | params![ |
| 1472 | id, |
Janis Danisevskis | 0cabd71 | 2021-05-25 11:07:10 -0700 | [diff] [blame] | 1473 | key_type, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1474 | domain.0 as u32, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1475 | *namespace, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1476 | KeyLifeCycle::Existing, |
| 1477 | km_uuid, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1478 | ], |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1479 | ) |
| 1480 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1481 | .context(ks_err!())?, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1482 | )) |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 1483 | } |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1484 | |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1485 | /// Set a new blob and associates it with the given key id. Each blob |
| 1486 | /// has a sub component type. |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1487 | /// Each key can have one of each sub component type associated. If more |
| 1488 | /// are added only the most recent can be retrieved, and superseded blobs |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1489 | /// will get garbage collected. |
| 1490 | /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be |
| 1491 | /// removed by setting blob to None. |
| 1492 | pub fn set_blob( |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1493 | &mut self, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1494 | key_id: &KeyIdGuard, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1495 | sc_type: SubComponentType, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1496 | blob: Option<&[u8]>, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1497 | blob_metadata: Option<&BlobMetaData>, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1498 | ) -> Result<()> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 1499 | let _wp = wd::watch("KeystoreDB::set_blob"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 1500 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 1501 | self.with_transaction(Immediate("TX_set_blob"), |tx| { |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 1502 | 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] | 1503 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1504 | .context(ks_err!()) |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1505 | } |
| 1506 | |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 1507 | /// Why would we insert a deleted blob? This weird function is for the purpose of legacy |
| 1508 | /// key migration in the case where we bulk delete all the keys of an app or even a user. |
| 1509 | /// We use this to insert key blobs into the database which can then be garbage collected |
| 1510 | /// lazily by the key garbage collector. |
| 1511 | pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 1512 | let _wp = wd::watch("KeystoreDB::set_deleted_blob"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 1513 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 1514 | self.with_transaction(Immediate("TX_set_deleted_blob"), |tx| { |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 1515 | Self::set_blob_internal( |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 1516 | tx, |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 1517 | Self::UNASSIGNED_KEY_ID, |
| 1518 | SubComponentType::KEY_BLOB, |
| 1519 | Some(blob), |
| 1520 | Some(blob_metadata), |
| 1521 | ) |
| 1522 | .need_gc() |
| 1523 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1524 | .context(ks_err!()) |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 1525 | } |
| 1526 | |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1527 | fn set_blob_internal( |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1528 | tx: &Transaction, |
| 1529 | key_id: i64, |
| 1530 | sc_type: SubComponentType, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1531 | blob: Option<&[u8]>, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1532 | blob_metadata: Option<&BlobMetaData>, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1533 | ) -> Result<()> { |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1534 | match (blob, sc_type) { |
| 1535 | (Some(blob), _) => { |
| 1536 | tx.execute( |
| 1537 | "INSERT INTO persistent.blobentry |
| 1538 | (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);", |
| 1539 | params![sc_type, key_id, blob], |
| 1540 | ) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1541 | .context(ks_err!("Failed to insert blob."))?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1542 | if let Some(blob_metadata) = blob_metadata { |
| 1543 | let blob_id = tx |
Andrew Walbran | 78abb1e | 2023-05-30 16:20:56 +0000 | [diff] [blame] | 1544 | .query_row("SELECT MAX(id) FROM persistent.blobentry;", [], |row| { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1545 | row.get(0) |
| 1546 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1547 | .context(ks_err!("Failed to get new blob id."))?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1548 | blob_metadata |
| 1549 | .store_in_db(blob_id, tx) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1550 | .context(ks_err!("Trying to store blob metadata."))?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1551 | } |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1552 | } |
| 1553 | (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => { |
| 1554 | tx.execute( |
| 1555 | "DELETE FROM persistent.blobentry |
| 1556 | WHERE subcomponent_type = ? AND keyentryid = ?;", |
| 1557 | params![sc_type, key_id], |
| 1558 | ) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1559 | .context(ks_err!("Failed to delete blob."))?; |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1560 | } |
| 1561 | (None, _) => { |
| 1562 | return Err(KsError::sys()) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1563 | .context(ks_err!("Other blobs cannot be deleted in this way.")); |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1564 | } |
| 1565 | } |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1566 | Ok(()) |
| 1567 | } |
| 1568 | |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1569 | /// Inserts a collection of key parameters into the `persistent.keyparameter` table |
| 1570 | /// and associates them with the given `key_id`. |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1571 | #[cfg(test)] |
| 1572 | fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> { |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 1573 | self.with_transaction(Immediate("TX_insert_keyparameter"), |tx| { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1574 | Self::insert_keyparameter_internal(tx, key_id, params).no_gc() |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1575 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1576 | .context(ks_err!()) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1577 | } |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1578 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1579 | fn insert_keyparameter_internal( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1580 | tx: &Transaction, |
| 1581 | key_id: &KeyIdGuard, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1582 | params: &[KeyParameter], |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1583 | ) -> Result<()> { |
| 1584 | let mut stmt = tx |
| 1585 | .prepare( |
| 1586 | "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level) |
| 1587 | VALUES (?, ?, ?, ?);", |
| 1588 | ) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1589 | .context(ks_err!("Failed to prepare statement."))?; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1590 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1591 | for p in params.iter() { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1592 | stmt.insert(params![ |
| 1593 | key_id.0, |
| 1594 | p.get_tag().0, |
| 1595 | p.key_parameter_value(), |
| 1596 | p.security_level().0 |
| 1597 | ]) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1598 | .with_context(|| ks_err!("Failed to insert {:?}", p))?; |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 1599 | } |
| 1600 | Ok(()) |
| 1601 | } |
| 1602 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1603 | /// Insert a set of key entry specific metadata into the database. |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1604 | #[cfg(test)] |
| 1605 | fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> { |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 1606 | self.with_transaction(Immediate("TX_insert_key_metadata"), |tx| { |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 1607 | metadata.store_in_db(key_id.0, tx).no_gc() |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1608 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1609 | .context(ks_err!()) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1610 | } |
| 1611 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1612 | /// Updates the alias column of the given key id `newid` with the given alias, |
| 1613 | /// and atomically, removes the alias, domain, and namespace from another row |
| 1614 | /// with the same alias-domain-namespace tuple if such row exits. |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1615 | /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage |
| 1616 | /// collector. |
| 1617 | fn rebind_alias( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1618 | tx: &Transaction, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 1619 | newid: &KeyIdGuard, |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1620 | alias: &str, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1621 | domain: &Domain, |
| 1622 | namespace: &i64, |
Janis Danisevskis | 0cabd71 | 2021-05-25 11:07:10 -0700 | [diff] [blame] | 1623 | key_type: KeyType, |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1624 | ) -> Result<bool> { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1625 | match *domain { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1626 | Domain::APP | Domain::SELINUX => {} |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1627 | _ => { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1628 | return Err(KsError::sys()) |
| 1629 | .context(ks_err!("Domain {:?} must be either App or SELinux.", domain)); |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1630 | } |
| 1631 | } |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1632 | let updated = tx |
| 1633 | .execute( |
| 1634 | "UPDATE persistent.keyentry |
| 1635 | SET alias = NULL, domain = NULL, namespace = NULL, state = ? |
Janis Danisevskis | 0cabd71 | 2021-05-25 11:07:10 -0700 | [diff] [blame] | 1636 | WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;", |
| 1637 | params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type], |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1638 | ) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1639 | .context(ks_err!("Failed to rebind existing entry."))?; |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1640 | let result = tx |
| 1641 | .execute( |
| 1642 | "UPDATE persistent.keyentry |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1643 | SET alias = ?, state = ? |
Janis Danisevskis | 0cabd71 | 2021-05-25 11:07:10 -0700 | [diff] [blame] | 1644 | WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;", |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1645 | params![ |
| 1646 | alias, |
| 1647 | KeyLifeCycle::Live, |
| 1648 | newid.0, |
| 1649 | domain.0 as u32, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1650 | *namespace, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1651 | KeyLifeCycle::Existing, |
Janis Danisevskis | 0cabd71 | 2021-05-25 11:07:10 -0700 | [diff] [blame] | 1652 | key_type, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1653 | ], |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1654 | ) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1655 | .context(ks_err!("Failed to set alias."))?; |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1656 | if result != 1 { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1657 | return Err(KsError::sys()).context(ks_err!( |
| 1658 | "Expected to update a single entry but instead updated {}.", |
Joel Galenson | 33c04ad | 2020-08-03 11:04:38 -0700 | [diff] [blame] | 1659 | result |
| 1660 | )); |
| 1661 | } |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1662 | Ok(updated != 0) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1663 | } |
| 1664 | |
Janis Danisevskis | cdcf4e5 | 2021-04-14 15:44:36 -0700 | [diff] [blame] | 1665 | /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination |
| 1666 | /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`. |
| 1667 | pub fn migrate_key_namespace( |
| 1668 | &mut self, |
| 1669 | key_id_guard: KeyIdGuard, |
| 1670 | destination: &KeyDescriptor, |
| 1671 | caller_uid: u32, |
| 1672 | check_permission: impl Fn(&KeyDescriptor) -> Result<()>, |
| 1673 | ) -> Result<()> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 1674 | let _wp = wd::watch("KeystoreDB::migrate_key_namespace"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 1675 | |
Janis Danisevskis | cdcf4e5 | 2021-04-14 15:44:36 -0700 | [diff] [blame] | 1676 | let destination = match destination.domain { |
| 1677 | Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() }, |
| 1678 | Domain::SELINUX => (*destination).clone(), |
| 1679 | domain => { |
| 1680 | return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)) |
| 1681 | .context(format!("Domain {:?} must be either APP or SELINUX.", domain)); |
| 1682 | } |
| 1683 | }; |
| 1684 | |
| 1685 | // Security critical: Must return immediately on failure. Do not remove the '?'; |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1686 | check_permission(&destination).context(ks_err!("Trying to check permission."))?; |
Janis Danisevskis | cdcf4e5 | 2021-04-14 15:44:36 -0700 | [diff] [blame] | 1687 | |
| 1688 | let alias = destination |
| 1689 | .alias |
| 1690 | .as_ref() |
| 1691 | .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1692 | .context(ks_err!("Alias must be specified."))?; |
Janis Danisevskis | cdcf4e5 | 2021-04-14 15:44:36 -0700 | [diff] [blame] | 1693 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 1694 | self.with_transaction(Immediate("TX_migrate_key_namespace"), |tx| { |
Janis Danisevskis | cdcf4e5 | 2021-04-14 15:44:36 -0700 | [diff] [blame] | 1695 | // Query the destination location. If there is a key, the migration request fails. |
| 1696 | if tx |
| 1697 | .query_row( |
| 1698 | "SELECT id FROM persistent.keyentry |
| 1699 | WHERE alias = ? AND domain = ? AND namespace = ?;", |
| 1700 | params![alias, destination.domain.0, destination.nspace], |
| 1701 | |_| Ok(()), |
| 1702 | ) |
| 1703 | .optional() |
| 1704 | .context("Failed to query destination.")? |
| 1705 | .is_some() |
| 1706 | { |
| 1707 | return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)) |
| 1708 | .context("Target already exists."); |
| 1709 | } |
| 1710 | |
| 1711 | let updated = tx |
| 1712 | .execute( |
| 1713 | "UPDATE persistent.keyentry |
| 1714 | SET alias = ?, domain = ?, namespace = ? |
| 1715 | WHERE id = ?;", |
| 1716 | params![alias, destination.domain.0, destination.nspace, key_id_guard.id()], |
| 1717 | ) |
| 1718 | .context("Failed to update key entry.")?; |
| 1719 | |
| 1720 | if updated != 1 { |
| 1721 | return Err(KsError::sys()) |
| 1722 | .context(format!("Update succeeded, but {} rows were updated.", updated)); |
| 1723 | } |
| 1724 | Ok(()).no_gc() |
| 1725 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1726 | .context(ks_err!()) |
Janis Danisevskis | cdcf4e5 | 2021-04-14 15:44:36 -0700 | [diff] [blame] | 1727 | } |
| 1728 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1729 | /// Store a new key in a single transaction. |
| 1730 | /// The function creates a new key entry, populates the blob, key parameter, and metadata |
| 1731 | /// fields, and rebinds the given alias to the new key. |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 1732 | /// The boolean returned is a hint for the garbage collector. If true, a key was replaced, |
| 1733 | /// is now unreferenced and needs to be collected. |
Chris Wailes | 3877f29 | 2021-07-26 19:24:18 -0700 | [diff] [blame] | 1734 | #[allow(clippy::too_many_arguments)] |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1735 | pub fn store_new_key( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1736 | &mut self, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1737 | key: &KeyDescriptor, |
Janis Danisevskis | 0cabd71 | 2021-05-25 11:07:10 -0700 | [diff] [blame] | 1738 | key_type: KeyType, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1739 | params: &[KeyParameter], |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 1740 | blob_info: &BlobInfo, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1741 | cert_info: &CertificateInfo, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1742 | metadata: &KeyMetaData, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1743 | km_uuid: &Uuid, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1744 | ) -> Result<KeyIdGuard> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 1745 | let _wp = wd::watch("KeystoreDB::store_new_key"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 1746 | |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1747 | let (alias, domain, namespace) = match key { |
| 1748 | KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None } |
| 1749 | | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => { |
| 1750 | (alias, key.domain, nspace) |
| 1751 | } |
| 1752 | _ => { |
| 1753 | return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1754 | .context(ks_err!("Need alias and domain must be APP or SELINUX.")); |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1755 | } |
| 1756 | }; |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 1757 | self.with_transaction(Immediate("TX_store_new_key"), |tx| { |
Janis Danisevskis | 0cabd71 | 2021-05-25 11:07:10 -0700 | [diff] [blame] | 1758 | let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1759 | .context("Trying to create new key entry.")?; |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 1760 | let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info; |
| 1761 | |
| 1762 | // In some occasions the key blob is already upgraded during the import. |
| 1763 | // In order to make sure it gets properly deleted it is inserted into the |
| 1764 | // database here and then immediately replaced by the superseding blob. |
| 1765 | // The garbage collector will then subject the blob to deleteKey of the |
| 1766 | // KM back end to permanently invalidate the key. |
| 1767 | let need_gc = if let Some((blob, blob_metadata)) = superseded_blob { |
| 1768 | Self::set_blob_internal( |
| 1769 | tx, |
| 1770 | key_id.id(), |
| 1771 | SubComponentType::KEY_BLOB, |
| 1772 | Some(blob), |
| 1773 | Some(blob_metadata), |
| 1774 | ) |
| 1775 | .context("Trying to insert superseded key blob.")?; |
| 1776 | true |
| 1777 | } else { |
| 1778 | false |
| 1779 | }; |
| 1780 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1781 | Self::set_blob_internal( |
| 1782 | tx, |
| 1783 | key_id.id(), |
| 1784 | SubComponentType::KEY_BLOB, |
| 1785 | Some(blob), |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 1786 | Some(blob_metadata), |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1787 | ) |
| 1788 | .context("Trying to insert the key blob.")?; |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1789 | if let Some(cert) = &cert_info.cert { |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 1790 | 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] | 1791 | .context("Trying to insert the certificate.")?; |
| 1792 | } |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1793 | if let Some(cert_chain) = &cert_info.cert_chain { |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1794 | Self::set_blob_internal( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1795 | tx, |
| 1796 | key_id.id(), |
| 1797 | SubComponentType::CERT_CHAIN, |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 1798 | Some(cert_chain), |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1799 | None, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1800 | ) |
| 1801 | .context("Trying to insert the certificate chain.")?; |
| 1802 | } |
| 1803 | Self::insert_keyparameter_internal(tx, &key_id, params) |
| 1804 | .context("Trying to insert key parameters.")?; |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1805 | metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?; |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 1806 | let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type) |
Janis Danisevskis | f84d0b0 | 2022-01-26 14:11:14 -0800 | [diff] [blame] | 1807 | .context("Trying to rebind alias.")? |
| 1808 | || need_gc; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1809 | Ok(key_id).do_gc(need_gc) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1810 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1811 | .context(ks_err!()) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1812 | } |
| 1813 | |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1814 | /// Store a new certificate |
| 1815 | /// The function creates a new key entry, populates the blob field and metadata, and rebinds |
| 1816 | /// the given alias to the new cert. |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1817 | pub fn store_new_certificate( |
| 1818 | &mut self, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1819 | key: &KeyDescriptor, |
Janis Danisevskis | 0cabd71 | 2021-05-25 11:07:10 -0700 | [diff] [blame] | 1820 | key_type: KeyType, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 1821 | cert: &[u8], |
| 1822 | km_uuid: &Uuid, |
| 1823 | ) -> Result<KeyIdGuard> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 1824 | let _wp = wd::watch("KeystoreDB::store_new_certificate"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 1825 | |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1826 | let (alias, domain, namespace) = match key { |
| 1827 | KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None } |
| 1828 | | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => { |
| 1829 | (alias, key.domain, nspace) |
| 1830 | } |
| 1831 | _ => { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1832 | return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)) |
| 1833 | .context(ks_err!("Need alias and domain must be APP or SELINUX.")); |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1834 | } |
| 1835 | }; |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 1836 | self.with_transaction(Immediate("TX_store_new_certificate"), |tx| { |
Janis Danisevskis | 0cabd71 | 2021-05-25 11:07:10 -0700 | [diff] [blame] | 1837 | let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid) |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1838 | .context("Trying to create new key entry.")?; |
| 1839 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1840 | Self::set_blob_internal( |
| 1841 | tx, |
| 1842 | key_id.id(), |
| 1843 | SubComponentType::CERT_CHAIN, |
| 1844 | Some(cert), |
| 1845 | None, |
| 1846 | ) |
| 1847 | .context("Trying to insert certificate.")?; |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1848 | |
| 1849 | let mut metadata = KeyMetaData::new(); |
| 1850 | metadata.add(KeyMetaEntry::CreationDate( |
| 1851 | DateTime::now().context("Trying to make creation time.")?, |
| 1852 | )); |
| 1853 | |
| 1854 | metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?; |
| 1855 | |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 1856 | let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type) |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1857 | .context("Trying to rebind alias.")?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 1858 | Ok(key_id).do_gc(need_gc) |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1859 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1860 | .context(ks_err!()) |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 1861 | } |
| 1862 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1863 | // Helper function loading the key_id given the key descriptor |
| 1864 | // tuple comprising domain, namespace, and alias. |
| 1865 | // Requires a valid transaction. |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1866 | 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] | 1867 | let alias = key |
| 1868 | .alias |
| 1869 | .as_ref() |
| 1870 | .map_or_else(|| Err(KsError::sys()), Ok) |
| 1871 | .context("In load_key_entry_id: Alias must be specified.")?; |
| 1872 | let mut stmt = tx |
| 1873 | .prepare( |
| 1874 | "SELECT id FROM persistent.keyentry |
| 1875 | WHERE |
Hasini Gunasinghe | deab85d | 2021-02-01 21:10:02 +0000 | [diff] [blame] | 1876 | key_type = ? |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1877 | AND domain = ? |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1878 | AND namespace = ? |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1879 | AND alias = ? |
| 1880 | AND state = ?;", |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1881 | ) |
| 1882 | .context("In load_key_entry_id: Failed to select from keyentry table.")?; |
| 1883 | let mut rows = stmt |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 1884 | .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] | 1885 | .context("In load_key_entry_id: Failed to read from keyentry table.")?; |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 1886 | db_utils::with_rows_extract_one(&mut rows, |row| { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1887 | row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)? |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1888 | .get(0) |
| 1889 | .context("Failed to unpack id.") |
| 1890 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 1891 | .context(ks_err!()) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1892 | } |
| 1893 | |
| 1894 | /// This helper function completes the access tuple of a key, which is required |
| 1895 | /// to perform access control. The strategy depends on the `domain` field in the |
| 1896 | /// key descriptor. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1897 | /// * Domain::SELINUX: The access tuple is complete and this function only loads |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1898 | /// the key_id for further processing. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1899 | /// * 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] | 1900 | /// which serves as the namespace. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1901 | /// * 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] | 1902 | /// `access_vector`. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1903 | /// * 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] | 1904 | /// `namespace`. |
Chris Wailes | 1806f97 | 2024-08-19 16:37:40 -0700 | [diff] [blame^] | 1905 | /// |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1906 | /// In each case the information returned is sufficient to perform the access |
| 1907 | /// check and the key id can be used to load further key artifacts. |
| 1908 | fn load_access_tuple( |
| 1909 | tx: &Transaction, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1910 | key: &KeyDescriptor, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 1911 | key_type: KeyType, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1912 | caller_uid: u32, |
| 1913 | ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> { |
| 1914 | match key.domain { |
| 1915 | // Domain App or SELinux. In this case we load the key_id from |
| 1916 | // the keyentry database for further loading of key components. |
| 1917 | // We already have the full access tuple to perform access control. |
| 1918 | // The only distinction is that we use the caller_uid instead |
| 1919 | // of the caller supplied namespace if the domain field is |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1920 | // Domain::APP. |
| 1921 | Domain::APP | Domain::SELINUX => { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1922 | let mut access_key = key.clone(); |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1923 | if access_key.domain == Domain::APP { |
| 1924 | access_key.nspace = caller_uid as i64; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1925 | } |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 1926 | 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] | 1927 | .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1928 | |
| 1929 | Ok((key_id, access_key, None)) |
| 1930 | } |
| 1931 | |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1932 | // 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] | 1933 | // from the grant table. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1934 | Domain::GRANT => { |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1935 | let mut stmt = tx |
| 1936 | .prepare( |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 1937 | "SELECT keyentryid, access_vector FROM persistent.grant |
Hasini Gunasinghe | e70a0ec | 2021-05-10 21:12:34 +0000 | [diff] [blame] | 1938 | WHERE grantee = ? AND id = ? AND |
| 1939 | (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;", |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1940 | ) |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1941 | .context("Domain::GRANT prepare statement failed")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1942 | let mut rows = stmt |
Hasini Gunasinghe | e70a0ec | 2021-05-10 21:12:34 +0000 | [diff] [blame] | 1943 | .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live]) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1944 | .context("Domain:Grant: query failed.")?; |
| 1945 | let (key_id, access_vector): (i64, i32) = |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 1946 | db_utils::with_rows_extract_one(&mut rows, |row| { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1947 | let r = |
| 1948 | row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1949 | Ok(( |
| 1950 | r.get(0).context("Failed to unpack key_id.")?, |
| 1951 | r.get(1).context("Failed to unpack access_vector.")?, |
| 1952 | )) |
| 1953 | }) |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1954 | .context("Domain::GRANT.")?; |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 1955 | Ok((key_id, key.clone(), Some(access_vector.into()))) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1956 | } |
| 1957 | |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1958 | // 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] | 1959 | // keyentry database because we need them for access control. |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1960 | Domain::KEY_ID => { |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 1961 | let (domain, namespace): (Domain, i64) = { |
| 1962 | let mut stmt = tx |
| 1963 | .prepare( |
| 1964 | "SELECT domain, namespace FROM persistent.keyentry |
| 1965 | WHERE |
| 1966 | id = ? |
| 1967 | AND state = ?;", |
| 1968 | ) |
| 1969 | .context("Domain::KEY_ID: prepare statement failed")?; |
| 1970 | let mut rows = stmt |
| 1971 | .query(params![key.nspace, KeyLifeCycle::Live]) |
| 1972 | .context("Domain::KEY_ID: query failed.")?; |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 1973 | db_utils::with_rows_extract_one(&mut rows, |row| { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1974 | let r = |
| 1975 | row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1976 | Ok(( |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 1977 | Domain(r.get(0).context("Failed to unpack domain.")?), |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 1978 | r.get(1).context("Failed to unpack namespace.")?, |
| 1979 | )) |
| 1980 | }) |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 1981 | .context("Domain::KEY_ID.")? |
| 1982 | }; |
| 1983 | |
| 1984 | // We may use a key by id after loading it by grant. |
| 1985 | // In this case we have to check if the caller has a grant for this particular |
| 1986 | // key. We can skip this if we already know that the caller is the owner. |
| 1987 | // But we cannot know this if domain is anything but App. E.g. in the case |
| 1988 | // of Domain::SELINUX we have to speculatively check for grants because we have to |
| 1989 | // consult the SEPolicy before we know if the caller is the owner. |
| 1990 | let access_vector: Option<KeyPermSet> = |
| 1991 | if domain != Domain::APP || namespace != caller_uid as i64 { |
| 1992 | let access_vector: Option<i32> = tx |
| 1993 | .query_row( |
| 1994 | "SELECT access_vector FROM persistent.grant |
| 1995 | WHERE grantee = ? AND keyentryid = ?;", |
| 1996 | params![caller_uid as i64, key.nspace], |
| 1997 | |row| row.get(0), |
| 1998 | ) |
| 1999 | .optional() |
| 2000 | .context("Domain::KEY_ID: query grant failed.")?; |
| 2001 | access_vector.map(|p| p.into()) |
| 2002 | } else { |
| 2003 | None |
| 2004 | }; |
| 2005 | |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2006 | let key_id = key.nspace; |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2007 | let mut access_key: KeyDescriptor = key.clone(); |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2008 | access_key.domain = domain; |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2009 | access_key.nspace = namespace; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2010 | |
Janis Danisevskis | 4576002 | 2021-01-19 16:34:10 -0800 | [diff] [blame] | 2011 | Ok((key_id, access_key, access_vector)) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2012 | } |
Rajesh Nyamagoud | 625e589 | 2022-05-18 01:31:26 +0000 | [diff] [blame] | 2013 | _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))), |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2014 | } |
| 2015 | } |
| 2016 | |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2017 | fn load_blob_components( |
| 2018 | key_id: i64, |
| 2019 | load_bits: KeyEntryLoadBits, |
| 2020 | tx: &Transaction, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2021 | ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> { |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2022 | let mut stmt = tx |
| 2023 | .prepare( |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2024 | "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2025 | WHERE keyentryid = ? GROUP BY subcomponent_type;", |
| 2026 | ) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2027 | .context(ks_err!("prepare statement failed."))?; |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2028 | |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2029 | let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?; |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2030 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2031 | let mut key_blob: Option<(i64, Vec<u8>)> = None; |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2032 | let mut cert_blob: Option<Vec<u8>> = None; |
| 2033 | let mut cert_chain_blob: Option<Vec<u8>> = None; |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2034 | let mut has_km_blob: bool = false; |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 2035 | db_utils::with_rows_extract_all(&mut rows, |row| { |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2036 | let sub_type: SubComponentType = |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2037 | row.get(1).context("Failed to extract subcomponent_type.")?; |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2038 | has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2039 | match (sub_type, load_bits.load_public(), load_bits.load_km()) { |
| 2040 | (SubComponentType::KEY_BLOB, _, true) => { |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2041 | key_blob = Some(( |
| 2042 | row.get(0).context("Failed to extract key blob id.")?, |
| 2043 | row.get(2).context("Failed to extract key blob.")?, |
| 2044 | )); |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2045 | } |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2046 | (SubComponentType::CERT, true, _) => { |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2047 | cert_blob = |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2048 | Some(row.get(2).context("Failed to extract public certificate blob.")?); |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2049 | } |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2050 | (SubComponentType::CERT_CHAIN, true, _) => { |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2051 | cert_chain_blob = |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2052 | Some(row.get(2).context("Failed to extract certificate chain blob.")?); |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2053 | } |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2054 | (SubComponentType::CERT, _, _) |
| 2055 | | (SubComponentType::CERT_CHAIN, _, _) |
| 2056 | | (SubComponentType::KEY_BLOB, _, _) => {} |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2057 | _ => Err(KsError::sys()).context("Unknown subcomponent type.")?, |
| 2058 | } |
| 2059 | Ok(()) |
| 2060 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2061 | .context(ks_err!())?; |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2062 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2063 | let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| { |
| 2064 | Ok(Some(( |
| 2065 | blob, |
| 2066 | BlobMetaData::load_from_db(blob_id, tx) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2067 | .context(ks_err!("Trying to load blob_metadata."))?, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2068 | ))) |
| 2069 | })?; |
| 2070 | |
| 2071 | Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob)) |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2072 | } |
| 2073 | |
| 2074 | fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> { |
| 2075 | let mut stmt = tx |
| 2076 | .prepare( |
| 2077 | "SELECT tag, data, security_level from persistent.keyparameter |
| 2078 | WHERE keyentryid = ?;", |
| 2079 | ) |
| 2080 | .context("In load_key_parameters: prepare statement failed.")?; |
| 2081 | |
| 2082 | let mut parameters: Vec<KeyParameter> = Vec::new(); |
| 2083 | |
| 2084 | let mut rows = |
| 2085 | stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?; |
Janis Danisevskis | bf15d73 | 2020-12-08 10:35:26 -0800 | [diff] [blame] | 2086 | db_utils::with_rows_extract_all(&mut rows, |row| { |
Janis Danisevskis | c5b210b | 2020-09-11 13:27:37 -0700 | [diff] [blame] | 2087 | let tag = Tag(row.get(0).context("Failed to read tag.")?); |
| 2088 | 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] | 2089 | parameters.push( |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 2090 | KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level) |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2091 | .context("Failed to read KeyParameter.")?, |
| 2092 | ); |
| 2093 | Ok(()) |
| 2094 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2095 | .context(ks_err!())?; |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2096 | |
| 2097 | Ok(parameters) |
| 2098 | } |
| 2099 | |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2100 | /// Decrements the usage count of a limited use key. This function first checks whether the |
| 2101 | /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches |
| 2102 | /// zero, the key also gets marked unreferenced and scheduled for deletion. |
| 2103 | /// 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] | 2104 | pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 2105 | let _wp = wd::watch("KeystoreDB::check_and_update_key_usage_count"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 2106 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 2107 | self.with_transaction(Immediate("TX_check_and_update_key_usage_count"), |tx| { |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2108 | let limit: Option<i32> = tx |
| 2109 | .query_row( |
| 2110 | "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;", |
| 2111 | params![key_id, Tag::USAGE_COUNT_LIMIT.0], |
| 2112 | |row| row.get(0), |
| 2113 | ) |
| 2114 | .optional() |
| 2115 | .context("Trying to load usage count")?; |
| 2116 | |
| 2117 | let limit = limit |
| 2118 | .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB)) |
| 2119 | .context("The Key no longer exists. Key is exhausted.")?; |
| 2120 | |
| 2121 | tx.execute( |
| 2122 | "UPDATE persistent.keyparameter |
| 2123 | SET data = data - 1 |
| 2124 | WHERE keyentryid = ? AND tag = ? AND data > 0;", |
| 2125 | params![key_id, Tag::USAGE_COUNT_LIMIT.0], |
| 2126 | ) |
| 2127 | .context("Failed to update key usage count.")?; |
| 2128 | |
| 2129 | match limit { |
| 2130 | 1 => Self::mark_unreferenced(tx, key_id) |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2131 | .map(|need_gc| (need_gc, ())) |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2132 | .context("Trying to mark limited use key for deletion."), |
| 2133 | 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."), |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2134 | _ => Ok(()).no_gc(), |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2135 | } |
| 2136 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2137 | .context(ks_err!()) |
Qi Wu | b9433b5 | 2020-12-01 14:52:46 +0800 | [diff] [blame] | 2138 | } |
| 2139 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2140 | /// Load a key entry by the given key descriptor. |
| 2141 | /// It uses the `check_permission` callback to verify if the access is allowed |
| 2142 | /// given the key access tuple read from the database using `load_access_tuple`. |
| 2143 | /// With `load_bits` the caller may specify which blobs shall be loaded from |
| 2144 | /// the blob database. |
| 2145 | pub fn load_key_entry( |
| 2146 | &mut self, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2147 | key: &KeyDescriptor, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2148 | key_type: KeyType, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2149 | load_bits: KeyEntryLoadBits, |
| 2150 | caller_uid: u32, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2151 | check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>, |
| 2152 | ) -> Result<(KeyIdGuard, KeyEntry)> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 2153 | let _wp = wd::watch("KeystoreDB::load_key_entry"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 2154 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2155 | loop { |
| 2156 | match self.load_key_entry_internal( |
| 2157 | key, |
| 2158 | key_type, |
| 2159 | load_bits, |
| 2160 | caller_uid, |
| 2161 | &check_permission, |
| 2162 | ) { |
| 2163 | Ok(result) => break Ok(result), |
| 2164 | Err(e) => { |
| 2165 | if Self::is_locked_error(&e) { |
David Drysdale | 115c472 | 2024-04-15 14:11:52 +0100 | [diff] [blame] | 2166 | std::thread::sleep(DB_BUSY_RETRY_INTERVAL); |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2167 | continue; |
| 2168 | } else { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2169 | return Err(e).context(ks_err!()); |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2170 | } |
| 2171 | } |
| 2172 | } |
| 2173 | } |
| 2174 | } |
| 2175 | |
| 2176 | fn load_key_entry_internal( |
| 2177 | &mut self, |
| 2178 | key: &KeyDescriptor, |
| 2179 | key_type: KeyType, |
| 2180 | load_bits: KeyEntryLoadBits, |
| 2181 | caller_uid: u32, |
| 2182 | check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2183 | ) -> Result<(KeyIdGuard, KeyEntry)> { |
| 2184 | // KEY ID LOCK 1/2 |
| 2185 | // If we got a key descriptor with a key id we can get the lock right away. |
| 2186 | // Otherwise we have to defer it until we know the key id. |
| 2187 | let key_id_guard = match key.domain { |
| 2188 | Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)), |
| 2189 | _ => None, |
| 2190 | }; |
| 2191 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2192 | let tx = self |
| 2193 | .conn |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2194 | .unchecked_transaction() |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2195 | .context(ks_err!("Failed to initialize transaction."))?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2196 | |
| 2197 | // Load the key_id and complete the access control tuple. |
| 2198 | let (key_id, access_key_descriptor, access_vector) = |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2199 | Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2200 | |
| 2201 | // Perform access control. It is vital that we return here if the permission is denied. |
| 2202 | // So do not touch that '?' at the end. |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2203 | check_permission(&access_key_descriptor, access_vector).context(ks_err!())?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2204 | |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2205 | // KEY ID LOCK 2/2 |
| 2206 | // If we did not get a key id lock by now, it was because we got a key descriptor |
| 2207 | // without a key id. At this point we got the key id, so we can try and get a lock. |
| 2208 | // However, we cannot block here, because we are in the middle of the transaction. |
| 2209 | // So first we try to get the lock non blocking. If that fails, we roll back the |
| 2210 | // transaction and block until we get the lock. After we successfully got the lock, |
| 2211 | // we start a new transaction and load the access tuple again. |
| 2212 | // |
| 2213 | // We don't need to perform access control again, because we already established |
| 2214 | // that the caller had access to the given key. But we need to make sure that the |
| 2215 | // key id still exists. So we have to load the key entry by key id this time. |
| 2216 | let (key_id_guard, tx) = match key_id_guard { |
| 2217 | None => match KEY_ID_LOCK.try_get(key_id) { |
| 2218 | None => { |
| 2219 | // Roll back the transaction. |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2220 | tx.rollback().context(ks_err!("Failed to roll back transaction."))?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2221 | |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2222 | // Block until we have a key id lock. |
| 2223 | let key_id_guard = KEY_ID_LOCK.get(key_id); |
| 2224 | |
| 2225 | // Create a new transaction. |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2226 | let tx = self |
| 2227 | .conn |
| 2228 | .unchecked_transaction() |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2229 | .context(ks_err!("Failed to initialize transaction."))?; |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2230 | |
| 2231 | Self::load_access_tuple( |
| 2232 | &tx, |
| 2233 | // This time we have to load the key by the retrieved key id, because the |
| 2234 | // alias may have been rebound after we rolled back the transaction. |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2235 | &KeyDescriptor { |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2236 | domain: Domain::KEY_ID, |
| 2237 | nspace: key_id, |
| 2238 | ..Default::default() |
| 2239 | }, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2240 | key_type, |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2241 | caller_uid, |
| 2242 | ) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2243 | .context(ks_err!("(deferred key lock)"))?; |
Janis Danisevskis | aec1459 | 2020-11-12 09:41:49 -0800 | [diff] [blame] | 2244 | (key_id_guard, tx) |
| 2245 | } |
| 2246 | Some(l) => (l, tx), |
| 2247 | }, |
| 2248 | Some(key_id_guard) => (key_id_guard, tx), |
| 2249 | }; |
| 2250 | |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2251 | let key_entry = |
| 2252 | Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2253 | |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2254 | tx.commit().context(ks_err!("Failed to commit transaction."))?; |
Janis Danisevskis | 3f322cb | 2020-09-03 14:46:22 -0700 | [diff] [blame] | 2255 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2256 | Ok((key_id_guard, key_entry)) |
| 2257 | } |
| 2258 | |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2259 | fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2260 | let updated = tx |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2261 | .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id]) |
| 2262 | .context("Trying to delete keyentry.")?; |
| 2263 | tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id]) |
| 2264 | .context("Trying to delete keymetadata.")?; |
| 2265 | tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id]) |
| 2266 | .context("Trying to delete keyparameters.")?; |
| 2267 | tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id]) |
| 2268 | .context("Trying to delete grants.")?; |
Janis Danisevskis | 4507f3b | 2021-01-13 16:34:39 -0800 | [diff] [blame] | 2269 | Ok(updated != 0) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2270 | } |
| 2271 | |
| 2272 | /// 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] | 2273 | /// 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] | 2274 | pub fn unbind_key( |
| 2275 | &mut self, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2276 | key: &KeyDescriptor, |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2277 | key_type: KeyType, |
| 2278 | caller_uid: u32, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2279 | check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2280 | ) -> Result<()> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 2281 | let _wp = wd::watch("KeystoreDB::unbind_key"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 2282 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 2283 | self.with_transaction(Immediate("TX_unbind_key"), |tx| { |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2284 | let (key_id, access_key_descriptor, access_vector) = |
| 2285 | Self::load_access_tuple(tx, key, key_type, caller_uid) |
| 2286 | .context("Trying to get access tuple.")?; |
| 2287 | |
| 2288 | // Perform access control. It is vital that we return here if the permission is denied. |
| 2289 | // So do not touch that '?' at the end. |
| 2290 | check_permission(&access_key_descriptor, access_vector) |
| 2291 | .context("While checking permission.")?; |
| 2292 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2293 | Self::mark_unreferenced(tx, key_id) |
| 2294 | .map(|need_gc| (need_gc, ())) |
| 2295 | .context("Trying to mark the key unreferenced.") |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2296 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2297 | .context(ks_err!()) |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2298 | } |
| 2299 | |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2300 | fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> { |
| 2301 | tx.query_row( |
| 2302 | "SELECT km_uuid FROM persistent.keyentry WHERE id = ?", |
| 2303 | params![key_id], |
| 2304 | |row| row.get(0), |
| 2305 | ) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2306 | .context(ks_err!()) |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2307 | } |
| 2308 | |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 2309 | /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple. |
| 2310 | /// This leaves all of the blob entries orphaned for subsequent garbage collection. |
| 2311 | pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 2312 | let _wp = wd::watch("KeystoreDB::unbind_keys_for_namespace"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 2313 | |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 2314 | if !(domain == Domain::APP || domain == Domain::SELINUX) { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2315 | return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!()); |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 2316 | } |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 2317 | self.with_transaction(Immediate("TX_unbind_keys_for_namespace"), |tx| { |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 2318 | tx.execute( |
| 2319 | "DELETE FROM persistent.keymetadata |
| 2320 | WHERE keyentryid IN ( |
| 2321 | SELECT id FROM persistent.keyentry |
Tri Vo | 0346bbe | 2023-05-12 14:16:31 -0400 | [diff] [blame] | 2322 | WHERE domain = ? AND namespace = ? AND key_type = ? |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 2323 | );", |
Tri Vo | 0346bbe | 2023-05-12 14:16:31 -0400 | [diff] [blame] | 2324 | params![domain.0, namespace, KeyType::Client], |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 2325 | ) |
| 2326 | .context("Trying to delete keymetadata.")?; |
| 2327 | tx.execute( |
| 2328 | "DELETE FROM persistent.keyparameter |
| 2329 | WHERE keyentryid IN ( |
| 2330 | SELECT id FROM persistent.keyentry |
Tri Vo | 0346bbe | 2023-05-12 14:16:31 -0400 | [diff] [blame] | 2331 | WHERE domain = ? AND namespace = ? AND key_type = ? |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 2332 | );", |
Tri Vo | 0346bbe | 2023-05-12 14:16:31 -0400 | [diff] [blame] | 2333 | params![domain.0, namespace, KeyType::Client], |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 2334 | ) |
| 2335 | .context("Trying to delete keyparameters.")?; |
| 2336 | tx.execute( |
| 2337 | "DELETE FROM persistent.grant |
| 2338 | WHERE keyentryid IN ( |
| 2339 | SELECT id FROM persistent.keyentry |
Tri Vo | 0346bbe | 2023-05-12 14:16:31 -0400 | [diff] [blame] | 2340 | WHERE domain = ? AND namespace = ? AND key_type = ? |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 2341 | );", |
Tri Vo | 0346bbe | 2023-05-12 14:16:31 -0400 | [diff] [blame] | 2342 | params![domain.0, namespace, KeyType::Client], |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 2343 | ) |
| 2344 | .context("Trying to delete grants.")?; |
| 2345 | tx.execute( |
Janis Danisevskis | b146f31 | 2021-05-06 15:05:45 -0700 | [diff] [blame] | 2346 | "DELETE FROM persistent.keyentry |
Tri Vo | 0346bbe | 2023-05-12 14:16:31 -0400 | [diff] [blame] | 2347 | WHERE domain = ? AND namespace = ? AND key_type = ?;", |
| 2348 | params![domain.0, namespace, KeyType::Client], |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 2349 | ) |
| 2350 | .context("Trying to delete keyentry.")?; |
| 2351 | Ok(()).need_gc() |
| 2352 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2353 | .context(ks_err!()) |
Janis Danisevskis | ddd6e75 | 2021-02-22 18:46:55 -0800 | [diff] [blame] | 2354 | } |
| 2355 | |
Janis Danisevskis | 3cba10d | 2021-05-06 17:02:19 -0700 | [diff] [blame] | 2356 | fn cleanup_unreferenced(tx: &Transaction) -> Result<()> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 2357 | let _wp = wd::watch("KeystoreDB::cleanup_unreferenced"); |
Janis Danisevskis | 3cba10d | 2021-05-06 17:02:19 -0700 | [diff] [blame] | 2358 | { |
| 2359 | tx.execute( |
| 2360 | "DELETE FROM persistent.keymetadata |
| 2361 | WHERE keyentryid IN ( |
| 2362 | SELECT id FROM persistent.keyentry |
| 2363 | WHERE state = ? |
| 2364 | );", |
| 2365 | params![KeyLifeCycle::Unreferenced], |
| 2366 | ) |
| 2367 | .context("Trying to delete keymetadata.")?; |
| 2368 | tx.execute( |
| 2369 | "DELETE FROM persistent.keyparameter |
| 2370 | WHERE keyentryid IN ( |
| 2371 | SELECT id FROM persistent.keyentry |
| 2372 | WHERE state = ? |
| 2373 | );", |
| 2374 | params![KeyLifeCycle::Unreferenced], |
| 2375 | ) |
| 2376 | .context("Trying to delete keyparameters.")?; |
| 2377 | tx.execute( |
| 2378 | "DELETE FROM persistent.grant |
| 2379 | WHERE keyentryid IN ( |
| 2380 | SELECT id FROM persistent.keyentry |
| 2381 | WHERE state = ? |
| 2382 | );", |
| 2383 | params![KeyLifeCycle::Unreferenced], |
| 2384 | ) |
| 2385 | .context("Trying to delete grants.")?; |
| 2386 | tx.execute( |
| 2387 | "DELETE FROM persistent.keyentry |
| 2388 | WHERE state = ?;", |
| 2389 | params![KeyLifeCycle::Unreferenced], |
| 2390 | ) |
| 2391 | .context("Trying to delete keyentry.")?; |
| 2392 | Result::<()>::Ok(()) |
| 2393 | } |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2394 | .context(ks_err!()) |
Janis Danisevskis | 3cba10d | 2021-05-06 17:02:19 -0700 | [diff] [blame] | 2395 | } |
| 2396 | |
Eric Biggers | 9f7ebeb | 2024-06-20 14:59:32 +0000 | [diff] [blame] | 2397 | /// Deletes all keys for the given user, including both client keys and super keys. |
| 2398 | pub fn unbind_keys_for_user(&mut self, user_id: u32) -> Result<()> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 2399 | let _wp = wd::watch("KeystoreDB::unbind_keys_for_user"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 2400 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 2401 | self.with_transaction(Immediate("TX_unbind_keys_for_user"), |tx| { |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 2402 | let mut stmt = tx |
| 2403 | .prepare(&format!( |
| 2404 | "SELECT id from persistent.keyentry |
| 2405 | WHERE ( |
| 2406 | key_type = ? |
| 2407 | AND domain = ? |
| 2408 | AND cast ( (namespace/{aid_user_offset}) as int) = ? |
| 2409 | AND state = ? |
| 2410 | ) OR ( |
| 2411 | key_type = ? |
| 2412 | AND namespace = ? |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 2413 | AND state = ? |
| 2414 | );", |
| 2415 | aid_user_offset = AID_USER_OFFSET |
| 2416 | )) |
| 2417 | .context(concat!( |
| 2418 | "In unbind_keys_for_user. ", |
| 2419 | "Failed to prepare the query to find the keys created by apps." |
| 2420 | ))?; |
| 2421 | |
| 2422 | let mut rows = stmt |
| 2423 | .query(params![ |
| 2424 | // WHERE client key: |
| 2425 | KeyType::Client, |
| 2426 | Domain::APP.0 as u32, |
| 2427 | user_id, |
| 2428 | KeyLifeCycle::Live, |
| 2429 | // OR super key: |
| 2430 | KeyType::Super, |
| 2431 | user_id, |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 2432 | KeyLifeCycle::Live |
| 2433 | ]) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2434 | .context(ks_err!("Failed to query the keys created by apps."))?; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 2435 | |
| 2436 | let mut key_ids: Vec<i64> = Vec::new(); |
| 2437 | db_utils::with_rows_extract_all(&mut rows, |row| { |
| 2438 | key_ids |
| 2439 | .push(row.get(0).context("Failed to read key id of a key created by an app.")?); |
| 2440 | Ok(()) |
| 2441 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2442 | .context(ks_err!())?; |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 2443 | |
| 2444 | let mut notify_gc = false; |
| 2445 | for key_id in key_ids { |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 2446 | notify_gc = Self::mark_unreferenced(tx, key_id) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 2447 | .context("In unbind_keys_for_user.")? |
| 2448 | || notify_gc; |
| 2449 | } |
| 2450 | Ok(()).do_gc(notify_gc) |
| 2451 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2452 | .context(ks_err!()) |
Hasini Gunasinghe | da89555 | 2021-01-27 19:34:37 +0000 | [diff] [blame] | 2453 | } |
| 2454 | |
Eric Biggers | b0478cf | 2023-10-27 03:55:29 +0000 | [diff] [blame] | 2455 | /// Deletes all auth-bound keys, i.e. keys that require user authentication, for the given user. |
| 2456 | /// This runs when the user's lock screen is being changed to Swipe or None. |
| 2457 | /// |
| 2458 | /// This intentionally does *not* delete keys that require that the device be unlocked, unless |
| 2459 | /// such keys also require user authentication. Keystore's concept of user authentication is |
| 2460 | /// fairly strong, and it requires that keys that require authentication be deleted as soon as |
| 2461 | /// authentication is no longer possible. In contrast, keys that just require that the device |
| 2462 | /// be unlocked should remain usable when the lock screen is set to Swipe or None, as the device |
| 2463 | /// is always considered "unlocked" in that case. |
| 2464 | pub fn unbind_auth_bound_keys_for_user(&mut self, user_id: u32) -> Result<()> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 2465 | let _wp = wd::watch("KeystoreDB::unbind_auth_bound_keys_for_user"); |
Eric Biggers | b0478cf | 2023-10-27 03:55:29 +0000 | [diff] [blame] | 2466 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 2467 | self.with_transaction(Immediate("TX_unbind_auth_bound_keys_for_user"), |tx| { |
Eric Biggers | b0478cf | 2023-10-27 03:55:29 +0000 | [diff] [blame] | 2468 | let mut stmt = tx |
| 2469 | .prepare(&format!( |
| 2470 | "SELECT id from persistent.keyentry |
| 2471 | WHERE key_type = ? |
| 2472 | AND domain = ? |
| 2473 | AND cast ( (namespace/{aid_user_offset}) as int) = ? |
| 2474 | AND state = ?;", |
| 2475 | aid_user_offset = AID_USER_OFFSET |
| 2476 | )) |
| 2477 | .context(concat!( |
| 2478 | "In unbind_auth_bound_keys_for_user. ", |
| 2479 | "Failed to prepare the query to find the keys created by apps." |
| 2480 | ))?; |
| 2481 | |
| 2482 | let mut rows = stmt |
| 2483 | .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,]) |
| 2484 | .context(ks_err!("Failed to query the keys created by apps."))?; |
| 2485 | |
| 2486 | let mut key_ids: Vec<i64> = Vec::new(); |
| 2487 | db_utils::with_rows_extract_all(&mut rows, |row| { |
| 2488 | key_ids |
| 2489 | .push(row.get(0).context("Failed to read key id of a key created by an app.")?); |
| 2490 | Ok(()) |
| 2491 | }) |
| 2492 | .context(ks_err!())?; |
| 2493 | |
| 2494 | let mut notify_gc = false; |
| 2495 | let mut num_unbound = 0; |
| 2496 | for key_id in key_ids { |
| 2497 | // Load the key parameters and filter out non-auth-bound keys. To identify |
| 2498 | // auth-bound keys, use the presence of UserSecureID. The absence of NoAuthRequired |
| 2499 | // could also be used, but UserSecureID is what Keystore treats as authoritative |
| 2500 | // when actually enforcing the key parameters (it might not matter, though). |
| 2501 | let params = Self::load_key_parameters(key_id, tx) |
| 2502 | .context("Failed to load key parameters.")?; |
| 2503 | let is_auth_bound_key = params.iter().any(|kp| { |
| 2504 | matches!(kp.key_parameter_value(), KeyParameterValue::UserSecureID(_)) |
| 2505 | }); |
| 2506 | if is_auth_bound_key { |
| 2507 | notify_gc = Self::mark_unreferenced(tx, key_id) |
| 2508 | .context("In unbind_auth_bound_keys_for_user.")? |
| 2509 | || notify_gc; |
| 2510 | num_unbound += 1; |
| 2511 | } |
| 2512 | } |
| 2513 | log::info!("Deleting {num_unbound} auth-bound keys for user {user_id}"); |
| 2514 | Ok(()).do_gc(notify_gc) |
| 2515 | }) |
| 2516 | .context(ks_err!()) |
| 2517 | } |
| 2518 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2519 | fn load_key_components( |
| 2520 | tx: &Transaction, |
| 2521 | load_bits: KeyEntryLoadBits, |
| 2522 | key_id: i64, |
| 2523 | ) -> Result<KeyEntry> { |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 2524 | let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2525 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2526 | let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) = |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 2527 | Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2528 | |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 2529 | let parameters = Self::load_key_parameters(key_id, tx) |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2530 | .context("In load_key_components: Trying to load key parameters.")?; |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2531 | |
Chris Wailes | d5aaaef | 2021-07-27 16:04:33 -0700 | [diff] [blame] | 2532 | let km_uuid = Self::get_key_km_uuid(tx, key_id) |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2533 | .context("In load_key_components: Trying to get KM uuid.")?; |
Janis Danisevskis | 93927dd | 2020-12-23 12:23:08 -0800 | [diff] [blame] | 2534 | |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2535 | Ok(KeyEntry { |
| 2536 | id: key_id, |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2537 | key_blob_info, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2538 | cert: cert_blob, |
| 2539 | cert_chain: cert_chain_blob, |
Max Bires | 8e93d2b | 2021-01-14 13:17:59 -0800 | [diff] [blame] | 2540 | km_uuid, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2541 | parameters, |
| 2542 | metadata, |
Janis Danisevskis | 377d100 | 2021-01-27 19:07:48 -0800 | [diff] [blame] | 2543 | pure_cert: !has_km_blob, |
Janis Danisevskis | b42fc18 | 2020-12-15 08:41:27 -0800 | [diff] [blame] | 2544 | }) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2545 | } |
| 2546 | |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 2547 | /// Returns a list of KeyDescriptors in the selected domain/namespace whose |
| 2548 | /// aliases are greater than the specified 'start_past_alias'. If no value |
| 2549 | /// is provided, returns all KeyDescriptors. |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 2550 | /// The key descriptors will have the domain, nspace, and alias field set. |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 2551 | /// The returned list will be sorted by alias. |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 2552 | /// Domain must be APP or SELINUX, the caller must make sure of that. |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 2553 | pub fn list_past_alias( |
Janis Danisevskis | 1831383 | 2021-05-17 13:30:32 -0700 | [diff] [blame] | 2554 | &mut self, |
| 2555 | domain: Domain, |
| 2556 | namespace: i64, |
| 2557 | key_type: KeyType, |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 2558 | start_past_alias: Option<&str>, |
Janis Danisevskis | 1831383 | 2021-05-17 13:30:32 -0700 | [diff] [blame] | 2559 | ) -> Result<Vec<KeyDescriptor>> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 2560 | let _wp = wd::watch("KeystoreDB::list_past_alias"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 2561 | |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 2562 | let query = format!( |
| 2563 | "SELECT DISTINCT alias FROM persistent.keyentry |
Janis Danisevskis | 1831383 | 2021-05-17 13:30:32 -0700 | [diff] [blame] | 2564 | WHERE domain = ? |
| 2565 | AND namespace = ? |
| 2566 | AND alias IS NOT NULL |
| 2567 | AND state = ? |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 2568 | AND key_type = ? |
| 2569 | {} |
| 2570 | ORDER BY alias ASC;", |
| 2571 | if start_past_alias.is_some() { " AND alias > ?" } else { "" } |
| 2572 | ); |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 2573 | |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 2574 | self.with_transaction(TransactionBehavior::Deferred, |tx| { |
| 2575 | let mut stmt = tx.prepare(&query).context(ks_err!("Failed to prepare."))?; |
| 2576 | |
| 2577 | let mut rows = match start_past_alias { |
| 2578 | Some(past_alias) => stmt |
| 2579 | .query(params![ |
| 2580 | domain.0 as u32, |
| 2581 | namespace, |
| 2582 | KeyLifeCycle::Live, |
| 2583 | key_type, |
| 2584 | past_alias |
| 2585 | ]) |
| 2586 | .context(ks_err!("Failed to query."))?, |
| 2587 | None => stmt |
| 2588 | .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type,]) |
| 2589 | .context(ks_err!("Failed to query."))?, |
| 2590 | }; |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 2591 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2592 | let mut descriptors: Vec<KeyDescriptor> = Vec::new(); |
| 2593 | db_utils::with_rows_extract_all(&mut rows, |row| { |
| 2594 | descriptors.push(KeyDescriptor { |
| 2595 | domain, |
| 2596 | nspace: namespace, |
| 2597 | alias: Some(row.get(0).context("Trying to extract alias.")?), |
| 2598 | blob: None, |
| 2599 | }); |
| 2600 | Ok(()) |
| 2601 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2602 | .context(ks_err!("Failed to extract rows."))?; |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2603 | Ok(descriptors).no_gc() |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 2604 | }) |
Janis Danisevskis | e92a5e6 | 2020-12-02 12:57:41 -0800 | [diff] [blame] | 2605 | } |
| 2606 | |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 2607 | /// Returns a number of KeyDescriptors in the selected domain/namespace. |
| 2608 | /// Domain must be APP or SELINUX, the caller must make sure of that. |
| 2609 | pub fn count_keys( |
| 2610 | &mut self, |
| 2611 | domain: Domain, |
| 2612 | namespace: i64, |
| 2613 | key_type: KeyType, |
| 2614 | ) -> Result<usize> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 2615 | let _wp = wd::watch("KeystoreDB::countKeys"); |
Eran Messeri | 24f3197 | 2023-01-25 17:00:33 +0000 | [diff] [blame] | 2616 | |
| 2617 | let num_keys = self.with_transaction(TransactionBehavior::Deferred, |tx| { |
| 2618 | tx.query_row( |
| 2619 | "SELECT COUNT(alias) FROM persistent.keyentry |
| 2620 | WHERE domain = ? |
| 2621 | AND namespace = ? |
| 2622 | AND alias IS NOT NULL |
| 2623 | AND state = ? |
| 2624 | AND key_type = ?;", |
| 2625 | params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type], |
| 2626 | |row| row.get(0), |
| 2627 | ) |
| 2628 | .context(ks_err!("Failed to count number of keys.")) |
| 2629 | .no_gc() |
| 2630 | })?; |
| 2631 | Ok(num_keys) |
| 2632 | } |
| 2633 | |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2634 | /// Adds a grant to the grant table. |
| 2635 | /// Like `load_key_entry` this function loads the access tuple before |
| 2636 | /// it uses the callback for a permission check. Upon success, |
| 2637 | /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the |
| 2638 | /// grant table. The new row will have a randomized id, which is used as |
| 2639 | /// grant id in the namespace field of the resulting KeyDescriptor. |
| 2640 | pub fn grant( |
| 2641 | &mut self, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2642 | key: &KeyDescriptor, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2643 | caller_uid: u32, |
| 2644 | grantee_uid: u32, |
| 2645 | access_vector: KeyPermSet, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2646 | check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2647 | ) -> Result<KeyDescriptor> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 2648 | let _wp = wd::watch("KeystoreDB::grant"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 2649 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 2650 | self.with_transaction(Immediate("TX_grant"), |tx| { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2651 | // Load the key_id and complete the access control tuple. |
| 2652 | // We ignore the access vector here because grants cannot be granted. |
| 2653 | // The access vector returned here expresses the permissions the |
| 2654 | // grantee has if key.domain == Domain::GRANT. But this vector |
| 2655 | // cannot include the grant permission by design, so there is no way the |
| 2656 | // subsequent permission check can pass. |
| 2657 | // We could check key.domain == Domain::GRANT and fail early. |
| 2658 | // But even if we load the access tuple by grant here, the permission |
| 2659 | // check denies the attempt to create a grant by grant descriptor. |
| 2660 | let (key_id, access_key_descriptor, _) = |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2661 | Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2662 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2663 | // Perform access control. It is vital that we return here if the permission |
| 2664 | // was denied. So do not touch that '?' at the end of the line. |
| 2665 | // This permission check checks if the caller has the grant permission |
| 2666 | // for the given key and in addition to all of the permissions |
| 2667 | // expressed in `access_vector`. |
| 2668 | check_permission(&access_key_descriptor, &access_vector) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2669 | .context(ks_err!("check_permission failed"))?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2670 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2671 | let grant_id = if let Some(grant_id) = tx |
| 2672 | .query_row( |
| 2673 | "SELECT id FROM persistent.grant |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2674 | WHERE keyentryid = ? AND grantee = ?;", |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2675 | params![key_id, grantee_uid], |
| 2676 | |row| row.get(0), |
| 2677 | ) |
| 2678 | .optional() |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2679 | .context(ks_err!("Failed get optional existing grant id."))? |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2680 | { |
| 2681 | tx.execute( |
| 2682 | "UPDATE persistent.grant |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2683 | SET access_vector = ? |
| 2684 | WHERE id = ?;", |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2685 | params![i32::from(access_vector), grant_id], |
Joel Galenson | 845f74b | 2020-09-09 14:11:55 -0700 | [diff] [blame] | 2686 | ) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2687 | .context(ks_err!("Failed to update existing grant."))?; |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2688 | grant_id |
| 2689 | } else { |
| 2690 | Self::insert_with_retry(|id| { |
| 2691 | tx.execute( |
| 2692 | "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector) |
| 2693 | VALUES (?, ?, ?, ?);", |
| 2694 | params![id, grantee_uid, key_id, i32::from(access_vector)], |
| 2695 | ) |
| 2696 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2697 | .context(ks_err!())? |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2698 | }; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2699 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2700 | Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None }) |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2701 | .no_gc() |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2702 | }) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2703 | } |
| 2704 | |
| 2705 | /// This function checks permissions like `grant` and `load_key_entry` |
| 2706 | /// before removing a grant from the grant table. |
| 2707 | pub fn ungrant( |
| 2708 | &mut self, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2709 | key: &KeyDescriptor, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2710 | caller_uid: u32, |
| 2711 | grantee_uid: u32, |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2712 | check_permission: impl Fn(&KeyDescriptor) -> Result<()>, |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2713 | ) -> Result<()> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 2714 | let _wp = wd::watch("KeystoreDB::ungrant"); |
Janis Danisevskis | 850d486 | 2021-05-05 08:41:14 -0700 | [diff] [blame] | 2715 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 2716 | self.with_transaction(Immediate("TX_ungrant"), |tx| { |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2717 | // Load the key_id and complete the access control tuple. |
| 2718 | // We ignore the access vector here because grants cannot be granted. |
| 2719 | let (key_id, access_key_descriptor, _) = |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2720 | Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2721 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2722 | // Perform access control. We must return here if the permission |
| 2723 | // was denied. So do not touch the '?' at the end of this line. |
| 2724 | check_permission(&access_key_descriptor) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2725 | .context(ks_err!("check_permission failed."))?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2726 | |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2727 | tx.execute( |
| 2728 | "DELETE FROM persistent.grant |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2729 | WHERE keyentryid = ? AND grantee = ?;", |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2730 | params![key_id, grantee_uid], |
| 2731 | ) |
| 2732 | .context("Failed to delete grant.")?; |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2733 | |
Janis Danisevskis | 7e8b462 | 2021-02-13 10:01:59 -0800 | [diff] [blame] | 2734 | Ok(()).no_gc() |
Janis Danisevskis | 66784c4 | 2021-01-27 08:40:25 -0800 | [diff] [blame] | 2735 | }) |
Janis Danisevskis | 63f7bc8 | 2020-09-03 10:12:56 -0700 | [diff] [blame] | 2736 | } |
| 2737 | |
Joel Galenson | 845f74b | 2020-09-09 14:11:55 -0700 | [diff] [blame] | 2738 | // Generates a random id and passes it to the given function, which will |
| 2739 | // try to insert it into a database. If that insertion fails, retry; |
| 2740 | // otherwise return the id. |
| 2741 | fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> { |
| 2742 | loop { |
Janis Danisevskis | eed6984 | 2021-02-18 20:04:10 -0800 | [diff] [blame] | 2743 | let newid: i64 = match random() { |
| 2744 | Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned. |
| 2745 | i => i, |
| 2746 | }; |
Joel Galenson | 845f74b | 2020-09-09 14:11:55 -0700 | [diff] [blame] | 2747 | match inserter(newid) { |
| 2748 | // If the id already existed, try again. |
| 2749 | Err(rusqlite::Error::SqliteFailure( |
| 2750 | libsqlite3_sys::Error { |
| 2751 | code: libsqlite3_sys::ErrorCode::ConstraintViolation, |
| 2752 | extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE, |
| 2753 | }, |
| 2754 | _, |
| 2755 | )) => (), |
| 2756 | Err(e) => { |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2757 | return Err(e).context(ks_err!("failed to insert into database.")); |
Joel Galenson | 845f74b | 2020-09-09 14:11:55 -0700 | [diff] [blame] | 2758 | } |
| 2759 | _ => return Ok(newid), |
| 2760 | } |
| 2761 | } |
| 2762 | } |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 2763 | |
Matthew Maurer | d7815ca | 2021-05-06 21:58:45 -0700 | [diff] [blame] | 2764 | /// Insert or replace the auth token based on (user_id, auth_id, auth_type) |
| 2765 | pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) { |
Eric Biggers | 19b3b0d | 2024-01-31 22:46:47 +0000 | [diff] [blame] | 2766 | self.perboot |
| 2767 | .insert_auth_token_entry(AuthTokenEntry::new(auth_token.clone(), BootTime::now())) |
Hasini Gunasinghe | 557b103 | 2020-11-10 01:35:30 +0000 | [diff] [blame] | 2768 | } |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 2769 | |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 2770 | /// Find the newest auth token matching the given predicate. |
Eric Biggers | b5613da | 2024-03-13 19:31:42 +0000 | [diff] [blame] | 2771 | pub fn find_auth_token_entry<F>(&self, p: F) -> Option<AuthTokenEntry> |
Janis Danisevskis | 5ed8c53 | 2021-01-11 14:19:42 -0800 | [diff] [blame] | 2772 | where |
| 2773 | F: Fn(&AuthTokenEntry) -> bool, |
| 2774 | { |
Eric Biggers | b5613da | 2024-03-13 19:31:42 +0000 | [diff] [blame] | 2775 | self.perboot.find_auth_token_entry(p) |
Hasini Gunasinghe | f70cf8e | 2020-11-11 01:02:41 +0000 | [diff] [blame] | 2776 | } |
Pavel Grafov | f45034a | 2021-05-12 22:35:45 +0100 | [diff] [blame] | 2777 | |
| 2778 | /// Load descriptor of a key by key id |
| 2779 | pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 2780 | let _wp = wd::watch("KeystoreDB::load_key_descriptor"); |
Pavel Grafov | f45034a | 2021-05-12 22:35:45 +0100 | [diff] [blame] | 2781 | |
| 2782 | self.with_transaction(TransactionBehavior::Deferred, |tx| { |
| 2783 | tx.query_row( |
| 2784 | "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;", |
| 2785 | params![key_id], |
| 2786 | |row| { |
| 2787 | Ok(KeyDescriptor { |
| 2788 | domain: Domain(row.get(0)?), |
| 2789 | nspace: row.get(1)?, |
| 2790 | alias: row.get(2)?, |
| 2791 | blob: None, |
| 2792 | }) |
| 2793 | }, |
| 2794 | ) |
| 2795 | .optional() |
| 2796 | .context("Trying to load key descriptor") |
| 2797 | .no_gc() |
| 2798 | }) |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 2799 | .context(ks_err!()) |
Pavel Grafov | f45034a | 2021-05-12 22:35:45 +0100 | [diff] [blame] | 2800 | } |
Eran Messeri | 4dc27b5 | 2024-01-09 12:43:31 +0000 | [diff] [blame] | 2801 | |
| 2802 | /// Returns a list of app UIDs that have keys authenticated by the given secure_user_id |
| 2803 | /// (for the given user_id). |
| 2804 | /// This is helpful for finding out which apps will have their keys invalidated when |
| 2805 | /// the user changes biometrics enrollment or removes their LSKF. |
| 2806 | pub fn get_app_uids_affected_by_sid( |
| 2807 | &mut self, |
| 2808 | user_id: i32, |
| 2809 | secure_user_id: i64, |
| 2810 | ) -> Result<Vec<i64>> { |
David Drysdale | 541846b | 2024-05-23 13:16:07 +0100 | [diff] [blame] | 2811 | let _wp = wd::watch("KeystoreDB::get_app_uids_affected_by_sid"); |
Eran Messeri | 4dc27b5 | 2024-01-09 12:43:31 +0000 | [diff] [blame] | 2812 | |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 2813 | let ids = self.with_transaction(Immediate("TX_get_app_uids_affected_by_sid"), |tx| { |
Eran Messeri | 4dc27b5 | 2024-01-09 12:43:31 +0000 | [diff] [blame] | 2814 | let mut stmt = tx |
| 2815 | .prepare(&format!( |
| 2816 | "SELECT id, namespace from persistent.keyentry |
| 2817 | WHERE key_type = ? |
| 2818 | AND domain = ? |
| 2819 | AND cast ( (namespace/{AID_USER_OFFSET}) as int) = ? |
| 2820 | AND state = ?;", |
| 2821 | )) |
| 2822 | .context(concat!( |
| 2823 | "In get_app_uids_affected_by_sid, ", |
| 2824 | "failed to prepare the query to find the keys created by apps." |
| 2825 | ))?; |
| 2826 | |
| 2827 | let mut rows = stmt |
| 2828 | .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,]) |
| 2829 | .context(ks_err!("Failed to query the keys created by apps."))?; |
| 2830 | |
| 2831 | let mut key_ids_and_app_uids: HashMap<i64, i64> = Default::default(); |
| 2832 | db_utils::with_rows_extract_all(&mut rows, |row| { |
| 2833 | key_ids_and_app_uids.insert( |
| 2834 | row.get(0).context("Failed to read key id of a key created by an app.")?, |
| 2835 | row.get(1).context("Failed to read the app uid")?, |
| 2836 | ); |
| 2837 | Ok(()) |
| 2838 | })?; |
| 2839 | Ok(key_ids_and_app_uids).no_gc() |
| 2840 | })?; |
| 2841 | let mut app_uids_affected_by_sid: HashSet<i64> = Default::default(); |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 2842 | for (key_id, app_uid) in ids { |
Eran Messeri | 4dc27b5 | 2024-01-09 12:43:31 +0000 | [diff] [blame] | 2843 | // Read the key parameters for each key in its own transaction. It is OK to ignore |
| 2844 | // an error to get the properties of a particular key since it might have been deleted |
| 2845 | // under our feet after the previous transaction concluded. If the key was deleted |
| 2846 | // then it is no longer applicable if it was auth-bound or not. |
| 2847 | if let Ok(is_key_bound_to_sid) = |
David Drysdale | 7b9ca23 | 2024-05-23 18:19:46 +0100 | [diff] [blame] | 2848 | self.with_transaction(Immediate("TX_get_app_uids_affects_by_sid 2"), |tx| { |
Eran Messeri | 4dc27b5 | 2024-01-09 12:43:31 +0000 | [diff] [blame] | 2849 | let params = Self::load_key_parameters(key_id, tx) |
| 2850 | .context("Failed to load key parameters.")?; |
| 2851 | // Check if the key is bound to this secure user ID. |
| 2852 | let is_key_bound_to_sid = params.iter().any(|kp| { |
| 2853 | matches!( |
| 2854 | kp.key_parameter_value(), |
| 2855 | KeyParameterValue::UserSecureID(sid) if *sid == secure_user_id |
| 2856 | ) |
| 2857 | }); |
| 2858 | Ok(is_key_bound_to_sid).no_gc() |
| 2859 | }) |
| 2860 | { |
| 2861 | if is_key_bound_to_sid { |
| 2862 | app_uids_affected_by_sid.insert(app_uid); |
| 2863 | } |
| 2864 | } |
| 2865 | } |
| 2866 | |
| 2867 | let app_uids_vec: Vec<i64> = app_uids_affected_by_sid.into_iter().collect(); |
| 2868 | Ok(app_uids_vec) |
| 2869 | } |
Joel Galenson | 26f4d01 | 2020-07-17 14:57:21 -0700 | [diff] [blame] | 2870 | } |