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