Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 1 | // Copyright 2021, 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 | |
| 15 | //! This is the metrics store module of keystore. It does the following tasks: |
| 16 | //! 1. Processes the data about keystore events asynchronously, and |
| 17 | //! stores them in an in-memory store. |
| 18 | //! 2. Returns the collected metrics when requested by the statsd proxy. |
| 19 | |
Tri Vo | a1634bb | 2022-12-01 15:54:19 -0800 | [diff] [blame] | 20 | use crate::error::get_error_code; |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 21 | use crate::globals::DB; |
| 22 | use crate::key_parameter::KeyParameterValue as KsKeyParamValue; |
Shaquille Johnson | 9da2e1c | 2022-09-19 12:39:01 +0000 | [diff] [blame] | 23 | use crate::ks_err; |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 24 | use crate::operation::Outcome; |
| 25 | use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{ |
| 26 | Algorithm::Algorithm, BlockMode::BlockMode, Digest::Digest, EcCurve::EcCurve, |
| 27 | HardwareAuthenticatorType::HardwareAuthenticatorType, KeyOrigin::KeyOrigin, |
| 28 | KeyParameter::KeyParameter, KeyPurpose::KeyPurpose, PaddingMode::PaddingMode, |
| 29 | SecurityLevel::SecurityLevel, |
| 30 | }; |
| 31 | use android_security_metrics::aidl::android::security::metrics::{ |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 32 | Algorithm::Algorithm as MetricsAlgorithm, AtomID::AtomID, CrashStats::CrashStats, |
| 33 | EcCurve::EcCurve as MetricsEcCurve, |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 34 | HardwareAuthenticatorType::HardwareAuthenticatorType as MetricsHardwareAuthenticatorType, |
| 35 | KeyCreationWithAuthInfo::KeyCreationWithAuthInfo, |
| 36 | KeyCreationWithGeneralInfo::KeyCreationWithGeneralInfo, |
| 37 | KeyCreationWithPurposeAndModesInfo::KeyCreationWithPurposeAndModesInfo, |
| 38 | KeyOperationWithGeneralInfo::KeyOperationWithGeneralInfo, |
| 39 | KeyOperationWithPurposeAndModesInfo::KeyOperationWithPurposeAndModesInfo, |
| 40 | KeyOrigin::KeyOrigin as MetricsKeyOrigin, Keystore2AtomWithOverflow::Keystore2AtomWithOverflow, |
| 41 | KeystoreAtom::KeystoreAtom, KeystoreAtomPayload::KeystoreAtomPayload, |
| 42 | Outcome::Outcome as MetricsOutcome, Purpose::Purpose as MetricsPurpose, |
Hasini Gunasinghe | 8af67ea | 2021-06-30 17:09:01 +0000 | [diff] [blame] | 43 | RkpError::RkpError as MetricsRkpError, RkpErrorStats::RkpErrorStats, |
Tri Vo | a1634bb | 2022-12-01 15:54:19 -0800 | [diff] [blame] | 44 | SecurityLevel::SecurityLevel as MetricsSecurityLevel, Storage::Storage as MetricsStorage, |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 45 | }; |
Eric Biggers | 9f9ab18 | 2023-05-31 21:37:32 +0000 | [diff] [blame^] | 46 | use anyhow::{anyhow, Context, Result}; |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 47 | use lazy_static::lazy_static; |
| 48 | use std::collections::HashMap; |
| 49 | use std::sync::Mutex; |
| 50 | |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 51 | // Note: Crash events are recorded at keystore restarts, based on the assumption that keystore only |
| 52 | // gets restarted after a crash, during a boot cycle. |
| 53 | const KEYSTORE_CRASH_COUNT_PROPERTY: &str = "keystore.crash_count"; |
| 54 | |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 55 | lazy_static! { |
| 56 | /// Singleton for MetricsStore. |
| 57 | pub static ref METRICS_STORE: MetricsStore = Default::default(); |
| 58 | } |
| 59 | |
| 60 | /// MetricsStore stores the <atom object, count> as <key, value> in the inner hash map, |
| 61 | /// indexed by the atom id, in the outer hash map. |
| 62 | /// There can be different atom objects with the same atom id based on the values assigned to the |
| 63 | /// fields of the atom objects. When an atom object with a particular combination of field values is |
| 64 | /// inserted, we first check if that atom object is in the inner hash map. If one exists, count |
| 65 | /// is inceremented. Otherwise, the atom object is inserted with count = 1. Note that count field |
| 66 | /// of the atom object itself is set to 0 while the object is stored in the hash map. When the atom |
| 67 | /// objects are queried by the atom id, the corresponding atom objects are retrieved, cloned, and |
| 68 | /// the count field of the cloned objects is set to the corresponding value field in the inner hash |
| 69 | /// map before the query result is returned. |
| 70 | #[derive(Default)] |
| 71 | pub struct MetricsStore { |
| 72 | metrics_store: Mutex<HashMap<AtomID, HashMap<KeystoreAtomPayload, i32>>>, |
| 73 | } |
| 74 | |
| 75 | impl MetricsStore { |
| 76 | /// There are some atoms whose maximum cardinality exceeds the cardinality limits tolerated |
| 77 | /// by statsd. Statsd tolerates cardinality between 200-300. Therefore, the in-memory storage |
| 78 | /// limit for a single atom is set to 250. If the number of atom objects created for a |
| 79 | /// particular atom exceeds this limit, an overflow atom object is created to track the ID of |
| 80 | /// such atoms. |
| 81 | const SINGLE_ATOM_STORE_MAX_SIZE: usize = 250; |
| 82 | |
| 83 | /// Return a vector of atom objects with the given atom ID, if one exists in the metrics_store. |
| 84 | /// If any atom object does not exist in the metrics_store for the given atom ID, return an |
| 85 | /// empty vector. |
| 86 | pub fn get_atoms(&self, atom_id: AtomID) -> Result<Vec<KeystoreAtom>> { |
| 87 | // StorageStats is an original pulled atom (i.e. not a pushed atom converted to a |
| 88 | // pulledd atom). Therefore, it is handled separately. |
| 89 | if AtomID::STORAGE_STATS == atom_id { |
| 90 | return pull_storage_stats(); |
| 91 | } |
| 92 | |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 93 | // Process keystore crash stats. |
| 94 | if AtomID::CRASH_STATS == atom_id { |
Eric Biggers | 9f9ab18 | 2023-05-31 21:37:32 +0000 | [diff] [blame^] | 95 | return match read_keystore_crash_count()? { |
| 96 | Some(count) => Ok(vec![KeystoreAtom { |
| 97 | payload: KeystoreAtomPayload::CrashStats(CrashStats { |
| 98 | count_of_crash_events: count, |
| 99 | }), |
| 100 | ..Default::default() |
| 101 | }]), |
| 102 | None => Err(anyhow!("Crash count property is not set")), |
| 103 | }; |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 104 | } |
| 105 | |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 106 | // It is safe to call unwrap here since the lock can not be poisoned based on its usage |
| 107 | // in this module and the lock is not acquired in the same thread before. |
| 108 | let metrics_store_guard = self.metrics_store.lock().unwrap(); |
| 109 | metrics_store_guard.get(&atom_id).map_or(Ok(Vec::<KeystoreAtom>::new()), |atom_count_map| { |
| 110 | Ok(atom_count_map |
| 111 | .iter() |
| 112 | .map(|(atom, count)| KeystoreAtom { payload: atom.clone(), count: *count }) |
| 113 | .collect()) |
| 114 | }) |
| 115 | } |
| 116 | |
| 117 | /// Insert an atom object to the metrics_store indexed by the atom ID. |
| 118 | fn insert_atom(&self, atom_id: AtomID, atom: KeystoreAtomPayload) { |
| 119 | // It is ok to unwrap here since the mutex cannot be poisoned according to the way it is |
| 120 | // used in this module. And the lock is not acquired by this thread before. |
| 121 | let mut metrics_store_guard = self.metrics_store.lock().unwrap(); |
| 122 | let atom_count_map = metrics_store_guard.entry(atom_id).or_insert_with(HashMap::new); |
| 123 | if atom_count_map.len() < MetricsStore::SINGLE_ATOM_STORE_MAX_SIZE { |
| 124 | let atom_count = atom_count_map.entry(atom).or_insert(0); |
| 125 | *atom_count += 1; |
| 126 | } else { |
| 127 | // Insert an overflow atom |
| 128 | let overflow_atom_count_map = metrics_store_guard |
| 129 | .entry(AtomID::KEYSTORE2_ATOM_WITH_OVERFLOW) |
| 130 | .or_insert_with(HashMap::new); |
| 131 | |
| 132 | if overflow_atom_count_map.len() < MetricsStore::SINGLE_ATOM_STORE_MAX_SIZE { |
| 133 | let overflow_atom = Keystore2AtomWithOverflow { atom_id }; |
| 134 | let atom_count = overflow_atom_count_map |
| 135 | .entry(KeystoreAtomPayload::Keystore2AtomWithOverflow(overflow_atom)) |
| 136 | .or_insert(0); |
| 137 | *atom_count += 1; |
| 138 | } else { |
| 139 | // This is a rare case, if at all. |
| 140 | log::error!("In insert_atom: Maximum storage limit reached for overflow atom.") |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | /// Log key creation events to be sent to statsd. |
| 147 | pub fn log_key_creation_event_stats<U>( |
| 148 | sec_level: SecurityLevel, |
| 149 | key_params: &[KeyParameter], |
| 150 | result: &Result<U>, |
| 151 | ) { |
| 152 | let ( |
| 153 | key_creation_with_general_info, |
| 154 | key_creation_with_auth_info, |
| 155 | key_creation_with_purpose_and_modes_info, |
| 156 | ) = process_key_creation_event_stats(sec_level, key_params, result); |
| 157 | |
| 158 | METRICS_STORE |
| 159 | .insert_atom(AtomID::KEY_CREATION_WITH_GENERAL_INFO, key_creation_with_general_info); |
| 160 | METRICS_STORE.insert_atom(AtomID::KEY_CREATION_WITH_AUTH_INFO, key_creation_with_auth_info); |
| 161 | METRICS_STORE.insert_atom( |
| 162 | AtomID::KEY_CREATION_WITH_PURPOSE_AND_MODES_INFO, |
| 163 | key_creation_with_purpose_and_modes_info, |
| 164 | ); |
| 165 | } |
| 166 | |
| 167 | // Process the statistics related to key creations and return the three atom objects related to key |
| 168 | // creations: i) KeyCreationWithGeneralInfo ii) KeyCreationWithAuthInfo |
| 169 | // iii) KeyCreationWithPurposeAndModesInfo |
| 170 | fn process_key_creation_event_stats<U>( |
| 171 | sec_level: SecurityLevel, |
| 172 | key_params: &[KeyParameter], |
| 173 | result: &Result<U>, |
| 174 | ) -> (KeystoreAtomPayload, KeystoreAtomPayload, KeystoreAtomPayload) { |
| 175 | // In the default atom objects, fields represented by bitmaps and i32 fields |
| 176 | // will take 0, except error_code which defaults to 1 indicating NO_ERROR and key_size, |
| 177 | // and auth_time_out which defaults to -1. |
| 178 | // The boolean fields are set to false by default. |
| 179 | // Some keymint enums do have 0 as an enum variant value. In such cases, the corresponding |
| 180 | // enum variant value in atoms.proto is incremented by 1, in order to have 0 as the reserved |
| 181 | // value for unspecified fields. |
| 182 | let mut key_creation_with_general_info = KeyCreationWithGeneralInfo { |
| 183 | algorithm: MetricsAlgorithm::ALGORITHM_UNSPECIFIED, |
| 184 | key_size: -1, |
| 185 | ec_curve: MetricsEcCurve::EC_CURVE_UNSPECIFIED, |
| 186 | key_origin: MetricsKeyOrigin::ORIGIN_UNSPECIFIED, |
| 187 | error_code: 1, |
| 188 | // Default for bool is false (for attestation_requested field). |
| 189 | ..Default::default() |
| 190 | }; |
| 191 | |
| 192 | let mut key_creation_with_auth_info = KeyCreationWithAuthInfo { |
| 193 | user_auth_type: MetricsHardwareAuthenticatorType::AUTH_TYPE_UNSPECIFIED, |
| 194 | log10_auth_key_timeout_seconds: -1, |
| 195 | security_level: MetricsSecurityLevel::SECURITY_LEVEL_UNSPECIFIED, |
| 196 | }; |
| 197 | |
| 198 | let mut key_creation_with_purpose_and_modes_info = KeyCreationWithPurposeAndModesInfo { |
| 199 | algorithm: MetricsAlgorithm::ALGORITHM_UNSPECIFIED, |
| 200 | // Default for i32 is 0 (for the remaining bitmap fields). |
| 201 | ..Default::default() |
| 202 | }; |
| 203 | |
| 204 | if let Err(ref e) = result { |
| 205 | key_creation_with_general_info.error_code = get_error_code(e); |
| 206 | } |
| 207 | |
| 208 | key_creation_with_auth_info.security_level = process_security_level(sec_level); |
| 209 | |
| 210 | for key_param in key_params.iter().map(KsKeyParamValue::from) { |
| 211 | match key_param { |
| 212 | KsKeyParamValue::Algorithm(a) => { |
| 213 | let algorithm = match a { |
| 214 | Algorithm::RSA => MetricsAlgorithm::RSA, |
| 215 | Algorithm::EC => MetricsAlgorithm::EC, |
| 216 | Algorithm::AES => MetricsAlgorithm::AES, |
| 217 | Algorithm::TRIPLE_DES => MetricsAlgorithm::TRIPLE_DES, |
| 218 | Algorithm::HMAC => MetricsAlgorithm::HMAC, |
| 219 | _ => MetricsAlgorithm::ALGORITHM_UNSPECIFIED, |
| 220 | }; |
| 221 | key_creation_with_general_info.algorithm = algorithm; |
| 222 | key_creation_with_purpose_and_modes_info.algorithm = algorithm; |
| 223 | } |
| 224 | KsKeyParamValue::KeySize(s) => { |
| 225 | key_creation_with_general_info.key_size = s; |
| 226 | } |
| 227 | KsKeyParamValue::KeyOrigin(o) => { |
| 228 | key_creation_with_general_info.key_origin = match o { |
| 229 | KeyOrigin::GENERATED => MetricsKeyOrigin::GENERATED, |
| 230 | KeyOrigin::DERIVED => MetricsKeyOrigin::DERIVED, |
| 231 | KeyOrigin::IMPORTED => MetricsKeyOrigin::IMPORTED, |
| 232 | KeyOrigin::RESERVED => MetricsKeyOrigin::RESERVED, |
| 233 | KeyOrigin::SECURELY_IMPORTED => MetricsKeyOrigin::SECURELY_IMPORTED, |
| 234 | _ => MetricsKeyOrigin::ORIGIN_UNSPECIFIED, |
| 235 | } |
| 236 | } |
| 237 | KsKeyParamValue::HardwareAuthenticatorType(a) => { |
| 238 | key_creation_with_auth_info.user_auth_type = match a { |
| 239 | HardwareAuthenticatorType::NONE => MetricsHardwareAuthenticatorType::NONE, |
| 240 | HardwareAuthenticatorType::PASSWORD => { |
| 241 | MetricsHardwareAuthenticatorType::PASSWORD |
| 242 | } |
| 243 | HardwareAuthenticatorType::FINGERPRINT => { |
| 244 | MetricsHardwareAuthenticatorType::FINGERPRINT |
| 245 | } |
| 246 | HardwareAuthenticatorType::ANY => MetricsHardwareAuthenticatorType::ANY, |
| 247 | _ => MetricsHardwareAuthenticatorType::AUTH_TYPE_UNSPECIFIED, |
| 248 | } |
| 249 | } |
| 250 | KsKeyParamValue::AuthTimeout(t) => { |
| 251 | key_creation_with_auth_info.log10_auth_key_timeout_seconds = |
| 252 | f32::log10(t as f32) as i32; |
| 253 | } |
| 254 | KsKeyParamValue::PaddingMode(p) => { |
| 255 | compute_padding_mode_bitmap( |
| 256 | &mut key_creation_with_purpose_and_modes_info.padding_mode_bitmap, |
| 257 | p, |
| 258 | ); |
| 259 | } |
| 260 | KsKeyParamValue::Digest(d) => { |
| 261 | // key_creation_with_purpose_and_modes_info.digest_bitmap = |
| 262 | compute_digest_bitmap( |
| 263 | &mut key_creation_with_purpose_and_modes_info.digest_bitmap, |
| 264 | d, |
| 265 | ); |
| 266 | } |
| 267 | KsKeyParamValue::BlockMode(b) => { |
| 268 | compute_block_mode_bitmap( |
| 269 | &mut key_creation_with_purpose_and_modes_info.block_mode_bitmap, |
| 270 | b, |
| 271 | ); |
| 272 | } |
| 273 | KsKeyParamValue::KeyPurpose(k) => { |
| 274 | compute_purpose_bitmap( |
| 275 | &mut key_creation_with_purpose_and_modes_info.purpose_bitmap, |
| 276 | k, |
| 277 | ); |
| 278 | } |
| 279 | KsKeyParamValue::EcCurve(e) => { |
| 280 | key_creation_with_general_info.ec_curve = match e { |
| 281 | EcCurve::P_224 => MetricsEcCurve::P_224, |
| 282 | EcCurve::P_256 => MetricsEcCurve::P_256, |
| 283 | EcCurve::P_384 => MetricsEcCurve::P_384, |
| 284 | EcCurve::P_521 => MetricsEcCurve::P_521, |
Seth Moore | 49d700d | 2021-12-13 20:03:33 +0000 | [diff] [blame] | 285 | EcCurve::CURVE_25519 => MetricsEcCurve::CURVE_25519, |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 286 | _ => MetricsEcCurve::EC_CURVE_UNSPECIFIED, |
| 287 | } |
| 288 | } |
| 289 | KsKeyParamValue::AttestationChallenge(_) => { |
| 290 | key_creation_with_general_info.attestation_requested = true; |
| 291 | } |
| 292 | _ => {} |
| 293 | } |
| 294 | } |
| 295 | if key_creation_with_general_info.algorithm == MetricsAlgorithm::EC { |
| 296 | // Do not record key sizes if Algorithm = EC, in order to reduce cardinality. |
| 297 | key_creation_with_general_info.key_size = -1; |
| 298 | } |
| 299 | |
| 300 | ( |
| 301 | KeystoreAtomPayload::KeyCreationWithGeneralInfo(key_creation_with_general_info), |
| 302 | KeystoreAtomPayload::KeyCreationWithAuthInfo(key_creation_with_auth_info), |
| 303 | KeystoreAtomPayload::KeyCreationWithPurposeAndModesInfo( |
| 304 | key_creation_with_purpose_and_modes_info, |
| 305 | ), |
| 306 | ) |
| 307 | } |
| 308 | |
| 309 | /// Log key operation events to be sent to statsd. |
| 310 | pub fn log_key_operation_event_stats( |
| 311 | sec_level: SecurityLevel, |
| 312 | key_purpose: KeyPurpose, |
| 313 | op_params: &[KeyParameter], |
| 314 | op_outcome: &Outcome, |
| 315 | key_upgraded: bool, |
| 316 | ) { |
| 317 | let (key_operation_with_general_info, key_operation_with_purpose_and_modes_info) = |
| 318 | process_key_operation_event_stats( |
| 319 | sec_level, |
| 320 | key_purpose, |
| 321 | op_params, |
| 322 | op_outcome, |
| 323 | key_upgraded, |
| 324 | ); |
| 325 | METRICS_STORE |
| 326 | .insert_atom(AtomID::KEY_OPERATION_WITH_GENERAL_INFO, key_operation_with_general_info); |
| 327 | METRICS_STORE.insert_atom( |
| 328 | AtomID::KEY_OPERATION_WITH_PURPOSE_AND_MODES_INFO, |
| 329 | key_operation_with_purpose_and_modes_info, |
| 330 | ); |
| 331 | } |
| 332 | |
| 333 | // Process the statistics related to key operations and return the two atom objects related to key |
| 334 | // operations: i) KeyOperationWithGeneralInfo ii) KeyOperationWithPurposeAndModesInfo |
| 335 | fn process_key_operation_event_stats( |
| 336 | sec_level: SecurityLevel, |
| 337 | key_purpose: KeyPurpose, |
| 338 | op_params: &[KeyParameter], |
| 339 | op_outcome: &Outcome, |
| 340 | key_upgraded: bool, |
| 341 | ) -> (KeystoreAtomPayload, KeystoreAtomPayload) { |
| 342 | let mut key_operation_with_general_info = KeyOperationWithGeneralInfo { |
| 343 | outcome: MetricsOutcome::OUTCOME_UNSPECIFIED, |
| 344 | error_code: 1, |
| 345 | security_level: MetricsSecurityLevel::SECURITY_LEVEL_UNSPECIFIED, |
| 346 | // Default for bool is false (for key_upgraded field). |
| 347 | ..Default::default() |
| 348 | }; |
| 349 | |
| 350 | let mut key_operation_with_purpose_and_modes_info = KeyOperationWithPurposeAndModesInfo { |
| 351 | purpose: MetricsPurpose::KEY_PURPOSE_UNSPECIFIED, |
| 352 | // Default for i32 is 0 (for the remaining bitmap fields). |
| 353 | ..Default::default() |
| 354 | }; |
| 355 | |
| 356 | key_operation_with_general_info.security_level = process_security_level(sec_level); |
| 357 | |
| 358 | key_operation_with_general_info.key_upgraded = key_upgraded; |
| 359 | |
| 360 | key_operation_with_purpose_and_modes_info.purpose = match key_purpose { |
| 361 | KeyPurpose::ENCRYPT => MetricsPurpose::ENCRYPT, |
| 362 | KeyPurpose::DECRYPT => MetricsPurpose::DECRYPT, |
| 363 | KeyPurpose::SIGN => MetricsPurpose::SIGN, |
| 364 | KeyPurpose::VERIFY => MetricsPurpose::VERIFY, |
| 365 | KeyPurpose::WRAP_KEY => MetricsPurpose::WRAP_KEY, |
| 366 | KeyPurpose::AGREE_KEY => MetricsPurpose::AGREE_KEY, |
| 367 | KeyPurpose::ATTEST_KEY => MetricsPurpose::ATTEST_KEY, |
| 368 | _ => MetricsPurpose::KEY_PURPOSE_UNSPECIFIED, |
| 369 | }; |
| 370 | |
| 371 | key_operation_with_general_info.outcome = match op_outcome { |
| 372 | Outcome::Unknown | Outcome::Dropped => MetricsOutcome::DROPPED, |
| 373 | Outcome::Success => MetricsOutcome::SUCCESS, |
| 374 | Outcome::Abort => MetricsOutcome::ABORT, |
| 375 | Outcome::Pruned => MetricsOutcome::PRUNED, |
| 376 | Outcome::ErrorCode(e) => { |
| 377 | key_operation_with_general_info.error_code = e.0; |
| 378 | MetricsOutcome::ERROR |
| 379 | } |
| 380 | }; |
| 381 | |
| 382 | for key_param in op_params.iter().map(KsKeyParamValue::from) { |
| 383 | match key_param { |
| 384 | KsKeyParamValue::PaddingMode(p) => { |
| 385 | compute_padding_mode_bitmap( |
| 386 | &mut key_operation_with_purpose_and_modes_info.padding_mode_bitmap, |
| 387 | p, |
| 388 | ); |
| 389 | } |
| 390 | KsKeyParamValue::Digest(d) => { |
| 391 | compute_digest_bitmap( |
| 392 | &mut key_operation_with_purpose_and_modes_info.digest_bitmap, |
| 393 | d, |
| 394 | ); |
| 395 | } |
| 396 | KsKeyParamValue::BlockMode(b) => { |
| 397 | compute_block_mode_bitmap( |
| 398 | &mut key_operation_with_purpose_and_modes_info.block_mode_bitmap, |
| 399 | b, |
| 400 | ); |
| 401 | } |
| 402 | _ => {} |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | ( |
| 407 | KeystoreAtomPayload::KeyOperationWithGeneralInfo(key_operation_with_general_info), |
| 408 | KeystoreAtomPayload::KeyOperationWithPurposeAndModesInfo( |
| 409 | key_operation_with_purpose_and_modes_info, |
| 410 | ), |
| 411 | ) |
| 412 | } |
| 413 | |
| 414 | fn process_security_level(sec_level: SecurityLevel) -> MetricsSecurityLevel { |
| 415 | match sec_level { |
| 416 | SecurityLevel::SOFTWARE => MetricsSecurityLevel::SECURITY_LEVEL_SOFTWARE, |
| 417 | SecurityLevel::TRUSTED_ENVIRONMENT => { |
| 418 | MetricsSecurityLevel::SECURITY_LEVEL_TRUSTED_ENVIRONMENT |
| 419 | } |
| 420 | SecurityLevel::STRONGBOX => MetricsSecurityLevel::SECURITY_LEVEL_STRONGBOX, |
| 421 | SecurityLevel::KEYSTORE => MetricsSecurityLevel::SECURITY_LEVEL_KEYSTORE, |
| 422 | _ => MetricsSecurityLevel::SECURITY_LEVEL_UNSPECIFIED, |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | fn compute_padding_mode_bitmap(padding_mode_bitmap: &mut i32, padding_mode: PaddingMode) { |
| 427 | match padding_mode { |
| 428 | PaddingMode::NONE => { |
| 429 | *padding_mode_bitmap |= 1 << PaddingModeBitPosition::NONE_BIT_POSITION as i32; |
| 430 | } |
| 431 | PaddingMode::RSA_OAEP => { |
| 432 | *padding_mode_bitmap |= 1 << PaddingModeBitPosition::RSA_OAEP_BIT_POS as i32; |
| 433 | } |
| 434 | PaddingMode::RSA_PSS => { |
| 435 | *padding_mode_bitmap |= 1 << PaddingModeBitPosition::RSA_PSS_BIT_POS as i32; |
| 436 | } |
| 437 | PaddingMode::RSA_PKCS1_1_5_ENCRYPT => { |
| 438 | *padding_mode_bitmap |= |
| 439 | 1 << PaddingModeBitPosition::RSA_PKCS1_1_5_ENCRYPT_BIT_POS as i32; |
| 440 | } |
| 441 | PaddingMode::RSA_PKCS1_1_5_SIGN => { |
| 442 | *padding_mode_bitmap |= 1 << PaddingModeBitPosition::RSA_PKCS1_1_5_SIGN_BIT_POS as i32; |
| 443 | } |
| 444 | PaddingMode::PKCS7 => { |
| 445 | *padding_mode_bitmap |= 1 << PaddingModeBitPosition::PKCS7_BIT_POS as i32; |
| 446 | } |
| 447 | _ => {} |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | fn compute_digest_bitmap(digest_bitmap: &mut i32, digest: Digest) { |
| 452 | match digest { |
| 453 | Digest::NONE => { |
| 454 | *digest_bitmap |= 1 << DigestBitPosition::NONE_BIT_POSITION as i32; |
| 455 | } |
| 456 | Digest::MD5 => { |
| 457 | *digest_bitmap |= 1 << DigestBitPosition::MD5_BIT_POS as i32; |
| 458 | } |
| 459 | Digest::SHA1 => { |
| 460 | *digest_bitmap |= 1 << DigestBitPosition::SHA_1_BIT_POS as i32; |
| 461 | } |
| 462 | Digest::SHA_2_224 => { |
| 463 | *digest_bitmap |= 1 << DigestBitPosition::SHA_2_224_BIT_POS as i32; |
| 464 | } |
| 465 | Digest::SHA_2_256 => { |
| 466 | *digest_bitmap |= 1 << DigestBitPosition::SHA_2_256_BIT_POS as i32; |
| 467 | } |
| 468 | Digest::SHA_2_384 => { |
| 469 | *digest_bitmap |= 1 << DigestBitPosition::SHA_2_384_BIT_POS as i32; |
| 470 | } |
| 471 | Digest::SHA_2_512 => { |
| 472 | *digest_bitmap |= 1 << DigestBitPosition::SHA_2_512_BIT_POS as i32; |
| 473 | } |
| 474 | _ => {} |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | fn compute_block_mode_bitmap(block_mode_bitmap: &mut i32, block_mode: BlockMode) { |
| 479 | match block_mode { |
| 480 | BlockMode::ECB => { |
| 481 | *block_mode_bitmap |= 1 << BlockModeBitPosition::ECB_BIT_POS as i32; |
| 482 | } |
| 483 | BlockMode::CBC => { |
| 484 | *block_mode_bitmap |= 1 << BlockModeBitPosition::CBC_BIT_POS as i32; |
| 485 | } |
| 486 | BlockMode::CTR => { |
| 487 | *block_mode_bitmap |= 1 << BlockModeBitPosition::CTR_BIT_POS as i32; |
| 488 | } |
| 489 | BlockMode::GCM => { |
| 490 | *block_mode_bitmap |= 1 << BlockModeBitPosition::GCM_BIT_POS as i32; |
| 491 | } |
| 492 | _ => {} |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | fn compute_purpose_bitmap(purpose_bitmap: &mut i32, purpose: KeyPurpose) { |
| 497 | match purpose { |
| 498 | KeyPurpose::ENCRYPT => { |
| 499 | *purpose_bitmap |= 1 << KeyPurposeBitPosition::ENCRYPT_BIT_POS as i32; |
| 500 | } |
| 501 | KeyPurpose::DECRYPT => { |
| 502 | *purpose_bitmap |= 1 << KeyPurposeBitPosition::DECRYPT_BIT_POS as i32; |
| 503 | } |
| 504 | KeyPurpose::SIGN => { |
| 505 | *purpose_bitmap |= 1 << KeyPurposeBitPosition::SIGN_BIT_POS as i32; |
| 506 | } |
| 507 | KeyPurpose::VERIFY => { |
| 508 | *purpose_bitmap |= 1 << KeyPurposeBitPosition::VERIFY_BIT_POS as i32; |
| 509 | } |
| 510 | KeyPurpose::WRAP_KEY => { |
| 511 | *purpose_bitmap |= 1 << KeyPurposeBitPosition::WRAP_KEY_BIT_POS as i32; |
| 512 | } |
| 513 | KeyPurpose::AGREE_KEY => { |
| 514 | *purpose_bitmap |= 1 << KeyPurposeBitPosition::AGREE_KEY_BIT_POS as i32; |
| 515 | } |
| 516 | KeyPurpose::ATTEST_KEY => { |
| 517 | *purpose_bitmap |= 1 << KeyPurposeBitPosition::ATTEST_KEY_BIT_POS as i32; |
| 518 | } |
| 519 | _ => {} |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | fn pull_storage_stats() -> Result<Vec<KeystoreAtom>> { |
| 524 | let mut atom_vec: Vec<KeystoreAtom> = Vec::new(); |
| 525 | let mut append = |stat| { |
| 526 | match stat { |
| 527 | Ok(s) => atom_vec.push(KeystoreAtom { |
| 528 | payload: KeystoreAtomPayload::StorageStats(s), |
| 529 | ..Default::default() |
| 530 | }), |
| 531 | Err(error) => { |
| 532 | log::error!("pull_metrics_callback: Error getting storage stat: {}", error) |
| 533 | } |
| 534 | }; |
| 535 | }; |
| 536 | DB.with(|db| { |
| 537 | let mut db = db.borrow_mut(); |
| 538 | append(db.get_storage_stat(MetricsStorage::DATABASE)); |
| 539 | append(db.get_storage_stat(MetricsStorage::KEY_ENTRY)); |
| 540 | append(db.get_storage_stat(MetricsStorage::KEY_ENTRY_ID_INDEX)); |
| 541 | append(db.get_storage_stat(MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX)); |
| 542 | append(db.get_storage_stat(MetricsStorage::BLOB_ENTRY)); |
| 543 | append(db.get_storage_stat(MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX)); |
| 544 | append(db.get_storage_stat(MetricsStorage::KEY_PARAMETER)); |
| 545 | append(db.get_storage_stat(MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX)); |
| 546 | append(db.get_storage_stat(MetricsStorage::KEY_METADATA)); |
| 547 | append(db.get_storage_stat(MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX)); |
| 548 | append(db.get_storage_stat(MetricsStorage::GRANT)); |
| 549 | append(db.get_storage_stat(MetricsStorage::AUTH_TOKEN)); |
| 550 | append(db.get_storage_stat(MetricsStorage::BLOB_METADATA)); |
| 551 | append(db.get_storage_stat(MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX)); |
| 552 | }); |
| 553 | Ok(atom_vec) |
| 554 | } |
| 555 | |
Hasini Gunasinghe | 8af67ea | 2021-06-30 17:09:01 +0000 | [diff] [blame] | 556 | /// Log error events related to Remote Key Provisioning (RKP). |
Hasini Gunasinghe | adf6692 | 2022-05-10 08:49:53 +0000 | [diff] [blame] | 557 | pub fn log_rkp_error_stats(rkp_error: MetricsRkpError, sec_level: &SecurityLevel) { |
Shaquille Johnson | bcab601 | 2022-09-02 11:16:24 +0000 | [diff] [blame] | 558 | let rkp_error_stats = KeystoreAtomPayload::RkpErrorStats(RkpErrorStats { |
| 559 | rkpError: rkp_error, |
| 560 | security_level: process_security_level(*sec_level), |
| 561 | }); |
Hasini Gunasinghe | 8af67ea | 2021-06-30 17:09:01 +0000 | [diff] [blame] | 562 | METRICS_STORE.insert_atom(AtomID::RKP_ERROR_STATS, rkp_error_stats); |
| 563 | } |
| 564 | |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 565 | /// This function tries to read and update the system property: keystore.crash_count. |
| 566 | /// If the property is absent, it sets the property with value 0. If the property is present, it |
| 567 | /// increments the value. This helps tracking keystore crashes internally. |
| 568 | pub fn update_keystore_crash_sysprop() { |
Eric Biggers | 9f9ab18 | 2023-05-31 21:37:32 +0000 | [diff] [blame^] | 569 | let new_count = match read_keystore_crash_count() { |
| 570 | Ok(Some(count)) => count + 1, |
| 571 | // If the property is absent, then this is the first start up during the boot. |
| 572 | // Proceed to write the system property with value 0. |
| 573 | Ok(None) => 0, |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 574 | Err(error) => { |
Eric Biggers | 9f9ab18 | 2023-05-31 21:37:32 +0000 | [diff] [blame^] | 575 | log::warn!( |
| 576 | concat!( |
| 577 | "In update_keystore_crash_sysprop: ", |
| 578 | "Failed to read the existing system property due to: {:?}.", |
| 579 | "Therefore, keystore crashes will not be logged." |
| 580 | ), |
| 581 | error |
| 582 | ); |
| 583 | return; |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 584 | } |
| 585 | }; |
| 586 | |
Joel Galenson | 7ead3a2 | 2021-07-29 15:27:34 -0700 | [diff] [blame] | 587 | if let Err(e) = |
| 588 | rustutils::system_properties::write(KEYSTORE_CRASH_COUNT_PROPERTY, &new_count.to_string()) |
Joel Galenson | d83784a | 2021-07-21 11:35:25 -0700 | [diff] [blame] | 589 | { |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 590 | log::error!( |
| 591 | concat!( |
| 592 | "In update_keystore_crash_sysprop:: ", |
| 593 | "Failed to write the system property due to error: {:?}" |
| 594 | ), |
| 595 | e |
| 596 | ); |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | /// Read the system property: keystore.crash_count. |
Eric Biggers | 9f9ab18 | 2023-05-31 21:37:32 +0000 | [diff] [blame^] | 601 | pub fn read_keystore_crash_count() -> Result<Option<i32>> { |
| 602 | match rustutils::system_properties::read("keystore.crash_count") { |
| 603 | Ok(Some(count)) => count.parse::<i32>().map(Some).map_err(std::convert::Into::into), |
| 604 | Ok(None) => Ok(None), |
| 605 | Err(e) => Err(e).context(ks_err!("Failed to read crash count property.")), |
| 606 | } |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 607 | } |
| 608 | |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 609 | /// Enum defining the bit position for each padding mode. Since padding mode can be repeatable, it |
| 610 | /// is represented using a bitmap. |
| 611 | #[allow(non_camel_case_types)] |
| 612 | #[repr(i32)] |
| 613 | enum PaddingModeBitPosition { |
| 614 | ///Bit position in the PaddingMode bitmap for NONE. |
| 615 | NONE_BIT_POSITION = 0, |
| 616 | ///Bit position in the PaddingMode bitmap for RSA_OAEP. |
| 617 | RSA_OAEP_BIT_POS = 1, |
| 618 | ///Bit position in the PaddingMode bitmap for RSA_PSS. |
| 619 | RSA_PSS_BIT_POS = 2, |
| 620 | ///Bit position in the PaddingMode bitmap for RSA_PKCS1_1_5_ENCRYPT. |
| 621 | RSA_PKCS1_1_5_ENCRYPT_BIT_POS = 3, |
| 622 | ///Bit position in the PaddingMode bitmap for RSA_PKCS1_1_5_SIGN. |
| 623 | RSA_PKCS1_1_5_SIGN_BIT_POS = 4, |
| 624 | ///Bit position in the PaddingMode bitmap for RSA_PKCS7. |
| 625 | PKCS7_BIT_POS = 5, |
| 626 | } |
| 627 | |
| 628 | /// Enum defining the bit position for each digest type. Since digest can be repeatable in |
| 629 | /// key parameters, it is represented using a bitmap. |
| 630 | #[allow(non_camel_case_types)] |
| 631 | #[repr(i32)] |
| 632 | enum DigestBitPosition { |
| 633 | ///Bit position in the Digest bitmap for NONE. |
| 634 | NONE_BIT_POSITION = 0, |
| 635 | ///Bit position in the Digest bitmap for MD5. |
| 636 | MD5_BIT_POS = 1, |
| 637 | ///Bit position in the Digest bitmap for SHA1. |
| 638 | SHA_1_BIT_POS = 2, |
| 639 | ///Bit position in the Digest bitmap for SHA_2_224. |
| 640 | SHA_2_224_BIT_POS = 3, |
| 641 | ///Bit position in the Digest bitmap for SHA_2_256. |
| 642 | SHA_2_256_BIT_POS = 4, |
| 643 | ///Bit position in the Digest bitmap for SHA_2_384. |
| 644 | SHA_2_384_BIT_POS = 5, |
| 645 | ///Bit position in the Digest bitmap for SHA_2_512. |
| 646 | SHA_2_512_BIT_POS = 6, |
| 647 | } |
| 648 | |
| 649 | /// Enum defining the bit position for each block mode type. Since block mode can be repeatable in |
| 650 | /// key parameters, it is represented using a bitmap. |
| 651 | #[allow(non_camel_case_types)] |
| 652 | #[repr(i32)] |
| 653 | enum BlockModeBitPosition { |
| 654 | ///Bit position in the BlockMode bitmap for ECB. |
| 655 | ECB_BIT_POS = 1, |
| 656 | ///Bit position in the BlockMode bitmap for CBC. |
| 657 | CBC_BIT_POS = 2, |
| 658 | ///Bit position in the BlockMode bitmap for CTR. |
| 659 | CTR_BIT_POS = 3, |
| 660 | ///Bit position in the BlockMode bitmap for GCM. |
| 661 | GCM_BIT_POS = 4, |
| 662 | } |
| 663 | |
| 664 | /// Enum defining the bit position for each key purpose. Since key purpose can be repeatable in |
| 665 | /// key parameters, it is represented using a bitmap. |
| 666 | #[allow(non_camel_case_types)] |
| 667 | #[repr(i32)] |
| 668 | enum KeyPurposeBitPosition { |
| 669 | ///Bit position in the KeyPurpose bitmap for Encrypt. |
| 670 | ENCRYPT_BIT_POS = 1, |
| 671 | ///Bit position in the KeyPurpose bitmap for Decrypt. |
| 672 | DECRYPT_BIT_POS = 2, |
| 673 | ///Bit position in the KeyPurpose bitmap for Sign. |
| 674 | SIGN_BIT_POS = 3, |
| 675 | ///Bit position in the KeyPurpose bitmap for Verify. |
| 676 | VERIFY_BIT_POS = 4, |
| 677 | ///Bit position in the KeyPurpose bitmap for Wrap Key. |
| 678 | WRAP_KEY_BIT_POS = 5, |
| 679 | ///Bit position in the KeyPurpose bitmap for Agree Key. |
| 680 | AGREE_KEY_BIT_POS = 6, |
| 681 | ///Bit position in the KeyPurpose bitmap for Attest Key. |
| 682 | ATTEST_KEY_BIT_POS = 7, |
| 683 | } |