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 | cd6fc7a | 2023-08-31 11:46:32 -0400 | [diff] [blame] | 20 | use crate::error::anyhow_error_to_serialized_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; |
| 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 std::collections::HashMap; |
Andrew Walbran | a4bc1a9 | 2024-09-03 13:08:17 +0100 | [diff] [blame] | 48 | use std::sync::{LazyLock, Mutex}; |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 49 | |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 50 | // Note: Crash events are recorded at keystore restarts, based on the assumption that keystore only |
| 51 | // gets restarted after a crash, during a boot cycle. |
| 52 | const KEYSTORE_CRASH_COUNT_PROPERTY: &str = "keystore.crash_count"; |
| 53 | |
Andrew Walbran | a4bc1a9 | 2024-09-03 13:08:17 +0100 | [diff] [blame] | 54 | /// Singleton for MetricsStore. |
| 55 | pub static METRICS_STORE: LazyLock<MetricsStore> = LazyLock::new(Default::default); |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 56 | |
| 57 | /// MetricsStore stores the <atom object, count> as <key, value> in the inner hash map, |
| 58 | /// indexed by the atom id, in the outer hash map. |
| 59 | /// There can be different atom objects with the same atom id based on the values assigned to the |
| 60 | /// fields of the atom objects. When an atom object with a particular combination of field values is |
| 61 | /// inserted, we first check if that atom object is in the inner hash map. If one exists, count |
| 62 | /// is inceremented. Otherwise, the atom object is inserted with count = 1. Note that count field |
| 63 | /// of the atom object itself is set to 0 while the object is stored in the hash map. When the atom |
| 64 | /// objects are queried by the atom id, the corresponding atom objects are retrieved, cloned, and |
| 65 | /// the count field of the cloned objects is set to the corresponding value field in the inner hash |
| 66 | /// map before the query result is returned. |
| 67 | #[derive(Default)] |
| 68 | pub struct MetricsStore { |
| 69 | metrics_store: Mutex<HashMap<AtomID, HashMap<KeystoreAtomPayload, i32>>>, |
| 70 | } |
| 71 | |
David Drysdale | 49811e2 | 2023-05-22 18:51:30 +0100 | [diff] [blame] | 72 | impl std::fmt::Debug for MetricsStore { |
| 73 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { |
| 74 | let store = self.metrics_store.lock().unwrap(); |
| 75 | let mut atom_ids: Vec<&AtomID> = store.keys().collect(); |
| 76 | atom_ids.sort(); |
| 77 | for atom_id in atom_ids { |
| 78 | writeln!(f, " {} : [", atom_id.show())?; |
| 79 | let data = store.get(atom_id).unwrap(); |
| 80 | let mut payloads: Vec<&KeystoreAtomPayload> = data.keys().collect(); |
| 81 | payloads.sort(); |
| 82 | for payload in payloads { |
| 83 | let count = data.get(payload).unwrap(); |
| 84 | writeln!(f, " {} => count={count}", payload.show())?; |
| 85 | } |
| 86 | writeln!(f, " ]")?; |
| 87 | } |
| 88 | Ok(()) |
| 89 | } |
| 90 | } |
| 91 | |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 92 | impl MetricsStore { |
| 93 | /// There are some atoms whose maximum cardinality exceeds the cardinality limits tolerated |
| 94 | /// by statsd. Statsd tolerates cardinality between 200-300. Therefore, the in-memory storage |
| 95 | /// limit for a single atom is set to 250. If the number of atom objects created for a |
| 96 | /// particular atom exceeds this limit, an overflow atom object is created to track the ID of |
| 97 | /// such atoms. |
| 98 | const SINGLE_ATOM_STORE_MAX_SIZE: usize = 250; |
| 99 | |
| 100 | /// Return a vector of atom objects with the given atom ID, if one exists in the metrics_store. |
| 101 | /// If any atom object does not exist in the metrics_store for the given atom ID, return an |
| 102 | /// empty vector. |
| 103 | pub fn get_atoms(&self, atom_id: AtomID) -> Result<Vec<KeystoreAtom>> { |
| 104 | // StorageStats is an original pulled atom (i.e. not a pushed atom converted to a |
David Drysdale | 49811e2 | 2023-05-22 18:51:30 +0100 | [diff] [blame] | 105 | // pulled atom). Therefore, it is handled separately. |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 106 | if AtomID::STORAGE_STATS == atom_id { |
| 107 | return pull_storage_stats(); |
| 108 | } |
| 109 | |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 110 | // Process keystore crash stats. |
| 111 | if AtomID::CRASH_STATS == atom_id { |
Eric Biggers | 9f9ab18 | 2023-05-31 21:37:32 +0000 | [diff] [blame] | 112 | return match read_keystore_crash_count()? { |
| 113 | Some(count) => Ok(vec![KeystoreAtom { |
| 114 | payload: KeystoreAtomPayload::CrashStats(CrashStats { |
| 115 | count_of_crash_events: count, |
| 116 | }), |
| 117 | ..Default::default() |
| 118 | }]), |
| 119 | None => Err(anyhow!("Crash count property is not set")), |
| 120 | }; |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 121 | } |
| 122 | |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 123 | // It is safe to call unwrap here since the lock can not be poisoned based on its usage |
| 124 | // in this module and the lock is not acquired in the same thread before. |
| 125 | let metrics_store_guard = self.metrics_store.lock().unwrap(); |
| 126 | metrics_store_guard.get(&atom_id).map_or(Ok(Vec::<KeystoreAtom>::new()), |atom_count_map| { |
| 127 | Ok(atom_count_map |
| 128 | .iter() |
| 129 | .map(|(atom, count)| KeystoreAtom { payload: atom.clone(), count: *count }) |
| 130 | .collect()) |
| 131 | }) |
| 132 | } |
| 133 | |
| 134 | /// Insert an atom object to the metrics_store indexed by the atom ID. |
| 135 | fn insert_atom(&self, atom_id: AtomID, atom: KeystoreAtomPayload) { |
| 136 | // It is ok to unwrap here since the mutex cannot be poisoned according to the way it is |
| 137 | // used in this module. And the lock is not acquired by this thread before. |
| 138 | let mut metrics_store_guard = self.metrics_store.lock().unwrap(); |
Charisee | 6fff58e | 2023-10-14 21:09:04 +0000 | [diff] [blame] | 139 | let atom_count_map = metrics_store_guard.entry(atom_id).or_default(); |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 140 | if atom_count_map.len() < MetricsStore::SINGLE_ATOM_STORE_MAX_SIZE { |
| 141 | let atom_count = atom_count_map.entry(atom).or_insert(0); |
| 142 | *atom_count += 1; |
| 143 | } else { |
| 144 | // Insert an overflow atom |
Charisee | 6fff58e | 2023-10-14 21:09:04 +0000 | [diff] [blame] | 145 | let overflow_atom_count_map = |
| 146 | metrics_store_guard.entry(AtomID::KEYSTORE2_ATOM_WITH_OVERFLOW).or_default(); |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 147 | |
| 148 | if overflow_atom_count_map.len() < MetricsStore::SINGLE_ATOM_STORE_MAX_SIZE { |
| 149 | let overflow_atom = Keystore2AtomWithOverflow { atom_id }; |
| 150 | let atom_count = overflow_atom_count_map |
| 151 | .entry(KeystoreAtomPayload::Keystore2AtomWithOverflow(overflow_atom)) |
| 152 | .or_insert(0); |
| 153 | *atom_count += 1; |
| 154 | } else { |
| 155 | // This is a rare case, if at all. |
| 156 | log::error!("In insert_atom: Maximum storage limit reached for overflow atom.") |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | /// Log key creation events to be sent to statsd. |
| 163 | pub fn log_key_creation_event_stats<U>( |
| 164 | sec_level: SecurityLevel, |
| 165 | key_params: &[KeyParameter], |
| 166 | result: &Result<U>, |
| 167 | ) { |
| 168 | let ( |
| 169 | key_creation_with_general_info, |
| 170 | key_creation_with_auth_info, |
| 171 | key_creation_with_purpose_and_modes_info, |
| 172 | ) = process_key_creation_event_stats(sec_level, key_params, result); |
| 173 | |
| 174 | METRICS_STORE |
| 175 | .insert_atom(AtomID::KEY_CREATION_WITH_GENERAL_INFO, key_creation_with_general_info); |
| 176 | METRICS_STORE.insert_atom(AtomID::KEY_CREATION_WITH_AUTH_INFO, key_creation_with_auth_info); |
| 177 | METRICS_STORE.insert_atom( |
| 178 | AtomID::KEY_CREATION_WITH_PURPOSE_AND_MODES_INFO, |
| 179 | key_creation_with_purpose_and_modes_info, |
| 180 | ); |
| 181 | } |
| 182 | |
| 183 | // Process the statistics related to key creations and return the three atom objects related to key |
| 184 | // creations: i) KeyCreationWithGeneralInfo ii) KeyCreationWithAuthInfo |
| 185 | // iii) KeyCreationWithPurposeAndModesInfo |
| 186 | fn process_key_creation_event_stats<U>( |
| 187 | sec_level: SecurityLevel, |
| 188 | key_params: &[KeyParameter], |
| 189 | result: &Result<U>, |
| 190 | ) -> (KeystoreAtomPayload, KeystoreAtomPayload, KeystoreAtomPayload) { |
| 191 | // In the default atom objects, fields represented by bitmaps and i32 fields |
| 192 | // will take 0, except error_code which defaults to 1 indicating NO_ERROR and key_size, |
| 193 | // and auth_time_out which defaults to -1. |
| 194 | // The boolean fields are set to false by default. |
| 195 | // Some keymint enums do have 0 as an enum variant value. In such cases, the corresponding |
| 196 | // enum variant value in atoms.proto is incremented by 1, in order to have 0 as the reserved |
| 197 | // value for unspecified fields. |
| 198 | let mut key_creation_with_general_info = KeyCreationWithGeneralInfo { |
| 199 | algorithm: MetricsAlgorithm::ALGORITHM_UNSPECIFIED, |
| 200 | key_size: -1, |
| 201 | ec_curve: MetricsEcCurve::EC_CURVE_UNSPECIFIED, |
| 202 | key_origin: MetricsKeyOrigin::ORIGIN_UNSPECIFIED, |
| 203 | error_code: 1, |
| 204 | // Default for bool is false (for attestation_requested field). |
| 205 | ..Default::default() |
| 206 | }; |
| 207 | |
| 208 | let mut key_creation_with_auth_info = KeyCreationWithAuthInfo { |
| 209 | user_auth_type: MetricsHardwareAuthenticatorType::AUTH_TYPE_UNSPECIFIED, |
| 210 | log10_auth_key_timeout_seconds: -1, |
| 211 | security_level: MetricsSecurityLevel::SECURITY_LEVEL_UNSPECIFIED, |
| 212 | }; |
| 213 | |
| 214 | let mut key_creation_with_purpose_and_modes_info = KeyCreationWithPurposeAndModesInfo { |
| 215 | algorithm: MetricsAlgorithm::ALGORITHM_UNSPECIFIED, |
| 216 | // Default for i32 is 0 (for the remaining bitmap fields). |
| 217 | ..Default::default() |
| 218 | }; |
| 219 | |
| 220 | if let Err(ref e) = result { |
Tri Vo | cd6fc7a | 2023-08-31 11:46:32 -0400 | [diff] [blame] | 221 | key_creation_with_general_info.error_code = anyhow_error_to_serialized_error(e).0; |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 222 | } |
| 223 | |
| 224 | key_creation_with_auth_info.security_level = process_security_level(sec_level); |
| 225 | |
| 226 | for key_param in key_params.iter().map(KsKeyParamValue::from) { |
| 227 | match key_param { |
| 228 | KsKeyParamValue::Algorithm(a) => { |
| 229 | let algorithm = match a { |
| 230 | Algorithm::RSA => MetricsAlgorithm::RSA, |
| 231 | Algorithm::EC => MetricsAlgorithm::EC, |
| 232 | Algorithm::AES => MetricsAlgorithm::AES, |
| 233 | Algorithm::TRIPLE_DES => MetricsAlgorithm::TRIPLE_DES, |
| 234 | Algorithm::HMAC => MetricsAlgorithm::HMAC, |
| 235 | _ => MetricsAlgorithm::ALGORITHM_UNSPECIFIED, |
| 236 | }; |
| 237 | key_creation_with_general_info.algorithm = algorithm; |
| 238 | key_creation_with_purpose_and_modes_info.algorithm = algorithm; |
| 239 | } |
| 240 | KsKeyParamValue::KeySize(s) => { |
| 241 | key_creation_with_general_info.key_size = s; |
| 242 | } |
| 243 | KsKeyParamValue::KeyOrigin(o) => { |
| 244 | key_creation_with_general_info.key_origin = match o { |
| 245 | KeyOrigin::GENERATED => MetricsKeyOrigin::GENERATED, |
| 246 | KeyOrigin::DERIVED => MetricsKeyOrigin::DERIVED, |
| 247 | KeyOrigin::IMPORTED => MetricsKeyOrigin::IMPORTED, |
| 248 | KeyOrigin::RESERVED => MetricsKeyOrigin::RESERVED, |
| 249 | KeyOrigin::SECURELY_IMPORTED => MetricsKeyOrigin::SECURELY_IMPORTED, |
| 250 | _ => MetricsKeyOrigin::ORIGIN_UNSPECIFIED, |
| 251 | } |
| 252 | } |
| 253 | KsKeyParamValue::HardwareAuthenticatorType(a) => { |
| 254 | key_creation_with_auth_info.user_auth_type = match a { |
| 255 | HardwareAuthenticatorType::NONE => MetricsHardwareAuthenticatorType::NONE, |
| 256 | HardwareAuthenticatorType::PASSWORD => { |
| 257 | MetricsHardwareAuthenticatorType::PASSWORD |
| 258 | } |
| 259 | HardwareAuthenticatorType::FINGERPRINT => { |
| 260 | MetricsHardwareAuthenticatorType::FINGERPRINT |
| 261 | } |
| 262 | HardwareAuthenticatorType::ANY => MetricsHardwareAuthenticatorType::ANY, |
| 263 | _ => MetricsHardwareAuthenticatorType::AUTH_TYPE_UNSPECIFIED, |
| 264 | } |
| 265 | } |
| 266 | KsKeyParamValue::AuthTimeout(t) => { |
| 267 | key_creation_with_auth_info.log10_auth_key_timeout_seconds = |
| 268 | f32::log10(t as f32) as i32; |
| 269 | } |
| 270 | KsKeyParamValue::PaddingMode(p) => { |
| 271 | compute_padding_mode_bitmap( |
| 272 | &mut key_creation_with_purpose_and_modes_info.padding_mode_bitmap, |
| 273 | p, |
| 274 | ); |
| 275 | } |
| 276 | KsKeyParamValue::Digest(d) => { |
| 277 | // key_creation_with_purpose_and_modes_info.digest_bitmap = |
| 278 | compute_digest_bitmap( |
| 279 | &mut key_creation_with_purpose_and_modes_info.digest_bitmap, |
| 280 | d, |
| 281 | ); |
| 282 | } |
| 283 | KsKeyParamValue::BlockMode(b) => { |
| 284 | compute_block_mode_bitmap( |
| 285 | &mut key_creation_with_purpose_and_modes_info.block_mode_bitmap, |
| 286 | b, |
| 287 | ); |
| 288 | } |
| 289 | KsKeyParamValue::KeyPurpose(k) => { |
| 290 | compute_purpose_bitmap( |
| 291 | &mut key_creation_with_purpose_and_modes_info.purpose_bitmap, |
| 292 | k, |
| 293 | ); |
| 294 | } |
| 295 | KsKeyParamValue::EcCurve(e) => { |
| 296 | key_creation_with_general_info.ec_curve = match e { |
| 297 | EcCurve::P_224 => MetricsEcCurve::P_224, |
| 298 | EcCurve::P_256 => MetricsEcCurve::P_256, |
| 299 | EcCurve::P_384 => MetricsEcCurve::P_384, |
| 300 | EcCurve::P_521 => MetricsEcCurve::P_521, |
Seth Moore | 49d700d | 2021-12-13 20:03:33 +0000 | [diff] [blame] | 301 | EcCurve::CURVE_25519 => MetricsEcCurve::CURVE_25519, |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 302 | _ => MetricsEcCurve::EC_CURVE_UNSPECIFIED, |
| 303 | } |
| 304 | } |
| 305 | KsKeyParamValue::AttestationChallenge(_) => { |
| 306 | key_creation_with_general_info.attestation_requested = true; |
| 307 | } |
| 308 | _ => {} |
| 309 | } |
| 310 | } |
| 311 | if key_creation_with_general_info.algorithm == MetricsAlgorithm::EC { |
| 312 | // Do not record key sizes if Algorithm = EC, in order to reduce cardinality. |
| 313 | key_creation_with_general_info.key_size = -1; |
| 314 | } |
| 315 | |
| 316 | ( |
| 317 | KeystoreAtomPayload::KeyCreationWithGeneralInfo(key_creation_with_general_info), |
| 318 | KeystoreAtomPayload::KeyCreationWithAuthInfo(key_creation_with_auth_info), |
| 319 | KeystoreAtomPayload::KeyCreationWithPurposeAndModesInfo( |
| 320 | key_creation_with_purpose_and_modes_info, |
| 321 | ), |
| 322 | ) |
| 323 | } |
| 324 | |
| 325 | /// Log key operation events to be sent to statsd. |
| 326 | pub fn log_key_operation_event_stats( |
| 327 | sec_level: SecurityLevel, |
| 328 | key_purpose: KeyPurpose, |
| 329 | op_params: &[KeyParameter], |
| 330 | op_outcome: &Outcome, |
| 331 | key_upgraded: bool, |
| 332 | ) { |
| 333 | let (key_operation_with_general_info, key_operation_with_purpose_and_modes_info) = |
| 334 | process_key_operation_event_stats( |
| 335 | sec_level, |
| 336 | key_purpose, |
| 337 | op_params, |
| 338 | op_outcome, |
| 339 | key_upgraded, |
| 340 | ); |
| 341 | METRICS_STORE |
| 342 | .insert_atom(AtomID::KEY_OPERATION_WITH_GENERAL_INFO, key_operation_with_general_info); |
| 343 | METRICS_STORE.insert_atom( |
| 344 | AtomID::KEY_OPERATION_WITH_PURPOSE_AND_MODES_INFO, |
| 345 | key_operation_with_purpose_and_modes_info, |
| 346 | ); |
| 347 | } |
| 348 | |
| 349 | // Process the statistics related to key operations and return the two atom objects related to key |
| 350 | // operations: i) KeyOperationWithGeneralInfo ii) KeyOperationWithPurposeAndModesInfo |
| 351 | fn process_key_operation_event_stats( |
| 352 | sec_level: SecurityLevel, |
| 353 | key_purpose: KeyPurpose, |
| 354 | op_params: &[KeyParameter], |
| 355 | op_outcome: &Outcome, |
| 356 | key_upgraded: bool, |
| 357 | ) -> (KeystoreAtomPayload, KeystoreAtomPayload) { |
| 358 | let mut key_operation_with_general_info = KeyOperationWithGeneralInfo { |
| 359 | outcome: MetricsOutcome::OUTCOME_UNSPECIFIED, |
| 360 | error_code: 1, |
| 361 | security_level: MetricsSecurityLevel::SECURITY_LEVEL_UNSPECIFIED, |
| 362 | // Default for bool is false (for key_upgraded field). |
| 363 | ..Default::default() |
| 364 | }; |
| 365 | |
| 366 | let mut key_operation_with_purpose_and_modes_info = KeyOperationWithPurposeAndModesInfo { |
| 367 | purpose: MetricsPurpose::KEY_PURPOSE_UNSPECIFIED, |
| 368 | // Default for i32 is 0 (for the remaining bitmap fields). |
| 369 | ..Default::default() |
| 370 | }; |
| 371 | |
| 372 | key_operation_with_general_info.security_level = process_security_level(sec_level); |
| 373 | |
| 374 | key_operation_with_general_info.key_upgraded = key_upgraded; |
| 375 | |
| 376 | key_operation_with_purpose_and_modes_info.purpose = match key_purpose { |
| 377 | KeyPurpose::ENCRYPT => MetricsPurpose::ENCRYPT, |
| 378 | KeyPurpose::DECRYPT => MetricsPurpose::DECRYPT, |
| 379 | KeyPurpose::SIGN => MetricsPurpose::SIGN, |
| 380 | KeyPurpose::VERIFY => MetricsPurpose::VERIFY, |
| 381 | KeyPurpose::WRAP_KEY => MetricsPurpose::WRAP_KEY, |
| 382 | KeyPurpose::AGREE_KEY => MetricsPurpose::AGREE_KEY, |
| 383 | KeyPurpose::ATTEST_KEY => MetricsPurpose::ATTEST_KEY, |
| 384 | _ => MetricsPurpose::KEY_PURPOSE_UNSPECIFIED, |
| 385 | }; |
| 386 | |
| 387 | key_operation_with_general_info.outcome = match op_outcome { |
| 388 | Outcome::Unknown | Outcome::Dropped => MetricsOutcome::DROPPED, |
| 389 | Outcome::Success => MetricsOutcome::SUCCESS, |
| 390 | Outcome::Abort => MetricsOutcome::ABORT, |
| 391 | Outcome::Pruned => MetricsOutcome::PRUNED, |
| 392 | Outcome::ErrorCode(e) => { |
| 393 | key_operation_with_general_info.error_code = e.0; |
| 394 | MetricsOutcome::ERROR |
| 395 | } |
| 396 | }; |
| 397 | |
| 398 | for key_param in op_params.iter().map(KsKeyParamValue::from) { |
| 399 | match key_param { |
| 400 | KsKeyParamValue::PaddingMode(p) => { |
| 401 | compute_padding_mode_bitmap( |
| 402 | &mut key_operation_with_purpose_and_modes_info.padding_mode_bitmap, |
| 403 | p, |
| 404 | ); |
| 405 | } |
| 406 | KsKeyParamValue::Digest(d) => { |
| 407 | compute_digest_bitmap( |
| 408 | &mut key_operation_with_purpose_and_modes_info.digest_bitmap, |
| 409 | d, |
| 410 | ); |
| 411 | } |
| 412 | KsKeyParamValue::BlockMode(b) => { |
| 413 | compute_block_mode_bitmap( |
| 414 | &mut key_operation_with_purpose_and_modes_info.block_mode_bitmap, |
| 415 | b, |
| 416 | ); |
| 417 | } |
| 418 | _ => {} |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | ( |
| 423 | KeystoreAtomPayload::KeyOperationWithGeneralInfo(key_operation_with_general_info), |
| 424 | KeystoreAtomPayload::KeyOperationWithPurposeAndModesInfo( |
| 425 | key_operation_with_purpose_and_modes_info, |
| 426 | ), |
| 427 | ) |
| 428 | } |
| 429 | |
| 430 | fn process_security_level(sec_level: SecurityLevel) -> MetricsSecurityLevel { |
| 431 | match sec_level { |
| 432 | SecurityLevel::SOFTWARE => MetricsSecurityLevel::SECURITY_LEVEL_SOFTWARE, |
| 433 | SecurityLevel::TRUSTED_ENVIRONMENT => { |
| 434 | MetricsSecurityLevel::SECURITY_LEVEL_TRUSTED_ENVIRONMENT |
| 435 | } |
| 436 | SecurityLevel::STRONGBOX => MetricsSecurityLevel::SECURITY_LEVEL_STRONGBOX, |
| 437 | SecurityLevel::KEYSTORE => MetricsSecurityLevel::SECURITY_LEVEL_KEYSTORE, |
| 438 | _ => MetricsSecurityLevel::SECURITY_LEVEL_UNSPECIFIED, |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | fn compute_padding_mode_bitmap(padding_mode_bitmap: &mut i32, padding_mode: PaddingMode) { |
| 443 | match padding_mode { |
| 444 | PaddingMode::NONE => { |
| 445 | *padding_mode_bitmap |= 1 << PaddingModeBitPosition::NONE_BIT_POSITION as i32; |
| 446 | } |
| 447 | PaddingMode::RSA_OAEP => { |
| 448 | *padding_mode_bitmap |= 1 << PaddingModeBitPosition::RSA_OAEP_BIT_POS as i32; |
| 449 | } |
| 450 | PaddingMode::RSA_PSS => { |
| 451 | *padding_mode_bitmap |= 1 << PaddingModeBitPosition::RSA_PSS_BIT_POS as i32; |
| 452 | } |
| 453 | PaddingMode::RSA_PKCS1_1_5_ENCRYPT => { |
| 454 | *padding_mode_bitmap |= |
| 455 | 1 << PaddingModeBitPosition::RSA_PKCS1_1_5_ENCRYPT_BIT_POS as i32; |
| 456 | } |
| 457 | PaddingMode::RSA_PKCS1_1_5_SIGN => { |
| 458 | *padding_mode_bitmap |= 1 << PaddingModeBitPosition::RSA_PKCS1_1_5_SIGN_BIT_POS as i32; |
| 459 | } |
| 460 | PaddingMode::PKCS7 => { |
| 461 | *padding_mode_bitmap |= 1 << PaddingModeBitPosition::PKCS7_BIT_POS as i32; |
| 462 | } |
| 463 | _ => {} |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | fn compute_digest_bitmap(digest_bitmap: &mut i32, digest: Digest) { |
| 468 | match digest { |
| 469 | Digest::NONE => { |
| 470 | *digest_bitmap |= 1 << DigestBitPosition::NONE_BIT_POSITION as i32; |
| 471 | } |
| 472 | Digest::MD5 => { |
| 473 | *digest_bitmap |= 1 << DigestBitPosition::MD5_BIT_POS as i32; |
| 474 | } |
| 475 | Digest::SHA1 => { |
| 476 | *digest_bitmap |= 1 << DigestBitPosition::SHA_1_BIT_POS as i32; |
| 477 | } |
| 478 | Digest::SHA_2_224 => { |
| 479 | *digest_bitmap |= 1 << DigestBitPosition::SHA_2_224_BIT_POS as i32; |
| 480 | } |
| 481 | Digest::SHA_2_256 => { |
| 482 | *digest_bitmap |= 1 << DigestBitPosition::SHA_2_256_BIT_POS as i32; |
| 483 | } |
| 484 | Digest::SHA_2_384 => { |
| 485 | *digest_bitmap |= 1 << DigestBitPosition::SHA_2_384_BIT_POS as i32; |
| 486 | } |
| 487 | Digest::SHA_2_512 => { |
| 488 | *digest_bitmap |= 1 << DigestBitPosition::SHA_2_512_BIT_POS as i32; |
| 489 | } |
| 490 | _ => {} |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | fn compute_block_mode_bitmap(block_mode_bitmap: &mut i32, block_mode: BlockMode) { |
| 495 | match block_mode { |
| 496 | BlockMode::ECB => { |
| 497 | *block_mode_bitmap |= 1 << BlockModeBitPosition::ECB_BIT_POS as i32; |
| 498 | } |
| 499 | BlockMode::CBC => { |
| 500 | *block_mode_bitmap |= 1 << BlockModeBitPosition::CBC_BIT_POS as i32; |
| 501 | } |
| 502 | BlockMode::CTR => { |
| 503 | *block_mode_bitmap |= 1 << BlockModeBitPosition::CTR_BIT_POS as i32; |
| 504 | } |
| 505 | BlockMode::GCM => { |
| 506 | *block_mode_bitmap |= 1 << BlockModeBitPosition::GCM_BIT_POS as i32; |
| 507 | } |
| 508 | _ => {} |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | fn compute_purpose_bitmap(purpose_bitmap: &mut i32, purpose: KeyPurpose) { |
| 513 | match purpose { |
| 514 | KeyPurpose::ENCRYPT => { |
| 515 | *purpose_bitmap |= 1 << KeyPurposeBitPosition::ENCRYPT_BIT_POS as i32; |
| 516 | } |
| 517 | KeyPurpose::DECRYPT => { |
| 518 | *purpose_bitmap |= 1 << KeyPurposeBitPosition::DECRYPT_BIT_POS as i32; |
| 519 | } |
| 520 | KeyPurpose::SIGN => { |
| 521 | *purpose_bitmap |= 1 << KeyPurposeBitPosition::SIGN_BIT_POS as i32; |
| 522 | } |
| 523 | KeyPurpose::VERIFY => { |
| 524 | *purpose_bitmap |= 1 << KeyPurposeBitPosition::VERIFY_BIT_POS as i32; |
| 525 | } |
| 526 | KeyPurpose::WRAP_KEY => { |
| 527 | *purpose_bitmap |= 1 << KeyPurposeBitPosition::WRAP_KEY_BIT_POS as i32; |
| 528 | } |
| 529 | KeyPurpose::AGREE_KEY => { |
| 530 | *purpose_bitmap |= 1 << KeyPurposeBitPosition::AGREE_KEY_BIT_POS as i32; |
| 531 | } |
| 532 | KeyPurpose::ATTEST_KEY => { |
| 533 | *purpose_bitmap |= 1 << KeyPurposeBitPosition::ATTEST_KEY_BIT_POS as i32; |
| 534 | } |
| 535 | _ => {} |
| 536 | } |
| 537 | } |
| 538 | |
David Drysdale | da89743 | 2024-06-24 15:57:35 +0100 | [diff] [blame] | 539 | pub(crate) fn pull_storage_stats() -> Result<Vec<KeystoreAtom>> { |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 540 | let mut atom_vec: Vec<KeystoreAtom> = Vec::new(); |
| 541 | let mut append = |stat| { |
| 542 | match stat { |
| 543 | Ok(s) => atom_vec.push(KeystoreAtom { |
| 544 | payload: KeystoreAtomPayload::StorageStats(s), |
| 545 | ..Default::default() |
| 546 | }), |
| 547 | Err(error) => { |
| 548 | log::error!("pull_metrics_callback: Error getting storage stat: {}", error) |
| 549 | } |
| 550 | }; |
| 551 | }; |
| 552 | DB.with(|db| { |
| 553 | let mut db = db.borrow_mut(); |
| 554 | append(db.get_storage_stat(MetricsStorage::DATABASE)); |
| 555 | append(db.get_storage_stat(MetricsStorage::KEY_ENTRY)); |
| 556 | append(db.get_storage_stat(MetricsStorage::KEY_ENTRY_ID_INDEX)); |
| 557 | append(db.get_storage_stat(MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX)); |
| 558 | append(db.get_storage_stat(MetricsStorage::BLOB_ENTRY)); |
| 559 | append(db.get_storage_stat(MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX)); |
| 560 | append(db.get_storage_stat(MetricsStorage::KEY_PARAMETER)); |
| 561 | append(db.get_storage_stat(MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX)); |
| 562 | append(db.get_storage_stat(MetricsStorage::KEY_METADATA)); |
| 563 | append(db.get_storage_stat(MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX)); |
| 564 | append(db.get_storage_stat(MetricsStorage::GRANT)); |
| 565 | append(db.get_storage_stat(MetricsStorage::AUTH_TOKEN)); |
| 566 | append(db.get_storage_stat(MetricsStorage::BLOB_METADATA)); |
| 567 | append(db.get_storage_stat(MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX)); |
| 568 | }); |
| 569 | Ok(atom_vec) |
| 570 | } |
| 571 | |
Hasini Gunasinghe | 8af67ea | 2021-06-30 17:09:01 +0000 | [diff] [blame] | 572 | /// Log error events related to Remote Key Provisioning (RKP). |
Hasini Gunasinghe | adf6692 | 2022-05-10 08:49:53 +0000 | [diff] [blame] | 573 | pub fn log_rkp_error_stats(rkp_error: MetricsRkpError, sec_level: &SecurityLevel) { |
Shaquille Johnson | bcab601 | 2022-09-02 11:16:24 +0000 | [diff] [blame] | 574 | let rkp_error_stats = KeystoreAtomPayload::RkpErrorStats(RkpErrorStats { |
| 575 | rkpError: rkp_error, |
| 576 | security_level: process_security_level(*sec_level), |
| 577 | }); |
Hasini Gunasinghe | 8af67ea | 2021-06-30 17:09:01 +0000 | [diff] [blame] | 578 | METRICS_STORE.insert_atom(AtomID::RKP_ERROR_STATS, rkp_error_stats); |
| 579 | } |
| 580 | |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 581 | /// This function tries to read and update the system property: keystore.crash_count. |
| 582 | /// If the property is absent, it sets the property with value 0. If the property is present, it |
| 583 | /// increments the value. This helps tracking keystore crashes internally. |
| 584 | pub fn update_keystore_crash_sysprop() { |
Eric Biggers | 9f9ab18 | 2023-05-31 21:37:32 +0000 | [diff] [blame] | 585 | let new_count = match read_keystore_crash_count() { |
| 586 | Ok(Some(count)) => count + 1, |
| 587 | // If the property is absent, then this is the first start up during the boot. |
| 588 | // Proceed to write the system property with value 0. |
| 589 | Ok(None) => 0, |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 590 | Err(error) => { |
Eric Biggers | 9f9ab18 | 2023-05-31 21:37:32 +0000 | [diff] [blame] | 591 | log::warn!( |
| 592 | concat!( |
| 593 | "In update_keystore_crash_sysprop: ", |
| 594 | "Failed to read the existing system property due to: {:?}.", |
| 595 | "Therefore, keystore crashes will not be logged." |
| 596 | ), |
| 597 | error |
| 598 | ); |
| 599 | return; |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 600 | } |
| 601 | }; |
| 602 | |
Joel Galenson | 7ead3a2 | 2021-07-29 15:27:34 -0700 | [diff] [blame] | 603 | if let Err(e) = |
| 604 | rustutils::system_properties::write(KEYSTORE_CRASH_COUNT_PROPERTY, &new_count.to_string()) |
Joel Galenson | d83784a | 2021-07-21 11:35:25 -0700 | [diff] [blame] | 605 | { |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 606 | log::error!( |
| 607 | concat!( |
| 608 | "In update_keystore_crash_sysprop:: ", |
| 609 | "Failed to write the system property due to error: {:?}" |
| 610 | ), |
| 611 | e |
| 612 | ); |
| 613 | } |
| 614 | } |
| 615 | |
| 616 | /// Read the system property: keystore.crash_count. |
Eric Biggers | 9f9ab18 | 2023-05-31 21:37:32 +0000 | [diff] [blame] | 617 | pub fn read_keystore_crash_count() -> Result<Option<i32>> { |
| 618 | match rustutils::system_properties::read("keystore.crash_count") { |
| 619 | Ok(Some(count)) => count.parse::<i32>().map(Some).map_err(std::convert::Into::into), |
| 620 | Ok(None) => Ok(None), |
| 621 | Err(e) => Err(e).context(ks_err!("Failed to read crash count property.")), |
| 622 | } |
Hasini Gunasinghe | 365ce37 | 2021-07-02 23:13:11 +0000 | [diff] [blame] | 623 | } |
| 624 | |
Hasini Gunasinghe | 15891e6 | 2021-06-10 16:23:27 +0000 | [diff] [blame] | 625 | /// Enum defining the bit position for each padding mode. Since padding mode can be repeatable, it |
| 626 | /// is represented using a bitmap. |
| 627 | #[allow(non_camel_case_types)] |
| 628 | #[repr(i32)] |
| 629 | enum PaddingModeBitPosition { |
| 630 | ///Bit position in the PaddingMode bitmap for NONE. |
| 631 | NONE_BIT_POSITION = 0, |
| 632 | ///Bit position in the PaddingMode bitmap for RSA_OAEP. |
| 633 | RSA_OAEP_BIT_POS = 1, |
| 634 | ///Bit position in the PaddingMode bitmap for RSA_PSS. |
| 635 | RSA_PSS_BIT_POS = 2, |
| 636 | ///Bit position in the PaddingMode bitmap for RSA_PKCS1_1_5_ENCRYPT. |
| 637 | RSA_PKCS1_1_5_ENCRYPT_BIT_POS = 3, |
| 638 | ///Bit position in the PaddingMode bitmap for RSA_PKCS1_1_5_SIGN. |
| 639 | RSA_PKCS1_1_5_SIGN_BIT_POS = 4, |
| 640 | ///Bit position in the PaddingMode bitmap for RSA_PKCS7. |
| 641 | PKCS7_BIT_POS = 5, |
| 642 | } |
| 643 | |
| 644 | /// Enum defining the bit position for each digest type. Since digest can be repeatable in |
| 645 | /// key parameters, it is represented using a bitmap. |
| 646 | #[allow(non_camel_case_types)] |
| 647 | #[repr(i32)] |
| 648 | enum DigestBitPosition { |
| 649 | ///Bit position in the Digest bitmap for NONE. |
| 650 | NONE_BIT_POSITION = 0, |
| 651 | ///Bit position in the Digest bitmap for MD5. |
| 652 | MD5_BIT_POS = 1, |
| 653 | ///Bit position in the Digest bitmap for SHA1. |
| 654 | SHA_1_BIT_POS = 2, |
| 655 | ///Bit position in the Digest bitmap for SHA_2_224. |
| 656 | SHA_2_224_BIT_POS = 3, |
| 657 | ///Bit position in the Digest bitmap for SHA_2_256. |
| 658 | SHA_2_256_BIT_POS = 4, |
| 659 | ///Bit position in the Digest bitmap for SHA_2_384. |
| 660 | SHA_2_384_BIT_POS = 5, |
| 661 | ///Bit position in the Digest bitmap for SHA_2_512. |
| 662 | SHA_2_512_BIT_POS = 6, |
| 663 | } |
| 664 | |
| 665 | /// Enum defining the bit position for each block mode type. Since block mode can be repeatable in |
| 666 | /// key parameters, it is represented using a bitmap. |
| 667 | #[allow(non_camel_case_types)] |
| 668 | #[repr(i32)] |
| 669 | enum BlockModeBitPosition { |
| 670 | ///Bit position in the BlockMode bitmap for ECB. |
| 671 | ECB_BIT_POS = 1, |
| 672 | ///Bit position in the BlockMode bitmap for CBC. |
| 673 | CBC_BIT_POS = 2, |
| 674 | ///Bit position in the BlockMode bitmap for CTR. |
| 675 | CTR_BIT_POS = 3, |
| 676 | ///Bit position in the BlockMode bitmap for GCM. |
| 677 | GCM_BIT_POS = 4, |
| 678 | } |
| 679 | |
| 680 | /// Enum defining the bit position for each key purpose. Since key purpose can be repeatable in |
| 681 | /// key parameters, it is represented using a bitmap. |
| 682 | #[allow(non_camel_case_types)] |
| 683 | #[repr(i32)] |
| 684 | enum KeyPurposeBitPosition { |
| 685 | ///Bit position in the KeyPurpose bitmap for Encrypt. |
| 686 | ENCRYPT_BIT_POS = 1, |
| 687 | ///Bit position in the KeyPurpose bitmap for Decrypt. |
| 688 | DECRYPT_BIT_POS = 2, |
| 689 | ///Bit position in the KeyPurpose bitmap for Sign. |
| 690 | SIGN_BIT_POS = 3, |
| 691 | ///Bit position in the KeyPurpose bitmap for Verify. |
| 692 | VERIFY_BIT_POS = 4, |
| 693 | ///Bit position in the KeyPurpose bitmap for Wrap Key. |
| 694 | WRAP_KEY_BIT_POS = 5, |
| 695 | ///Bit position in the KeyPurpose bitmap for Agree Key. |
| 696 | AGREE_KEY_BIT_POS = 6, |
| 697 | ///Bit position in the KeyPurpose bitmap for Attest Key. |
| 698 | ATTEST_KEY_BIT_POS = 7, |
| 699 | } |
David Drysdale | 49811e2 | 2023-05-22 18:51:30 +0100 | [diff] [blame] | 700 | |
| 701 | /// The various metrics-related types are not defined in this crate, so the orphan |
| 702 | /// trait rule means that `std::fmt::Debug` cannot be implemented for them. |
| 703 | /// Instead, create our own local trait that generates a debug string for a type. |
| 704 | trait Summary { |
| 705 | fn show(&self) -> String; |
| 706 | } |
| 707 | |
| 708 | /// Implement the [`Summary`] trait for AIDL-derived pseudo-enums, mapping named enum values to |
| 709 | /// specified short names, all padded with spaces to the specified width (to allow improved |
| 710 | /// readability when printed in a group). |
| 711 | macro_rules! impl_summary_enum { |
| 712 | { $enum:ident, $width:literal, $( $variant:ident => $short:literal ),+ $(,)? } => { |
| 713 | impl Summary for $enum{ |
| 714 | fn show(&self) -> String { |
| 715 | match self.0 { |
| 716 | $( |
| 717 | x if x == Self::$variant.0 => format!(concat!("{:", |
| 718 | stringify!($width), |
| 719 | "}"), |
| 720 | $short), |
| 721 | )* |
| 722 | v => format!("Unknown({})", v), |
| 723 | } |
| 724 | } |
| 725 | } |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | impl_summary_enum!(AtomID, 14, |
| 730 | STORAGE_STATS => "STORAGE", |
| 731 | KEYSTORE2_ATOM_WITH_OVERFLOW => "OVERFLOW", |
| 732 | KEY_CREATION_WITH_GENERAL_INFO => "KEYGEN_GENERAL", |
| 733 | KEY_CREATION_WITH_AUTH_INFO => "KEYGEN_AUTH", |
| 734 | KEY_CREATION_WITH_PURPOSE_AND_MODES_INFO => "KEYGEN_MODES", |
| 735 | KEY_OPERATION_WITH_PURPOSE_AND_MODES_INFO => "KEYOP_MODES", |
| 736 | KEY_OPERATION_WITH_GENERAL_INFO => "KEYOP_GENERAL", |
| 737 | RKP_ERROR_STATS => "RKP_ERR", |
| 738 | CRASH_STATS => "CRASH", |
| 739 | ); |
| 740 | |
| 741 | impl_summary_enum!(MetricsStorage, 28, |
| 742 | STORAGE_UNSPECIFIED => "UNSPECIFIED", |
| 743 | KEY_ENTRY => "KEY_ENTRY", |
| 744 | KEY_ENTRY_ID_INDEX => "KEY_ENTRY_ID_IDX" , |
| 745 | KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => "KEY_ENTRY_DOMAIN_NS_IDX" , |
| 746 | BLOB_ENTRY => "BLOB_ENTRY", |
| 747 | BLOB_ENTRY_KEY_ENTRY_ID_INDEX => "BLOB_ENTRY_KEY_ENTRY_ID_IDX" , |
| 748 | KEY_PARAMETER => "KEY_PARAMETER", |
| 749 | KEY_PARAMETER_KEY_ENTRY_ID_INDEX => "KEY_PARAM_KEY_ENTRY_ID_IDX" , |
| 750 | KEY_METADATA => "KEY_METADATA", |
| 751 | KEY_METADATA_KEY_ENTRY_ID_INDEX => "KEY_META_KEY_ENTRY_ID_IDX" , |
| 752 | GRANT => "GRANT", |
| 753 | AUTH_TOKEN => "AUTH_TOKEN", |
| 754 | BLOB_METADATA => "BLOB_METADATA", |
| 755 | BLOB_METADATA_BLOB_ENTRY_ID_INDEX => "BLOB_META_BLOB_ENTRY_ID_IDX" , |
| 756 | METADATA => "METADATA", |
| 757 | DATABASE => "DATABASE", |
| 758 | LEGACY_STORAGE => "LEGACY_STORAGE", |
| 759 | ); |
| 760 | |
| 761 | impl_summary_enum!(MetricsAlgorithm, 4, |
| 762 | ALGORITHM_UNSPECIFIED => "NONE", |
| 763 | RSA => "RSA", |
| 764 | EC => "EC", |
| 765 | AES => "AES", |
| 766 | TRIPLE_DES => "DES", |
| 767 | HMAC => "HMAC", |
| 768 | ); |
| 769 | |
| 770 | impl_summary_enum!(MetricsEcCurve, 5, |
| 771 | EC_CURVE_UNSPECIFIED => "NONE", |
| 772 | P_224 => "P-224", |
| 773 | P_256 => "P-256", |
| 774 | P_384 => "P-384", |
| 775 | P_521 => "P-521", |
| 776 | CURVE_25519 => "25519", |
| 777 | ); |
| 778 | |
| 779 | impl_summary_enum!(MetricsKeyOrigin, 10, |
| 780 | ORIGIN_UNSPECIFIED => "UNSPEC", |
| 781 | GENERATED => "GENERATED", |
| 782 | DERIVED => "DERIVED", |
| 783 | IMPORTED => "IMPORTED", |
| 784 | RESERVED => "RESERVED", |
| 785 | SECURELY_IMPORTED => "SEC-IMPORT", |
| 786 | ); |
| 787 | |
| 788 | impl_summary_enum!(MetricsSecurityLevel, 9, |
| 789 | SECURITY_LEVEL_UNSPECIFIED => "UNSPEC", |
| 790 | SECURITY_LEVEL_SOFTWARE => "SOFTWARE", |
| 791 | SECURITY_LEVEL_TRUSTED_ENVIRONMENT => "TEE", |
| 792 | SECURITY_LEVEL_STRONGBOX => "STRONGBOX", |
| 793 | SECURITY_LEVEL_KEYSTORE => "KEYSTORE", |
| 794 | ); |
| 795 | |
| 796 | // Metrics values for HardwareAuthenticatorType are broken -- the AIDL type is a bitmask |
| 797 | // not an enum, so offseting the enum values by 1 doesn't work. |
| 798 | impl_summary_enum!(MetricsHardwareAuthenticatorType, 6, |
| 799 | AUTH_TYPE_UNSPECIFIED => "UNSPEC", |
| 800 | NONE => "NONE", |
| 801 | PASSWORD => "PASSWD", |
| 802 | FINGERPRINT => "FPRINT", |
| 803 | ANY => "ANY", |
| 804 | ); |
| 805 | |
| 806 | impl_summary_enum!(MetricsPurpose, 7, |
| 807 | KEY_PURPOSE_UNSPECIFIED => "UNSPEC", |
| 808 | ENCRYPT => "ENCRYPT", |
| 809 | DECRYPT => "DECRYPT", |
| 810 | SIGN => "SIGN", |
| 811 | VERIFY => "VERIFY", |
| 812 | WRAP_KEY => "WRAPKEY", |
| 813 | AGREE_KEY => "AGREEKY", |
| 814 | ATTEST_KEY => "ATTESTK", |
| 815 | ); |
| 816 | |
| 817 | impl_summary_enum!(MetricsOutcome, 7, |
| 818 | OUTCOME_UNSPECIFIED => "UNSPEC", |
| 819 | DROPPED => "DROPPED", |
| 820 | SUCCESS => "SUCCESS", |
| 821 | ABORT => "ABORT", |
| 822 | PRUNED => "PRUNED", |
| 823 | ERROR => "ERROR", |
| 824 | ); |
| 825 | |
| 826 | impl_summary_enum!(MetricsRkpError, 6, |
| 827 | RKP_ERROR_UNSPECIFIED => "UNSPEC", |
| 828 | OUT_OF_KEYS => "OOKEYS", |
| 829 | FALL_BACK_DURING_HYBRID => "FALLBK", |
| 830 | ); |
| 831 | |
| 832 | /// Convert an argument into a corresponding format clause. (This is needed because |
| 833 | /// macro expansion text for repeated inputs needs to mention one of the repeated |
| 834 | /// inputs.) |
| 835 | macro_rules! format_clause { |
| 836 | { $ignored:ident } => { "{}" } |
| 837 | } |
| 838 | |
| 839 | /// Generate code to print a string corresponding to a bitmask, where the given |
| 840 | /// enum identifies which bits mean what. If additional bits (not included in |
| 841 | /// the enum variants) are set, include the whole bitmask in the output so no |
| 842 | /// information is lost. |
| 843 | macro_rules! show_enum_bitmask { |
| 844 | { $v:expr, $enum:ident, $( $variant:ident => $short:literal ),+ $(,)? } => { |
| 845 | { |
| 846 | let v: i32 = $v; |
| 847 | let mut displayed_mask = 0i32; |
| 848 | $( |
| 849 | displayed_mask |= 1 << $enum::$variant as i32; |
| 850 | )* |
| 851 | let undisplayed_mask = !displayed_mask; |
| 852 | let undisplayed = v & undisplayed_mask; |
| 853 | let extra = if undisplayed == 0 { |
| 854 | "".to_string() |
| 855 | } else { |
| 856 | format!("(full:{v:#010x})") |
| 857 | }; |
| 858 | format!( |
| 859 | concat!( $( format_clause!($variant), )* "{}"), |
| 860 | $( |
| 861 | if v & 1 << $enum::$variant as i32 != 0 { $short } else { "-" }, |
| 862 | )* |
| 863 | extra |
| 864 | ) |
| 865 | } |
| 866 | } |
| 867 | } |
| 868 | |
| 869 | fn show_purpose(v: i32) -> String { |
| 870 | show_enum_bitmask!(v, KeyPurposeBitPosition, |
| 871 | ATTEST_KEY_BIT_POS => "A", |
| 872 | AGREE_KEY_BIT_POS => "G", |
| 873 | WRAP_KEY_BIT_POS => "W", |
| 874 | VERIFY_BIT_POS => "V", |
| 875 | SIGN_BIT_POS => "S", |
| 876 | DECRYPT_BIT_POS => "D", |
| 877 | ENCRYPT_BIT_POS => "E", |
| 878 | ) |
| 879 | } |
| 880 | |
| 881 | fn show_padding(v: i32) -> String { |
| 882 | show_enum_bitmask!(v, PaddingModeBitPosition, |
| 883 | PKCS7_BIT_POS => "7", |
| 884 | RSA_PKCS1_1_5_SIGN_BIT_POS => "S", |
| 885 | RSA_PKCS1_1_5_ENCRYPT_BIT_POS => "E", |
| 886 | RSA_PSS_BIT_POS => "P", |
| 887 | RSA_OAEP_BIT_POS => "O", |
| 888 | NONE_BIT_POSITION => "N", |
| 889 | ) |
| 890 | } |
| 891 | |
| 892 | fn show_digest(v: i32) -> String { |
| 893 | show_enum_bitmask!(v, DigestBitPosition, |
| 894 | SHA_2_512_BIT_POS => "5", |
| 895 | SHA_2_384_BIT_POS => "3", |
| 896 | SHA_2_256_BIT_POS => "2", |
| 897 | SHA_2_224_BIT_POS => "4", |
| 898 | SHA_1_BIT_POS => "1", |
| 899 | MD5_BIT_POS => "M", |
| 900 | NONE_BIT_POSITION => "N", |
| 901 | ) |
| 902 | } |
| 903 | |
| 904 | fn show_blockmode(v: i32) -> String { |
| 905 | show_enum_bitmask!(v, BlockModeBitPosition, |
| 906 | GCM_BIT_POS => "G", |
| 907 | CTR_BIT_POS => "T", |
| 908 | CBC_BIT_POS => "C", |
| 909 | ECB_BIT_POS => "E", |
| 910 | ) |
| 911 | } |
| 912 | |
| 913 | impl Summary for KeystoreAtomPayload { |
| 914 | fn show(&self) -> String { |
| 915 | match self { |
| 916 | KeystoreAtomPayload::StorageStats(v) => { |
| 917 | format!("{} sz={} unused={}", v.storage_type.show(), v.size, v.unused_size) |
| 918 | } |
| 919 | KeystoreAtomPayload::KeyCreationWithGeneralInfo(v) => { |
| 920 | format!( |
| 921 | "{} ksz={:>4} crv={} {} rc={:4} attest? {}", |
| 922 | v.algorithm.show(), |
| 923 | v.key_size, |
| 924 | v.ec_curve.show(), |
| 925 | v.key_origin.show(), |
| 926 | v.error_code, |
| 927 | if v.attestation_requested { "Y" } else { "N" } |
| 928 | ) |
| 929 | } |
| 930 | KeystoreAtomPayload::KeyCreationWithAuthInfo(v) => { |
| 931 | format!( |
| 932 | "auth={} log(time)={:3} sec={}", |
| 933 | v.user_auth_type.show(), |
| 934 | v.log10_auth_key_timeout_seconds, |
| 935 | v.security_level.show() |
| 936 | ) |
| 937 | } |
| 938 | KeystoreAtomPayload::KeyCreationWithPurposeAndModesInfo(v) => { |
| 939 | format!( |
| 940 | "{} purpose={} padding={} digest={} blockmode={}", |
| 941 | v.algorithm.show(), |
| 942 | show_purpose(v.purpose_bitmap), |
| 943 | show_padding(v.padding_mode_bitmap), |
| 944 | show_digest(v.digest_bitmap), |
| 945 | show_blockmode(v.block_mode_bitmap), |
| 946 | ) |
| 947 | } |
| 948 | KeystoreAtomPayload::KeyOperationWithGeneralInfo(v) => { |
| 949 | format!( |
| 950 | "{} {:>8} upgraded? {} sec={}", |
| 951 | v.outcome.show(), |
| 952 | v.error_code, |
| 953 | if v.key_upgraded { "Y" } else { "N" }, |
| 954 | v.security_level.show() |
| 955 | ) |
| 956 | } |
| 957 | KeystoreAtomPayload::KeyOperationWithPurposeAndModesInfo(v) => { |
| 958 | format!( |
| 959 | "{} padding={} digest={} blockmode={}", |
| 960 | v.purpose.show(), |
| 961 | show_padding(v.padding_mode_bitmap), |
| 962 | show_digest(v.digest_bitmap), |
| 963 | show_blockmode(v.block_mode_bitmap) |
| 964 | ) |
| 965 | } |
| 966 | KeystoreAtomPayload::RkpErrorStats(v) => { |
| 967 | format!("{} sec={}", v.rkpError.show(), v.security_level.show()) |
| 968 | } |
| 969 | KeystoreAtomPayload::CrashStats(v) => { |
| 970 | format!("count={}", v.count_of_crash_events) |
| 971 | } |
| 972 | KeystoreAtomPayload::Keystore2AtomWithOverflow(v) => { |
| 973 | format!("atom={}", v.atom_id.show()) |
| 974 | } |
| 975 | } |
| 976 | } |
| 977 | } |
| 978 | |
| 979 | #[cfg(test)] |
| 980 | mod tests { |
| 981 | use super::*; |
| 982 | |
| 983 | #[test] |
| 984 | fn test_enum_show() { |
| 985 | let algo = MetricsAlgorithm::RSA; |
| 986 | assert_eq!("RSA ", algo.show()); |
| 987 | let algo = MetricsAlgorithm(42); |
| 988 | assert_eq!("Unknown(42)", algo.show()); |
| 989 | } |
| 990 | |
| 991 | #[test] |
| 992 | fn test_enum_bitmask_show() { |
| 993 | let mut modes = 0i32; |
| 994 | compute_block_mode_bitmap(&mut modes, BlockMode::ECB); |
| 995 | compute_block_mode_bitmap(&mut modes, BlockMode::CTR); |
| 996 | |
| 997 | assert_eq!(show_blockmode(modes), "-T-E"); |
| 998 | |
| 999 | // Add some bits not covered by the enum of valid bit positions. |
| 1000 | modes |= 0xa0; |
| 1001 | assert_eq!(show_blockmode(modes), "-T-E(full:0x000000aa)"); |
| 1002 | modes |= 0x300; |
| 1003 | assert_eq!(show_blockmode(modes), "-T-E(full:0x000003aa)"); |
| 1004 | } |
| 1005 | } |