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