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