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