• 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, 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 lazy_static::lazy_static;
50 use rustutils::system_properties::PropertyWatcherError;
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                     EcCurve::CURVE_25519 => MetricsEcCurve::CURVE_25519,
292                     _ => MetricsEcCurve::EC_CURVE_UNSPECIFIED,
293                 }
294             }
295             KsKeyParamValue::AttestationChallenge(_) => {
296                 key_creation_with_general_info.attestation_requested = true;
297             }
298             _ => {}
299         }
300     }
301     if key_creation_with_general_info.algorithm == MetricsAlgorithm::EC {
302         // Do not record key sizes if Algorithm = EC, in order to reduce cardinality.
303         key_creation_with_general_info.key_size = -1;
304     }
305 
306     (
307         KeystoreAtomPayload::KeyCreationWithGeneralInfo(key_creation_with_general_info),
308         KeystoreAtomPayload::KeyCreationWithAuthInfo(key_creation_with_auth_info),
309         KeystoreAtomPayload::KeyCreationWithPurposeAndModesInfo(
310             key_creation_with_purpose_and_modes_info,
311         ),
312     )
313 }
314 
315 /// 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, )316 pub fn log_key_operation_event_stats(
317     sec_level: SecurityLevel,
318     key_purpose: KeyPurpose,
319     op_params: &[KeyParameter],
320     op_outcome: &Outcome,
321     key_upgraded: bool,
322 ) {
323     let (key_operation_with_general_info, key_operation_with_purpose_and_modes_info) =
324         process_key_operation_event_stats(
325             sec_level,
326             key_purpose,
327             op_params,
328             op_outcome,
329             key_upgraded,
330         );
331     METRICS_STORE
332         .insert_atom(AtomID::KEY_OPERATION_WITH_GENERAL_INFO, key_operation_with_general_info);
333     METRICS_STORE.insert_atom(
334         AtomID::KEY_OPERATION_WITH_PURPOSE_AND_MODES_INFO,
335         key_operation_with_purpose_and_modes_info,
336     );
337 }
338 
339 // Process the statistics related to key operations and return the two atom objects related to key
340 // 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)341 fn process_key_operation_event_stats(
342     sec_level: SecurityLevel,
343     key_purpose: KeyPurpose,
344     op_params: &[KeyParameter],
345     op_outcome: &Outcome,
346     key_upgraded: bool,
347 ) -> (KeystoreAtomPayload, KeystoreAtomPayload) {
348     let mut key_operation_with_general_info = KeyOperationWithGeneralInfo {
349         outcome: MetricsOutcome::OUTCOME_UNSPECIFIED,
350         error_code: 1,
351         security_level: MetricsSecurityLevel::SECURITY_LEVEL_UNSPECIFIED,
352         // Default for bool is false (for key_upgraded field).
353         ..Default::default()
354     };
355 
356     let mut key_operation_with_purpose_and_modes_info = KeyOperationWithPurposeAndModesInfo {
357         purpose: MetricsPurpose::KEY_PURPOSE_UNSPECIFIED,
358         // Default for i32 is 0 (for the remaining bitmap fields).
359         ..Default::default()
360     };
361 
362     key_operation_with_general_info.security_level = process_security_level(sec_level);
363 
364     key_operation_with_general_info.key_upgraded = key_upgraded;
365 
366     key_operation_with_purpose_and_modes_info.purpose = match key_purpose {
367         KeyPurpose::ENCRYPT => MetricsPurpose::ENCRYPT,
368         KeyPurpose::DECRYPT => MetricsPurpose::DECRYPT,
369         KeyPurpose::SIGN => MetricsPurpose::SIGN,
370         KeyPurpose::VERIFY => MetricsPurpose::VERIFY,
371         KeyPurpose::WRAP_KEY => MetricsPurpose::WRAP_KEY,
372         KeyPurpose::AGREE_KEY => MetricsPurpose::AGREE_KEY,
373         KeyPurpose::ATTEST_KEY => MetricsPurpose::ATTEST_KEY,
374         _ => MetricsPurpose::KEY_PURPOSE_UNSPECIFIED,
375     };
376 
377     key_operation_with_general_info.outcome = match op_outcome {
378         Outcome::Unknown | Outcome::Dropped => MetricsOutcome::DROPPED,
379         Outcome::Success => MetricsOutcome::SUCCESS,
380         Outcome::Abort => MetricsOutcome::ABORT,
381         Outcome::Pruned => MetricsOutcome::PRUNED,
382         Outcome::ErrorCode(e) => {
383             key_operation_with_general_info.error_code = e.0;
384             MetricsOutcome::ERROR
385         }
386     };
387 
388     for key_param in op_params.iter().map(KsKeyParamValue::from) {
389         match key_param {
390             KsKeyParamValue::PaddingMode(p) => {
391                 compute_padding_mode_bitmap(
392                     &mut key_operation_with_purpose_and_modes_info.padding_mode_bitmap,
393                     p,
394                 );
395             }
396             KsKeyParamValue::Digest(d) => {
397                 compute_digest_bitmap(
398                     &mut key_operation_with_purpose_and_modes_info.digest_bitmap,
399                     d,
400                 );
401             }
402             KsKeyParamValue::BlockMode(b) => {
403                 compute_block_mode_bitmap(
404                     &mut key_operation_with_purpose_and_modes_info.block_mode_bitmap,
405                     b,
406                 );
407             }
408             _ => {}
409         }
410     }
411 
412     (
413         KeystoreAtomPayload::KeyOperationWithGeneralInfo(key_operation_with_general_info),
414         KeystoreAtomPayload::KeyOperationWithPurposeAndModesInfo(
415             key_operation_with_purpose_and_modes_info,
416         ),
417     )
418 }
419 
process_security_level(sec_level: SecurityLevel) -> MetricsSecurityLevel420 fn process_security_level(sec_level: SecurityLevel) -> MetricsSecurityLevel {
421     match sec_level {
422         SecurityLevel::SOFTWARE => MetricsSecurityLevel::SECURITY_LEVEL_SOFTWARE,
423         SecurityLevel::TRUSTED_ENVIRONMENT => {
424             MetricsSecurityLevel::SECURITY_LEVEL_TRUSTED_ENVIRONMENT
425         }
426         SecurityLevel::STRONGBOX => MetricsSecurityLevel::SECURITY_LEVEL_STRONGBOX,
427         SecurityLevel::KEYSTORE => MetricsSecurityLevel::SECURITY_LEVEL_KEYSTORE,
428         _ => MetricsSecurityLevel::SECURITY_LEVEL_UNSPECIFIED,
429     }
430 }
431 
compute_padding_mode_bitmap(padding_mode_bitmap: &mut i32, padding_mode: PaddingMode)432 fn compute_padding_mode_bitmap(padding_mode_bitmap: &mut i32, padding_mode: PaddingMode) {
433     match padding_mode {
434         PaddingMode::NONE => {
435             *padding_mode_bitmap |= 1 << PaddingModeBitPosition::NONE_BIT_POSITION as i32;
436         }
437         PaddingMode::RSA_OAEP => {
438             *padding_mode_bitmap |= 1 << PaddingModeBitPosition::RSA_OAEP_BIT_POS as i32;
439         }
440         PaddingMode::RSA_PSS => {
441             *padding_mode_bitmap |= 1 << PaddingModeBitPosition::RSA_PSS_BIT_POS as i32;
442         }
443         PaddingMode::RSA_PKCS1_1_5_ENCRYPT => {
444             *padding_mode_bitmap |=
445                 1 << PaddingModeBitPosition::RSA_PKCS1_1_5_ENCRYPT_BIT_POS as i32;
446         }
447         PaddingMode::RSA_PKCS1_1_5_SIGN => {
448             *padding_mode_bitmap |= 1 << PaddingModeBitPosition::RSA_PKCS1_1_5_SIGN_BIT_POS as i32;
449         }
450         PaddingMode::PKCS7 => {
451             *padding_mode_bitmap |= 1 << PaddingModeBitPosition::PKCS7_BIT_POS as i32;
452         }
453         _ => {}
454     }
455 }
456 
compute_digest_bitmap(digest_bitmap: &mut i32, digest: Digest)457 fn compute_digest_bitmap(digest_bitmap: &mut i32, digest: Digest) {
458     match digest {
459         Digest::NONE => {
460             *digest_bitmap |= 1 << DigestBitPosition::NONE_BIT_POSITION as i32;
461         }
462         Digest::MD5 => {
463             *digest_bitmap |= 1 << DigestBitPosition::MD5_BIT_POS as i32;
464         }
465         Digest::SHA1 => {
466             *digest_bitmap |= 1 << DigestBitPosition::SHA_1_BIT_POS as i32;
467         }
468         Digest::SHA_2_224 => {
469             *digest_bitmap |= 1 << DigestBitPosition::SHA_2_224_BIT_POS as i32;
470         }
471         Digest::SHA_2_256 => {
472             *digest_bitmap |= 1 << DigestBitPosition::SHA_2_256_BIT_POS as i32;
473         }
474         Digest::SHA_2_384 => {
475             *digest_bitmap |= 1 << DigestBitPosition::SHA_2_384_BIT_POS as i32;
476         }
477         Digest::SHA_2_512 => {
478             *digest_bitmap |= 1 << DigestBitPosition::SHA_2_512_BIT_POS as i32;
479         }
480         _ => {}
481     }
482 }
483 
compute_block_mode_bitmap(block_mode_bitmap: &mut i32, block_mode: BlockMode)484 fn compute_block_mode_bitmap(block_mode_bitmap: &mut i32, block_mode: BlockMode) {
485     match block_mode {
486         BlockMode::ECB => {
487             *block_mode_bitmap |= 1 << BlockModeBitPosition::ECB_BIT_POS as i32;
488         }
489         BlockMode::CBC => {
490             *block_mode_bitmap |= 1 << BlockModeBitPosition::CBC_BIT_POS as i32;
491         }
492         BlockMode::CTR => {
493             *block_mode_bitmap |= 1 << BlockModeBitPosition::CTR_BIT_POS as i32;
494         }
495         BlockMode::GCM => {
496             *block_mode_bitmap |= 1 << BlockModeBitPosition::GCM_BIT_POS as i32;
497         }
498         _ => {}
499     }
500 }
501 
compute_purpose_bitmap(purpose_bitmap: &mut i32, purpose: KeyPurpose)502 fn compute_purpose_bitmap(purpose_bitmap: &mut i32, purpose: KeyPurpose) {
503     match purpose {
504         KeyPurpose::ENCRYPT => {
505             *purpose_bitmap |= 1 << KeyPurposeBitPosition::ENCRYPT_BIT_POS as i32;
506         }
507         KeyPurpose::DECRYPT => {
508             *purpose_bitmap |= 1 << KeyPurposeBitPosition::DECRYPT_BIT_POS as i32;
509         }
510         KeyPurpose::SIGN => {
511             *purpose_bitmap |= 1 << KeyPurposeBitPosition::SIGN_BIT_POS as i32;
512         }
513         KeyPurpose::VERIFY => {
514             *purpose_bitmap |= 1 << KeyPurposeBitPosition::VERIFY_BIT_POS as i32;
515         }
516         KeyPurpose::WRAP_KEY => {
517             *purpose_bitmap |= 1 << KeyPurposeBitPosition::WRAP_KEY_BIT_POS as i32;
518         }
519         KeyPurpose::AGREE_KEY => {
520             *purpose_bitmap |= 1 << KeyPurposeBitPosition::AGREE_KEY_BIT_POS as i32;
521         }
522         KeyPurpose::ATTEST_KEY => {
523             *purpose_bitmap |= 1 << KeyPurposeBitPosition::ATTEST_KEY_BIT_POS as i32;
524         }
525         _ => {}
526     }
527 }
528 
pull_storage_stats() -> Result<Vec<KeystoreAtom>>529 fn pull_storage_stats() -> Result<Vec<KeystoreAtom>> {
530     let mut atom_vec: Vec<KeystoreAtom> = Vec::new();
531     let mut append = |stat| {
532         match stat {
533             Ok(s) => atom_vec.push(KeystoreAtom {
534                 payload: KeystoreAtomPayload::StorageStats(s),
535                 ..Default::default()
536             }),
537             Err(error) => {
538                 log::error!("pull_metrics_callback: Error getting storage stat: {}", error)
539             }
540         };
541     };
542     DB.with(|db| {
543         let mut db = db.borrow_mut();
544         append(db.get_storage_stat(MetricsStorage::DATABASE));
545         append(db.get_storage_stat(MetricsStorage::KEY_ENTRY));
546         append(db.get_storage_stat(MetricsStorage::KEY_ENTRY_ID_INDEX));
547         append(db.get_storage_stat(MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX));
548         append(db.get_storage_stat(MetricsStorage::BLOB_ENTRY));
549         append(db.get_storage_stat(MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX));
550         append(db.get_storage_stat(MetricsStorage::KEY_PARAMETER));
551         append(db.get_storage_stat(MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX));
552         append(db.get_storage_stat(MetricsStorage::KEY_METADATA));
553         append(db.get_storage_stat(MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX));
554         append(db.get_storage_stat(MetricsStorage::GRANT));
555         append(db.get_storage_stat(MetricsStorage::AUTH_TOKEN));
556         append(db.get_storage_stat(MetricsStorage::BLOB_METADATA));
557         append(db.get_storage_stat(MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX));
558     });
559     Ok(atom_vec)
560 }
561 
pull_attestation_pool_stats() -> Result<Vec<KeystoreAtom>>562 fn pull_attestation_pool_stats() -> Result<Vec<KeystoreAtom>> {
563     let mut atoms = Vec::<KeystoreAtom>::new();
564     for sec_level in &[SecurityLevel::TRUSTED_ENVIRONMENT, SecurityLevel::STRONGBOX] {
565         // set the expired_by date to be three days from now
566         let expired_by = SystemTime::now()
567             .checked_add(Duration::from_secs(60 * 60 * 24 * 3))
568             .ok_or(Error::Rc(ResponseCode::SYSTEM_ERROR))
569             .context("In pull_attestation_pool_stats: Failed to compute expired by system time.")?
570             .duration_since(UNIX_EPOCH)
571             .context("In pull_attestation_pool_stats: Failed to compute expired by duration.")?
572             .as_millis() as i64;
573 
574         let result = get_pool_status(expired_by, *sec_level);
575 
576         if let Ok(pool_status) = result {
577             let rkp_pool_stats = RkpPoolStats {
578                 security_level: process_security_level(*sec_level),
579                 expiring: pool_status.expiring,
580                 unassigned: pool_status.unassigned,
581                 attested: pool_status.attested,
582                 total: pool_status.total,
583             };
584             atoms.push(KeystoreAtom {
585                 payload: KeystoreAtomPayload::RkpPoolStats(rkp_pool_stats),
586                 ..Default::default()
587             });
588         } else {
589             log::error!(
590                 concat!(
591                     "In pull_attestation_pool_stats: Failed to retrieve pool status",
592                     " for security level: {:?}"
593                 ),
594                 sec_level
595             );
596         }
597     }
598     Ok(atoms)
599 }
600 
601 /// Log error events related to Remote Key Provisioning (RKP).
log_rkp_error_stats(rkp_error: MetricsRkpError, sec_level: &SecurityLevel)602 pub fn log_rkp_error_stats(rkp_error: MetricsRkpError, sec_level: &SecurityLevel) {
603     let rkp_error_stats = KeystoreAtomPayload::RkpErrorStats(
604         RkpErrorStats { rkpError: rkp_error, security_level: process_security_level(*sec_level) });
605     METRICS_STORE.insert_atom(AtomID::RKP_ERROR_STATS, rkp_error_stats);
606 }
607 
608 /// This function tries to read and update the system property: keystore.crash_count.
609 /// If the property is absent, it sets the property with value 0. If the property is present, it
610 /// increments the value. This helps tracking keystore crashes internally.
update_keystore_crash_sysprop()611 pub fn update_keystore_crash_sysprop() {
612     let crash_count = read_keystore_crash_count();
613     let new_count = match crash_count {
614         Ok(count) => count + 1,
615         Err(error) => {
616             // If the property is absent, this is the first start up during the boot.
617             // Proceed to write the system property with value 0. Otherwise, log and return.
618             if !matches!(
619                 error.root_cause().downcast_ref::<PropertyWatcherError>(),
620                 Some(PropertyWatcherError::SystemPropertyAbsent)
621             ) {
622                 log::warn!(
623                     concat!(
624                         "In update_keystore_crash_sysprop: ",
625                         "Failed to read the existing system property due to: {:?}.",
626                         "Therefore, keystore crashes will not be logged."
627                     ),
628                     error
629                 );
630                 return;
631             }
632             0
633         }
634     };
635 
636     if let Err(e) =
637         rustutils::system_properties::write(KEYSTORE_CRASH_COUNT_PROPERTY, &new_count.to_string())
638     {
639         log::error!(
640             concat!(
641                 "In update_keystore_crash_sysprop:: ",
642                 "Failed to write the system property due to error: {:?}"
643             ),
644             e
645         );
646     }
647 }
648 
649 /// Read the system property: keystore.crash_count.
read_keystore_crash_count() -> Result<i32>650 pub fn read_keystore_crash_count() -> Result<i32> {
651     rustutils::system_properties::read("keystore.crash_count")
652         .context("In read_keystore_crash_count: Failed read property.")?
653         .context("In read_keystore_crash_count: Property not set.")?
654         .parse::<i32>()
655         .map_err(std::convert::Into::into)
656 }
657 
658 /// Enum defining the bit position for each padding mode. Since padding mode can be repeatable, it
659 /// is represented using a bitmap.
660 #[allow(non_camel_case_types)]
661 #[repr(i32)]
662 enum PaddingModeBitPosition {
663     ///Bit position in the PaddingMode bitmap for NONE.
664     NONE_BIT_POSITION = 0,
665     ///Bit position in the PaddingMode bitmap for RSA_OAEP.
666     RSA_OAEP_BIT_POS = 1,
667     ///Bit position in the PaddingMode bitmap for RSA_PSS.
668     RSA_PSS_BIT_POS = 2,
669     ///Bit position in the PaddingMode bitmap for RSA_PKCS1_1_5_ENCRYPT.
670     RSA_PKCS1_1_5_ENCRYPT_BIT_POS = 3,
671     ///Bit position in the PaddingMode bitmap for RSA_PKCS1_1_5_SIGN.
672     RSA_PKCS1_1_5_SIGN_BIT_POS = 4,
673     ///Bit position in the PaddingMode bitmap for RSA_PKCS7.
674     PKCS7_BIT_POS = 5,
675 }
676 
677 /// Enum defining the bit position for each digest type. Since digest can be repeatable in
678 /// key parameters, it is represented using a bitmap.
679 #[allow(non_camel_case_types)]
680 #[repr(i32)]
681 enum DigestBitPosition {
682     ///Bit position in the Digest bitmap for NONE.
683     NONE_BIT_POSITION = 0,
684     ///Bit position in the Digest bitmap for MD5.
685     MD5_BIT_POS = 1,
686     ///Bit position in the Digest bitmap for SHA1.
687     SHA_1_BIT_POS = 2,
688     ///Bit position in the Digest bitmap for SHA_2_224.
689     SHA_2_224_BIT_POS = 3,
690     ///Bit position in the Digest bitmap for SHA_2_256.
691     SHA_2_256_BIT_POS = 4,
692     ///Bit position in the Digest bitmap for SHA_2_384.
693     SHA_2_384_BIT_POS = 5,
694     ///Bit position in the Digest bitmap for SHA_2_512.
695     SHA_2_512_BIT_POS = 6,
696 }
697 
698 /// Enum defining the bit position for each block mode type. Since block mode can be repeatable in
699 /// key parameters, it is represented using a bitmap.
700 #[allow(non_camel_case_types)]
701 #[repr(i32)]
702 enum BlockModeBitPosition {
703     ///Bit position in the BlockMode bitmap for ECB.
704     ECB_BIT_POS = 1,
705     ///Bit position in the BlockMode bitmap for CBC.
706     CBC_BIT_POS = 2,
707     ///Bit position in the BlockMode bitmap for CTR.
708     CTR_BIT_POS = 3,
709     ///Bit position in the BlockMode bitmap for GCM.
710     GCM_BIT_POS = 4,
711 }
712 
713 /// Enum defining the bit position for each key purpose. Since key purpose can be repeatable in
714 /// key parameters, it is represented using a bitmap.
715 #[allow(non_camel_case_types)]
716 #[repr(i32)]
717 enum KeyPurposeBitPosition {
718     ///Bit position in the KeyPurpose bitmap for Encrypt.
719     ENCRYPT_BIT_POS = 1,
720     ///Bit position in the KeyPurpose bitmap for Decrypt.
721     DECRYPT_BIT_POS = 2,
722     ///Bit position in the KeyPurpose bitmap for Sign.
723     SIGN_BIT_POS = 3,
724     ///Bit position in the KeyPurpose bitmap for Verify.
725     VERIFY_BIT_POS = 4,
726     ///Bit position in the KeyPurpose bitmap for Wrap Key.
727     WRAP_KEY_BIT_POS = 5,
728     ///Bit position in the KeyPurpose bitmap for Agree Key.
729     AGREE_KEY_BIT_POS = 6,
730     ///Bit position in the KeyPurpose bitmap for Attest Key.
731     ATTEST_KEY_BIT_POS = 7,
732 }
733