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