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