blob: 32fe353eda3334555439315d5dfd9b3d31df5f23 [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::{
32 Algorithm::Algorithm as MetricsAlgorithm, AtomID::AtomID, EcCurve::EcCurve as MetricsEcCurve,
33 HardwareAuthenticatorType::HardwareAuthenticatorType as MetricsHardwareAuthenticatorType,
34 KeyCreationWithAuthInfo::KeyCreationWithAuthInfo,
35 KeyCreationWithGeneralInfo::KeyCreationWithGeneralInfo,
36 KeyCreationWithPurposeAndModesInfo::KeyCreationWithPurposeAndModesInfo,
37 KeyOperationWithGeneralInfo::KeyOperationWithGeneralInfo,
38 KeyOperationWithPurposeAndModesInfo::KeyOperationWithPurposeAndModesInfo,
39 KeyOrigin::KeyOrigin as MetricsKeyOrigin, Keystore2AtomWithOverflow::Keystore2AtomWithOverflow,
40 KeystoreAtom::KeystoreAtom, KeystoreAtomPayload::KeystoreAtomPayload,
41 Outcome::Outcome as MetricsOutcome, Purpose::Purpose as MetricsPurpose,
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +000042 RkpError::RkpError as MetricsRkpError, RkpErrorStats::RkpErrorStats,
43 RkpPoolStats::RkpPoolStats, SecurityLevel::SecurityLevel as MetricsSecurityLevel,
44 Storage::Storage as MetricsStorage,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +000045};
46use anyhow::Result;
47use lazy_static::lazy_static;
48use std::collections::HashMap;
49use std::sync::Mutex;
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +000050use std::time::{Duration, SystemTime, UNIX_EPOCH};
Hasini Gunasinghe15891e62021-06-10 16:23:27 +000051
52lazy_static! {
53 /// Singleton for MetricsStore.
54 pub static ref METRICS_STORE: MetricsStore = Default::default();
55}
56
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 Gunasinghe8af67ea2021-06-30 17:09:01 +000090 // Process and return RKP pool stats.
91 if AtomID::RKP_POOL_STATS == atom_id {
92 return pull_attestation_pool_stats();
93 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +000094
95 // It is safe to call unwrap here since the lock can not be poisoned based on its usage
96 // in this module and the lock is not acquired in the same thread before.
97 let metrics_store_guard = self.metrics_store.lock().unwrap();
98 metrics_store_guard.get(&atom_id).map_or(Ok(Vec::<KeystoreAtom>::new()), |atom_count_map| {
99 Ok(atom_count_map
100 .iter()
101 .map(|(atom, count)| KeystoreAtom { payload: atom.clone(), count: *count })
102 .collect())
103 })
104 }
105
106 /// Insert an atom object to the metrics_store indexed by the atom ID.
107 fn insert_atom(&self, atom_id: AtomID, atom: KeystoreAtomPayload) {
108 // It is ok to unwrap here since the mutex cannot be poisoned according to the way it is
109 // used in this module. And the lock is not acquired by this thread before.
110 let mut metrics_store_guard = self.metrics_store.lock().unwrap();
111 let atom_count_map = metrics_store_guard.entry(atom_id).or_insert_with(HashMap::new);
112 if atom_count_map.len() < MetricsStore::SINGLE_ATOM_STORE_MAX_SIZE {
113 let atom_count = atom_count_map.entry(atom).or_insert(0);
114 *atom_count += 1;
115 } else {
116 // Insert an overflow atom
117 let overflow_atom_count_map = metrics_store_guard
118 .entry(AtomID::KEYSTORE2_ATOM_WITH_OVERFLOW)
119 .or_insert_with(HashMap::new);
120
121 if overflow_atom_count_map.len() < MetricsStore::SINGLE_ATOM_STORE_MAX_SIZE {
122 let overflow_atom = Keystore2AtomWithOverflow { atom_id };
123 let atom_count = overflow_atom_count_map
124 .entry(KeystoreAtomPayload::Keystore2AtomWithOverflow(overflow_atom))
125 .or_insert(0);
126 *atom_count += 1;
127 } else {
128 // This is a rare case, if at all.
129 log::error!("In insert_atom: Maximum storage limit reached for overflow atom.")
130 }
131 }
132 }
133}
134
135/// Log key creation events to be sent to statsd.
136pub fn log_key_creation_event_stats<U>(
137 sec_level: SecurityLevel,
138 key_params: &[KeyParameter],
139 result: &Result<U>,
140) {
141 let (
142 key_creation_with_general_info,
143 key_creation_with_auth_info,
144 key_creation_with_purpose_and_modes_info,
145 ) = process_key_creation_event_stats(sec_level, key_params, result);
146
147 METRICS_STORE
148 .insert_atom(AtomID::KEY_CREATION_WITH_GENERAL_INFO, key_creation_with_general_info);
149 METRICS_STORE.insert_atom(AtomID::KEY_CREATION_WITH_AUTH_INFO, key_creation_with_auth_info);
150 METRICS_STORE.insert_atom(
151 AtomID::KEY_CREATION_WITH_PURPOSE_AND_MODES_INFO,
152 key_creation_with_purpose_and_modes_info,
153 );
154}
155
156// Process the statistics related to key creations and return the three atom objects related to key
157// creations: i) KeyCreationWithGeneralInfo ii) KeyCreationWithAuthInfo
158// iii) KeyCreationWithPurposeAndModesInfo
159fn process_key_creation_event_stats<U>(
160 sec_level: SecurityLevel,
161 key_params: &[KeyParameter],
162 result: &Result<U>,
163) -> (KeystoreAtomPayload, KeystoreAtomPayload, KeystoreAtomPayload) {
164 // In the default atom objects, fields represented by bitmaps and i32 fields
165 // will take 0, except error_code which defaults to 1 indicating NO_ERROR and key_size,
166 // and auth_time_out which defaults to -1.
167 // The boolean fields are set to false by default.
168 // Some keymint enums do have 0 as an enum variant value. In such cases, the corresponding
169 // enum variant value in atoms.proto is incremented by 1, in order to have 0 as the reserved
170 // value for unspecified fields.
171 let mut key_creation_with_general_info = KeyCreationWithGeneralInfo {
172 algorithm: MetricsAlgorithm::ALGORITHM_UNSPECIFIED,
173 key_size: -1,
174 ec_curve: MetricsEcCurve::EC_CURVE_UNSPECIFIED,
175 key_origin: MetricsKeyOrigin::ORIGIN_UNSPECIFIED,
176 error_code: 1,
177 // Default for bool is false (for attestation_requested field).
178 ..Default::default()
179 };
180
181 let mut key_creation_with_auth_info = KeyCreationWithAuthInfo {
182 user_auth_type: MetricsHardwareAuthenticatorType::AUTH_TYPE_UNSPECIFIED,
183 log10_auth_key_timeout_seconds: -1,
184 security_level: MetricsSecurityLevel::SECURITY_LEVEL_UNSPECIFIED,
185 };
186
187 let mut key_creation_with_purpose_and_modes_info = KeyCreationWithPurposeAndModesInfo {
188 algorithm: MetricsAlgorithm::ALGORITHM_UNSPECIFIED,
189 // Default for i32 is 0 (for the remaining bitmap fields).
190 ..Default::default()
191 };
192
193 if let Err(ref e) = result {
194 key_creation_with_general_info.error_code = get_error_code(e);
195 }
196
197 key_creation_with_auth_info.security_level = process_security_level(sec_level);
198
199 for key_param in key_params.iter().map(KsKeyParamValue::from) {
200 match key_param {
201 KsKeyParamValue::Algorithm(a) => {
202 let algorithm = match a {
203 Algorithm::RSA => MetricsAlgorithm::RSA,
204 Algorithm::EC => MetricsAlgorithm::EC,
205 Algorithm::AES => MetricsAlgorithm::AES,
206 Algorithm::TRIPLE_DES => MetricsAlgorithm::TRIPLE_DES,
207 Algorithm::HMAC => MetricsAlgorithm::HMAC,
208 _ => MetricsAlgorithm::ALGORITHM_UNSPECIFIED,
209 };
210 key_creation_with_general_info.algorithm = algorithm;
211 key_creation_with_purpose_and_modes_info.algorithm = algorithm;
212 }
213 KsKeyParamValue::KeySize(s) => {
214 key_creation_with_general_info.key_size = s;
215 }
216 KsKeyParamValue::KeyOrigin(o) => {
217 key_creation_with_general_info.key_origin = match o {
218 KeyOrigin::GENERATED => MetricsKeyOrigin::GENERATED,
219 KeyOrigin::DERIVED => MetricsKeyOrigin::DERIVED,
220 KeyOrigin::IMPORTED => MetricsKeyOrigin::IMPORTED,
221 KeyOrigin::RESERVED => MetricsKeyOrigin::RESERVED,
222 KeyOrigin::SECURELY_IMPORTED => MetricsKeyOrigin::SECURELY_IMPORTED,
223 _ => MetricsKeyOrigin::ORIGIN_UNSPECIFIED,
224 }
225 }
226 KsKeyParamValue::HardwareAuthenticatorType(a) => {
227 key_creation_with_auth_info.user_auth_type = match a {
228 HardwareAuthenticatorType::NONE => MetricsHardwareAuthenticatorType::NONE,
229 HardwareAuthenticatorType::PASSWORD => {
230 MetricsHardwareAuthenticatorType::PASSWORD
231 }
232 HardwareAuthenticatorType::FINGERPRINT => {
233 MetricsHardwareAuthenticatorType::FINGERPRINT
234 }
235 HardwareAuthenticatorType::ANY => MetricsHardwareAuthenticatorType::ANY,
236 _ => MetricsHardwareAuthenticatorType::AUTH_TYPE_UNSPECIFIED,
237 }
238 }
239 KsKeyParamValue::AuthTimeout(t) => {
240 key_creation_with_auth_info.log10_auth_key_timeout_seconds =
241 f32::log10(t as f32) as i32;
242 }
243 KsKeyParamValue::PaddingMode(p) => {
244 compute_padding_mode_bitmap(
245 &mut key_creation_with_purpose_and_modes_info.padding_mode_bitmap,
246 p,
247 );
248 }
249 KsKeyParamValue::Digest(d) => {
250 // key_creation_with_purpose_and_modes_info.digest_bitmap =
251 compute_digest_bitmap(
252 &mut key_creation_with_purpose_and_modes_info.digest_bitmap,
253 d,
254 );
255 }
256 KsKeyParamValue::BlockMode(b) => {
257 compute_block_mode_bitmap(
258 &mut key_creation_with_purpose_and_modes_info.block_mode_bitmap,
259 b,
260 );
261 }
262 KsKeyParamValue::KeyPurpose(k) => {
263 compute_purpose_bitmap(
264 &mut key_creation_with_purpose_and_modes_info.purpose_bitmap,
265 k,
266 );
267 }
268 KsKeyParamValue::EcCurve(e) => {
269 key_creation_with_general_info.ec_curve = match e {
270 EcCurve::P_224 => MetricsEcCurve::P_224,
271 EcCurve::P_256 => MetricsEcCurve::P_256,
272 EcCurve::P_384 => MetricsEcCurve::P_384,
273 EcCurve::P_521 => MetricsEcCurve::P_521,
274 _ => MetricsEcCurve::EC_CURVE_UNSPECIFIED,
275 }
276 }
277 KsKeyParamValue::AttestationChallenge(_) => {
278 key_creation_with_general_info.attestation_requested = true;
279 }
280 _ => {}
281 }
282 }
283 if key_creation_with_general_info.algorithm == MetricsAlgorithm::EC {
284 // Do not record key sizes if Algorithm = EC, in order to reduce cardinality.
285 key_creation_with_general_info.key_size = -1;
286 }
287
288 (
289 KeystoreAtomPayload::KeyCreationWithGeneralInfo(key_creation_with_general_info),
290 KeystoreAtomPayload::KeyCreationWithAuthInfo(key_creation_with_auth_info),
291 KeystoreAtomPayload::KeyCreationWithPurposeAndModesInfo(
292 key_creation_with_purpose_and_modes_info,
293 ),
294 )
295}
296
297/// Log key operation events to be sent to statsd.
298pub fn log_key_operation_event_stats(
299 sec_level: SecurityLevel,
300 key_purpose: KeyPurpose,
301 op_params: &[KeyParameter],
302 op_outcome: &Outcome,
303 key_upgraded: bool,
304) {
305 let (key_operation_with_general_info, key_operation_with_purpose_and_modes_info) =
306 process_key_operation_event_stats(
307 sec_level,
308 key_purpose,
309 op_params,
310 op_outcome,
311 key_upgraded,
312 );
313 METRICS_STORE
314 .insert_atom(AtomID::KEY_OPERATION_WITH_GENERAL_INFO, key_operation_with_general_info);
315 METRICS_STORE.insert_atom(
316 AtomID::KEY_OPERATION_WITH_PURPOSE_AND_MODES_INFO,
317 key_operation_with_purpose_and_modes_info,
318 );
319}
320
321// Process the statistics related to key operations and return the two atom objects related to key
322// operations: i) KeyOperationWithGeneralInfo ii) KeyOperationWithPurposeAndModesInfo
323fn process_key_operation_event_stats(
324 sec_level: SecurityLevel,
325 key_purpose: KeyPurpose,
326 op_params: &[KeyParameter],
327 op_outcome: &Outcome,
328 key_upgraded: bool,
329) -> (KeystoreAtomPayload, KeystoreAtomPayload) {
330 let mut key_operation_with_general_info = KeyOperationWithGeneralInfo {
331 outcome: MetricsOutcome::OUTCOME_UNSPECIFIED,
332 error_code: 1,
333 security_level: MetricsSecurityLevel::SECURITY_LEVEL_UNSPECIFIED,
334 // Default for bool is false (for key_upgraded field).
335 ..Default::default()
336 };
337
338 let mut key_operation_with_purpose_and_modes_info = KeyOperationWithPurposeAndModesInfo {
339 purpose: MetricsPurpose::KEY_PURPOSE_UNSPECIFIED,
340 // Default for i32 is 0 (for the remaining bitmap fields).
341 ..Default::default()
342 };
343
344 key_operation_with_general_info.security_level = process_security_level(sec_level);
345
346 key_operation_with_general_info.key_upgraded = key_upgraded;
347
348 key_operation_with_purpose_and_modes_info.purpose = match key_purpose {
349 KeyPurpose::ENCRYPT => MetricsPurpose::ENCRYPT,
350 KeyPurpose::DECRYPT => MetricsPurpose::DECRYPT,
351 KeyPurpose::SIGN => MetricsPurpose::SIGN,
352 KeyPurpose::VERIFY => MetricsPurpose::VERIFY,
353 KeyPurpose::WRAP_KEY => MetricsPurpose::WRAP_KEY,
354 KeyPurpose::AGREE_KEY => MetricsPurpose::AGREE_KEY,
355 KeyPurpose::ATTEST_KEY => MetricsPurpose::ATTEST_KEY,
356 _ => MetricsPurpose::KEY_PURPOSE_UNSPECIFIED,
357 };
358
359 key_operation_with_general_info.outcome = match op_outcome {
360 Outcome::Unknown | Outcome::Dropped => MetricsOutcome::DROPPED,
361 Outcome::Success => MetricsOutcome::SUCCESS,
362 Outcome::Abort => MetricsOutcome::ABORT,
363 Outcome::Pruned => MetricsOutcome::PRUNED,
364 Outcome::ErrorCode(e) => {
365 key_operation_with_general_info.error_code = e.0;
366 MetricsOutcome::ERROR
367 }
368 };
369
370 for key_param in op_params.iter().map(KsKeyParamValue::from) {
371 match key_param {
372 KsKeyParamValue::PaddingMode(p) => {
373 compute_padding_mode_bitmap(
374 &mut key_operation_with_purpose_and_modes_info.padding_mode_bitmap,
375 p,
376 );
377 }
378 KsKeyParamValue::Digest(d) => {
379 compute_digest_bitmap(
380 &mut key_operation_with_purpose_and_modes_info.digest_bitmap,
381 d,
382 );
383 }
384 KsKeyParamValue::BlockMode(b) => {
385 compute_block_mode_bitmap(
386 &mut key_operation_with_purpose_and_modes_info.block_mode_bitmap,
387 b,
388 );
389 }
390 _ => {}
391 }
392 }
393
394 (
395 KeystoreAtomPayload::KeyOperationWithGeneralInfo(key_operation_with_general_info),
396 KeystoreAtomPayload::KeyOperationWithPurposeAndModesInfo(
397 key_operation_with_purpose_and_modes_info,
398 ),
399 )
400}
401
402fn process_security_level(sec_level: SecurityLevel) -> MetricsSecurityLevel {
403 match sec_level {
404 SecurityLevel::SOFTWARE => MetricsSecurityLevel::SECURITY_LEVEL_SOFTWARE,
405 SecurityLevel::TRUSTED_ENVIRONMENT => {
406 MetricsSecurityLevel::SECURITY_LEVEL_TRUSTED_ENVIRONMENT
407 }
408 SecurityLevel::STRONGBOX => MetricsSecurityLevel::SECURITY_LEVEL_STRONGBOX,
409 SecurityLevel::KEYSTORE => MetricsSecurityLevel::SECURITY_LEVEL_KEYSTORE,
410 _ => MetricsSecurityLevel::SECURITY_LEVEL_UNSPECIFIED,
411 }
412}
413
414fn compute_padding_mode_bitmap(padding_mode_bitmap: &mut i32, padding_mode: PaddingMode) {
415 match padding_mode {
416 PaddingMode::NONE => {
417 *padding_mode_bitmap |= 1 << PaddingModeBitPosition::NONE_BIT_POSITION as i32;
418 }
419 PaddingMode::RSA_OAEP => {
420 *padding_mode_bitmap |= 1 << PaddingModeBitPosition::RSA_OAEP_BIT_POS as i32;
421 }
422 PaddingMode::RSA_PSS => {
423 *padding_mode_bitmap |= 1 << PaddingModeBitPosition::RSA_PSS_BIT_POS as i32;
424 }
425 PaddingMode::RSA_PKCS1_1_5_ENCRYPT => {
426 *padding_mode_bitmap |=
427 1 << PaddingModeBitPosition::RSA_PKCS1_1_5_ENCRYPT_BIT_POS as i32;
428 }
429 PaddingMode::RSA_PKCS1_1_5_SIGN => {
430 *padding_mode_bitmap |= 1 << PaddingModeBitPosition::RSA_PKCS1_1_5_SIGN_BIT_POS as i32;
431 }
432 PaddingMode::PKCS7 => {
433 *padding_mode_bitmap |= 1 << PaddingModeBitPosition::PKCS7_BIT_POS as i32;
434 }
435 _ => {}
436 }
437}
438
439fn compute_digest_bitmap(digest_bitmap: &mut i32, digest: Digest) {
440 match digest {
441 Digest::NONE => {
442 *digest_bitmap |= 1 << DigestBitPosition::NONE_BIT_POSITION as i32;
443 }
444 Digest::MD5 => {
445 *digest_bitmap |= 1 << DigestBitPosition::MD5_BIT_POS as i32;
446 }
447 Digest::SHA1 => {
448 *digest_bitmap |= 1 << DigestBitPosition::SHA_1_BIT_POS as i32;
449 }
450 Digest::SHA_2_224 => {
451 *digest_bitmap |= 1 << DigestBitPosition::SHA_2_224_BIT_POS as i32;
452 }
453 Digest::SHA_2_256 => {
454 *digest_bitmap |= 1 << DigestBitPosition::SHA_2_256_BIT_POS as i32;
455 }
456 Digest::SHA_2_384 => {
457 *digest_bitmap |= 1 << DigestBitPosition::SHA_2_384_BIT_POS as i32;
458 }
459 Digest::SHA_2_512 => {
460 *digest_bitmap |= 1 << DigestBitPosition::SHA_2_512_BIT_POS as i32;
461 }
462 _ => {}
463 }
464}
465
466fn compute_block_mode_bitmap(block_mode_bitmap: &mut i32, block_mode: BlockMode) {
467 match block_mode {
468 BlockMode::ECB => {
469 *block_mode_bitmap |= 1 << BlockModeBitPosition::ECB_BIT_POS as i32;
470 }
471 BlockMode::CBC => {
472 *block_mode_bitmap |= 1 << BlockModeBitPosition::CBC_BIT_POS as i32;
473 }
474 BlockMode::CTR => {
475 *block_mode_bitmap |= 1 << BlockModeBitPosition::CTR_BIT_POS as i32;
476 }
477 BlockMode::GCM => {
478 *block_mode_bitmap |= 1 << BlockModeBitPosition::GCM_BIT_POS as i32;
479 }
480 _ => {}
481 }
482}
483
484fn compute_purpose_bitmap(purpose_bitmap: &mut i32, purpose: KeyPurpose) {
485 match purpose {
486 KeyPurpose::ENCRYPT => {
487 *purpose_bitmap |= 1 << KeyPurposeBitPosition::ENCRYPT_BIT_POS as i32;
488 }
489 KeyPurpose::DECRYPT => {
490 *purpose_bitmap |= 1 << KeyPurposeBitPosition::DECRYPT_BIT_POS as i32;
491 }
492 KeyPurpose::SIGN => {
493 *purpose_bitmap |= 1 << KeyPurposeBitPosition::SIGN_BIT_POS as i32;
494 }
495 KeyPurpose::VERIFY => {
496 *purpose_bitmap |= 1 << KeyPurposeBitPosition::VERIFY_BIT_POS as i32;
497 }
498 KeyPurpose::WRAP_KEY => {
499 *purpose_bitmap |= 1 << KeyPurposeBitPosition::WRAP_KEY_BIT_POS as i32;
500 }
501 KeyPurpose::AGREE_KEY => {
502 *purpose_bitmap |= 1 << KeyPurposeBitPosition::AGREE_KEY_BIT_POS as i32;
503 }
504 KeyPurpose::ATTEST_KEY => {
505 *purpose_bitmap |= 1 << KeyPurposeBitPosition::ATTEST_KEY_BIT_POS as i32;
506 }
507 _ => {}
508 }
509}
510
511fn pull_storage_stats() -> Result<Vec<KeystoreAtom>> {
512 let mut atom_vec: Vec<KeystoreAtom> = Vec::new();
513 let mut append = |stat| {
514 match stat {
515 Ok(s) => atom_vec.push(KeystoreAtom {
516 payload: KeystoreAtomPayload::StorageStats(s),
517 ..Default::default()
518 }),
519 Err(error) => {
520 log::error!("pull_metrics_callback: Error getting storage stat: {}", error)
521 }
522 };
523 };
524 DB.with(|db| {
525 let mut db = db.borrow_mut();
526 append(db.get_storage_stat(MetricsStorage::DATABASE));
527 append(db.get_storage_stat(MetricsStorage::KEY_ENTRY));
528 append(db.get_storage_stat(MetricsStorage::KEY_ENTRY_ID_INDEX));
529 append(db.get_storage_stat(MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX));
530 append(db.get_storage_stat(MetricsStorage::BLOB_ENTRY));
531 append(db.get_storage_stat(MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX));
532 append(db.get_storage_stat(MetricsStorage::KEY_PARAMETER));
533 append(db.get_storage_stat(MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX));
534 append(db.get_storage_stat(MetricsStorage::KEY_METADATA));
535 append(db.get_storage_stat(MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX));
536 append(db.get_storage_stat(MetricsStorage::GRANT));
537 append(db.get_storage_stat(MetricsStorage::AUTH_TOKEN));
538 append(db.get_storage_stat(MetricsStorage::BLOB_METADATA));
539 append(db.get_storage_stat(MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX));
540 });
541 Ok(atom_vec)
542}
543
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +0000544fn pull_attestation_pool_stats() -> Result<Vec<KeystoreAtom>> {
545 let mut atoms = Vec::<KeystoreAtom>::new();
546 for sec_level in &[SecurityLevel::TRUSTED_ENVIRONMENT, SecurityLevel::STRONGBOX] {
547 let expired_by = SystemTime::now()
548 .duration_since(UNIX_EPOCH)
549 .unwrap_or_else(|_| Duration::new(0, 0))
550 .as_secs() as i64;
551
552 let result = get_pool_status(expired_by, *sec_level);
553
554 if let Ok(pool_status) = result {
555 let rkp_pool_stats = RkpPoolStats {
556 security_level: process_security_level(*sec_level),
557 expiring: pool_status.expiring,
558 unassigned: pool_status.unassigned,
559 attested: pool_status.attested,
560 total: pool_status.total,
561 };
562 atoms.push(KeystoreAtom {
563 payload: KeystoreAtomPayload::RkpPoolStats(rkp_pool_stats),
564 ..Default::default()
565 });
566 } else {
567 log::error!(
568 concat!(
569 "In pull_attestation_pool_stats: Failed to retrieve pool status",
570 " for security level: {:?}"
571 ),
572 sec_level
573 );
574 }
575 }
576 Ok(atoms)
577}
578
579/// Log error events related to Remote Key Provisioning (RKP).
580pub fn log_rkp_error_stats(rkp_error: MetricsRkpError) {
581 let rkp_error_stats = KeystoreAtomPayload::RkpErrorStats(RkpErrorStats { rkpError: rkp_error });
582 METRICS_STORE.insert_atom(AtomID::RKP_ERROR_STATS, rkp_error_stats);
583}
584
Hasini Gunasinghe15891e62021-06-10 16:23:27 +0000585/// Enum defining the bit position for each padding mode. Since padding mode can be repeatable, it
586/// is represented using a bitmap.
587#[allow(non_camel_case_types)]
588#[repr(i32)]
589enum PaddingModeBitPosition {
590 ///Bit position in the PaddingMode bitmap for NONE.
591 NONE_BIT_POSITION = 0,
592 ///Bit position in the PaddingMode bitmap for RSA_OAEP.
593 RSA_OAEP_BIT_POS = 1,
594 ///Bit position in the PaddingMode bitmap for RSA_PSS.
595 RSA_PSS_BIT_POS = 2,
596 ///Bit position in the PaddingMode bitmap for RSA_PKCS1_1_5_ENCRYPT.
597 RSA_PKCS1_1_5_ENCRYPT_BIT_POS = 3,
598 ///Bit position in the PaddingMode bitmap for RSA_PKCS1_1_5_SIGN.
599 RSA_PKCS1_1_5_SIGN_BIT_POS = 4,
600 ///Bit position in the PaddingMode bitmap for RSA_PKCS7.
601 PKCS7_BIT_POS = 5,
602}
603
604/// Enum defining the bit position for each digest type. Since digest can be repeatable in
605/// key parameters, it is represented using a bitmap.
606#[allow(non_camel_case_types)]
607#[repr(i32)]
608enum DigestBitPosition {
609 ///Bit position in the Digest bitmap for NONE.
610 NONE_BIT_POSITION = 0,
611 ///Bit position in the Digest bitmap for MD5.
612 MD5_BIT_POS = 1,
613 ///Bit position in the Digest bitmap for SHA1.
614 SHA_1_BIT_POS = 2,
615 ///Bit position in the Digest bitmap for SHA_2_224.
616 SHA_2_224_BIT_POS = 3,
617 ///Bit position in the Digest bitmap for SHA_2_256.
618 SHA_2_256_BIT_POS = 4,
619 ///Bit position in the Digest bitmap for SHA_2_384.
620 SHA_2_384_BIT_POS = 5,
621 ///Bit position in the Digest bitmap for SHA_2_512.
622 SHA_2_512_BIT_POS = 6,
623}
624
625/// Enum defining the bit position for each block mode type. Since block mode can be repeatable in
626/// key parameters, it is represented using a bitmap.
627#[allow(non_camel_case_types)]
628#[repr(i32)]
629enum BlockModeBitPosition {
630 ///Bit position in the BlockMode bitmap for ECB.
631 ECB_BIT_POS = 1,
632 ///Bit position in the BlockMode bitmap for CBC.
633 CBC_BIT_POS = 2,
634 ///Bit position in the BlockMode bitmap for CTR.
635 CTR_BIT_POS = 3,
636 ///Bit position in the BlockMode bitmap for GCM.
637 GCM_BIT_POS = 4,
638}
639
640/// Enum defining the bit position for each key purpose. Since key purpose can be repeatable in
641/// key parameters, it is represented using a bitmap.
642#[allow(non_camel_case_types)]
643#[repr(i32)]
644enum KeyPurposeBitPosition {
645 ///Bit position in the KeyPurpose bitmap for Encrypt.
646 ENCRYPT_BIT_POS = 1,
647 ///Bit position in the KeyPurpose bitmap for Decrypt.
648 DECRYPT_BIT_POS = 2,
649 ///Bit position in the KeyPurpose bitmap for Sign.
650 SIGN_BIT_POS = 3,
651 ///Bit position in the KeyPurpose bitmap for Verify.
652 VERIFY_BIT_POS = 4,
653 ///Bit position in the KeyPurpose bitmap for Wrap Key.
654 WRAP_KEY_BIT_POS = 5,
655 ///Bit position in the KeyPurpose bitmap for Agree Key.
656 AGREE_KEY_BIT_POS = 6,
657 ///Bit position in the KeyPurpose bitmap for Attest Key.
658 ATTEST_KEY_BIT_POS = 7,
659}