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