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