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