xref: /aosp_15_r20/system/security/keystore2/src/metrics_store.rs (revision e1997b9af69e3155ead6e072d106a0077849ffba)
1 // Copyright 2021, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! This is the metrics store module of keystore. It does the following tasks:
16 //! 1. Processes the data about keystore events asynchronously, and
17 //!    stores them in an in-memory store.
18 //! 2. Returns the collected metrics when requested by the statsd proxy.
19 
20 use crate::error::anyhow_error_to_serialized_error;
21 use crate::globals::DB;
22 use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
23 use crate::ks_err;
24 use crate::operation::Outcome;
25 use crate::utils::watchdog as wd;
26 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
27     Algorithm::Algorithm, BlockMode::BlockMode, Digest::Digest, EcCurve::EcCurve,
28     HardwareAuthenticatorType::HardwareAuthenticatorType, KeyOrigin::KeyOrigin,
29     KeyParameter::KeyParameter, KeyPurpose::KeyPurpose, PaddingMode::PaddingMode,
30     SecurityLevel::SecurityLevel,
31 };
32 use android_security_metrics::aidl::android::security::metrics::{
33     Algorithm::Algorithm as MetricsAlgorithm, AtomID::AtomID, CrashStats::CrashStats,
34     EcCurve::EcCurve as MetricsEcCurve,
35     HardwareAuthenticatorType::HardwareAuthenticatorType as MetricsHardwareAuthenticatorType,
36     KeyCreationWithAuthInfo::KeyCreationWithAuthInfo,
37     KeyCreationWithGeneralInfo::KeyCreationWithGeneralInfo,
38     KeyCreationWithPurposeAndModesInfo::KeyCreationWithPurposeAndModesInfo,
39     KeyOperationWithGeneralInfo::KeyOperationWithGeneralInfo,
40     KeyOperationWithPurposeAndModesInfo::KeyOperationWithPurposeAndModesInfo,
41     KeyOrigin::KeyOrigin as MetricsKeyOrigin, Keystore2AtomWithOverflow::Keystore2AtomWithOverflow,
42     KeystoreAtom::KeystoreAtom, KeystoreAtomPayload::KeystoreAtomPayload,
43     Outcome::Outcome as MetricsOutcome, Purpose::Purpose as MetricsPurpose,
44     RkpError::RkpError as MetricsRkpError, RkpErrorStats::RkpErrorStats,
45     SecurityLevel::SecurityLevel as MetricsSecurityLevel, Storage::Storage as MetricsStorage,
46 };
47 use anyhow::{anyhow, Context, Result};
48 use std::collections::HashMap;
49 use std::sync::{LazyLock, Mutex};
50 
51 // Note: Crash events are recorded at keystore restarts, based on the assumption that keystore only
52 // gets restarted after a crash, during a boot cycle.
53 const KEYSTORE_CRASH_COUNT_PROPERTY: &str = "keystore.crash_count";
54 
55 /// Singleton for MetricsStore.
56 pub static METRICS_STORE: LazyLock<MetricsStore> = LazyLock::new(Default::default);
57 
58 /// MetricsStore stores the <atom object, count> as <key, value> in the inner hash map,
59 /// indexed by the atom id, in the outer hash map.
60 /// There can be different atom objects with the same atom id based on the values assigned to the
61 /// fields of the atom objects. When an atom object with a particular combination of field values is
62 /// inserted, we first check if that atom object is in the inner hash map. If one exists, count
63 /// is inceremented. Otherwise, the atom object is inserted with count = 1. Note that count field
64 /// of the atom object itself is set to 0 while the object is stored in the hash map. When the atom
65 /// objects are queried by the atom id, the corresponding atom objects are retrieved, cloned, and
66 /// the count field of the cloned objects is set to the corresponding value field in the inner hash
67 /// map before the query result is returned.
68 #[derive(Default)]
69 pub struct MetricsStore {
70     metrics_store: Mutex<HashMap<AtomID, HashMap<KeystoreAtomPayload, i32>>>,
71 }
72 
73 impl std::fmt::Debug for MetricsStore {
fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error>74     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
75         let store = self.metrics_store.lock().unwrap();
76         let mut atom_ids: Vec<&AtomID> = store.keys().collect();
77         atom_ids.sort();
78         for atom_id in atom_ids {
79             writeln!(f, "  {} : [", atom_id.show())?;
80             let data = store.get(atom_id).unwrap();
81             let mut payloads: Vec<&KeystoreAtomPayload> = data.keys().collect();
82             payloads.sort();
83             for payload in payloads {
84                 let count = data.get(payload).unwrap();
85                 writeln!(f, "    {} => count={count}", payload.show())?;
86             }
87             writeln!(f, "  ]")?;
88         }
89         Ok(())
90     }
91 }
92 
93 impl MetricsStore {
94     /// There are some atoms whose maximum cardinality exceeds the cardinality limits tolerated
95     /// by statsd. Statsd tolerates cardinality between 200-300. Therefore, the in-memory storage
96     /// limit for a single atom is set to 250. If the number of atom objects created for a
97     /// particular atom exceeds this limit, an overflow atom object is created to track the ID of
98     /// such atoms.
99     const SINGLE_ATOM_STORE_MAX_SIZE: usize = 250;
100 
101     /// Return a vector of atom objects with the given atom ID, if one exists in the metrics_store.
102     /// If any atom object does not exist in the metrics_store for the given atom ID, return an
103     /// empty vector.
get_atoms(&self, atom_id: AtomID) -> Result<Vec<KeystoreAtom>>104     pub fn get_atoms(&self, atom_id: AtomID) -> Result<Vec<KeystoreAtom>> {
105         // StorageStats is an original pulled atom (i.e. not a pushed atom converted to a
106         // pulled atom). Therefore, it is handled separately.
107         if AtomID::STORAGE_STATS == atom_id {
108             let _wp = wd::watch("MetricsStore::get_atoms calling pull_storage_stats");
109             return pull_storage_stats();
110         }
111 
112         // Process keystore crash stats.
113         if AtomID::CRASH_STATS == atom_id {
114             let _wp = wd::watch("MetricsStore::get_atoms calling read_keystore_crash_count");
115             return match read_keystore_crash_count()? {
116                 Some(count) => Ok(vec![KeystoreAtom {
117                     payload: KeystoreAtomPayload::CrashStats(CrashStats {
118                         count_of_crash_events: count,
119                     }),
120                     ..Default::default()
121                 }]),
122                 None => Err(anyhow!("Crash count property is not set")),
123             };
124         }
125 
126         let metrics_store_guard = self.metrics_store.lock().unwrap();
127         metrics_store_guard.get(&atom_id).map_or(Ok(Vec::<KeystoreAtom>::new()), |atom_count_map| {
128             Ok(atom_count_map
129                 .iter()
130                 .map(|(atom, count)| KeystoreAtom { payload: atom.clone(), count: *count })
131                 .collect())
132         })
133     }
134 
135     /// Insert an atom object to the metrics_store indexed by the atom ID.
insert_atom(&self, atom_id: AtomID, atom: KeystoreAtomPayload)136     fn insert_atom(&self, atom_id: AtomID, atom: KeystoreAtomPayload) {
137         let mut metrics_store_guard = self.metrics_store.lock().unwrap();
138         let atom_count_map = metrics_store_guard.entry(atom_id).or_default();
139         if atom_count_map.len() < MetricsStore::SINGLE_ATOM_STORE_MAX_SIZE {
140             let atom_count = atom_count_map.entry(atom).or_insert(0);
141             *atom_count += 1;
142         } else {
143             // Insert an overflow atom
144             let overflow_atom_count_map =
145                 metrics_store_guard.entry(AtomID::KEYSTORE2_ATOM_WITH_OVERFLOW).or_default();
146 
147             if overflow_atom_count_map.len() < MetricsStore::SINGLE_ATOM_STORE_MAX_SIZE {
148                 let overflow_atom = Keystore2AtomWithOverflow { atom_id };
149                 let atom_count = overflow_atom_count_map
150                     .entry(KeystoreAtomPayload::Keystore2AtomWithOverflow(overflow_atom))
151                     .or_insert(0);
152                 *atom_count += 1;
153             } else {
154                 // This is a rare case, if at all.
155                 log::error!("In insert_atom: Maximum storage limit reached for overflow atom.")
156             }
157         }
158     }
159 }
160 
161 /// Log key creation events to be sent to statsd.
log_key_creation_event_stats<U>( sec_level: SecurityLevel, key_params: &[KeyParameter], result: &Result<U>, )162 pub fn log_key_creation_event_stats<U>(
163     sec_level: SecurityLevel,
164     key_params: &[KeyParameter],
165     result: &Result<U>,
166 ) {
167     let (
168         key_creation_with_general_info,
169         key_creation_with_auth_info,
170         key_creation_with_purpose_and_modes_info,
171     ) = process_key_creation_event_stats(sec_level, key_params, result);
172 
173     METRICS_STORE
174         .insert_atom(AtomID::KEY_CREATION_WITH_GENERAL_INFO, key_creation_with_general_info);
175     METRICS_STORE.insert_atom(AtomID::KEY_CREATION_WITH_AUTH_INFO, key_creation_with_auth_info);
176     METRICS_STORE.insert_atom(
177         AtomID::KEY_CREATION_WITH_PURPOSE_AND_MODES_INFO,
178         key_creation_with_purpose_and_modes_info,
179     );
180 }
181 
182 // Process the statistics related to key creations and return the three atom objects related to key
183 // creations: i) KeyCreationWithGeneralInfo ii) KeyCreationWithAuthInfo
184 // iii) KeyCreationWithPurposeAndModesInfo
process_key_creation_event_stats<U>( sec_level: SecurityLevel, key_params: &[KeyParameter], result: &Result<U>, ) -> (KeystoreAtomPayload, KeystoreAtomPayload, KeystoreAtomPayload)185 fn process_key_creation_event_stats<U>(
186     sec_level: SecurityLevel,
187     key_params: &[KeyParameter],
188     result: &Result<U>,
189 ) -> (KeystoreAtomPayload, KeystoreAtomPayload, KeystoreAtomPayload) {
190     // In the default atom objects, fields represented by bitmaps and i32 fields
191     // will take 0, except error_code which defaults to 1 indicating NO_ERROR and key_size,
192     // and auth_time_out which defaults to -1.
193     // The boolean fields are set to false by default.
194     // Some keymint enums do have 0 as an enum variant value. In such cases, the corresponding
195     // enum variant value in atoms.proto is incremented by 1, in order to have 0 as the reserved
196     // value for unspecified fields.
197     let mut key_creation_with_general_info = KeyCreationWithGeneralInfo {
198         algorithm: MetricsAlgorithm::ALGORITHM_UNSPECIFIED,
199         key_size: -1,
200         ec_curve: MetricsEcCurve::EC_CURVE_UNSPECIFIED,
201         key_origin: MetricsKeyOrigin::ORIGIN_UNSPECIFIED,
202         error_code: 1,
203         // Default for bool is false (for attestation_requested field).
204         ..Default::default()
205     };
206 
207     let mut key_creation_with_auth_info = KeyCreationWithAuthInfo {
208         user_auth_type: MetricsHardwareAuthenticatorType::AUTH_TYPE_UNSPECIFIED,
209         log10_auth_key_timeout_seconds: -1,
210         security_level: MetricsSecurityLevel::SECURITY_LEVEL_UNSPECIFIED,
211     };
212 
213     let mut key_creation_with_purpose_and_modes_info = KeyCreationWithPurposeAndModesInfo {
214         algorithm: MetricsAlgorithm::ALGORITHM_UNSPECIFIED,
215         // Default for i32 is 0 (for the remaining bitmap fields).
216         ..Default::default()
217     };
218 
219     if let Err(ref e) = result {
220         key_creation_with_general_info.error_code = anyhow_error_to_serialized_error(e).0;
221     }
222 
223     key_creation_with_auth_info.security_level = process_security_level(sec_level);
224 
225     for key_param in key_params.iter().map(KsKeyParamValue::from) {
226         match key_param {
227             KsKeyParamValue::Algorithm(a) => {
228                 let algorithm = match a {
229                     Algorithm::RSA => MetricsAlgorithm::RSA,
230                     Algorithm::EC => MetricsAlgorithm::EC,
231                     Algorithm::AES => MetricsAlgorithm::AES,
232                     Algorithm::TRIPLE_DES => MetricsAlgorithm::TRIPLE_DES,
233                     Algorithm::HMAC => MetricsAlgorithm::HMAC,
234                     _ => MetricsAlgorithm::ALGORITHM_UNSPECIFIED,
235                 };
236                 key_creation_with_general_info.algorithm = algorithm;
237                 key_creation_with_purpose_and_modes_info.algorithm = algorithm;
238             }
239             KsKeyParamValue::KeySize(s) => {
240                 key_creation_with_general_info.key_size = s;
241             }
242             KsKeyParamValue::KeyOrigin(o) => {
243                 key_creation_with_general_info.key_origin = match o {
244                     KeyOrigin::GENERATED => MetricsKeyOrigin::GENERATED,
245                     KeyOrigin::DERIVED => MetricsKeyOrigin::DERIVED,
246                     KeyOrigin::IMPORTED => MetricsKeyOrigin::IMPORTED,
247                     KeyOrigin::RESERVED => MetricsKeyOrigin::RESERVED,
248                     KeyOrigin::SECURELY_IMPORTED => MetricsKeyOrigin::SECURELY_IMPORTED,
249                     _ => MetricsKeyOrigin::ORIGIN_UNSPECIFIED,
250                 }
251             }
252             KsKeyParamValue::HardwareAuthenticatorType(a) => {
253                 key_creation_with_auth_info.user_auth_type = match a {
254                     HardwareAuthenticatorType::NONE => MetricsHardwareAuthenticatorType::NONE,
255                     HardwareAuthenticatorType::PASSWORD => {
256                         MetricsHardwareAuthenticatorType::PASSWORD
257                     }
258                     HardwareAuthenticatorType::FINGERPRINT => {
259                         MetricsHardwareAuthenticatorType::FINGERPRINT
260                     }
261                     HardwareAuthenticatorType::ANY => MetricsHardwareAuthenticatorType::ANY,
262                     _ => MetricsHardwareAuthenticatorType::AUTH_TYPE_UNSPECIFIED,
263                 }
264             }
265             KsKeyParamValue::AuthTimeout(t) => {
266                 key_creation_with_auth_info.log10_auth_key_timeout_seconds =
267                     f32::log10(t as f32) as i32;
268             }
269             KsKeyParamValue::PaddingMode(p) => {
270                 compute_padding_mode_bitmap(
271                     &mut key_creation_with_purpose_and_modes_info.padding_mode_bitmap,
272                     p,
273                 );
274             }
275             KsKeyParamValue::Digest(d) => {
276                 // key_creation_with_purpose_and_modes_info.digest_bitmap =
277                 compute_digest_bitmap(
278                     &mut key_creation_with_purpose_and_modes_info.digest_bitmap,
279                     d,
280                 );
281             }
282             KsKeyParamValue::BlockMode(b) => {
283                 compute_block_mode_bitmap(
284                     &mut key_creation_with_purpose_and_modes_info.block_mode_bitmap,
285                     b,
286                 );
287             }
288             KsKeyParamValue::KeyPurpose(k) => {
289                 compute_purpose_bitmap(
290                     &mut key_creation_with_purpose_and_modes_info.purpose_bitmap,
291                     k,
292                 );
293             }
294             KsKeyParamValue::EcCurve(e) => {
295                 key_creation_with_general_info.ec_curve = match e {
296                     EcCurve::P_224 => MetricsEcCurve::P_224,
297                     EcCurve::P_256 => MetricsEcCurve::P_256,
298                     EcCurve::P_384 => MetricsEcCurve::P_384,
299                     EcCurve::P_521 => MetricsEcCurve::P_521,
300                     EcCurve::CURVE_25519 => MetricsEcCurve::CURVE_25519,
301                     _ => MetricsEcCurve::EC_CURVE_UNSPECIFIED,
302                 }
303             }
304             KsKeyParamValue::AttestationChallenge(_) => {
305                 key_creation_with_general_info.attestation_requested = true;
306             }
307             _ => {}
308         }
309     }
310     if key_creation_with_general_info.algorithm == MetricsAlgorithm::EC {
311         // Do not record key sizes if Algorithm = EC, in order to reduce cardinality.
312         key_creation_with_general_info.key_size = -1;
313     }
314 
315     (
316         KeystoreAtomPayload::KeyCreationWithGeneralInfo(key_creation_with_general_info),
317         KeystoreAtomPayload::KeyCreationWithAuthInfo(key_creation_with_auth_info),
318         KeystoreAtomPayload::KeyCreationWithPurposeAndModesInfo(
319             key_creation_with_purpose_and_modes_info,
320         ),
321     )
322 }
323 
324 /// Log key operation events to be sent to statsd.
log_key_operation_event_stats( sec_level: SecurityLevel, key_purpose: KeyPurpose, op_params: &[KeyParameter], op_outcome: &Outcome, key_upgraded: bool, )325 pub fn log_key_operation_event_stats(
326     sec_level: SecurityLevel,
327     key_purpose: KeyPurpose,
328     op_params: &[KeyParameter],
329     op_outcome: &Outcome,
330     key_upgraded: bool,
331 ) {
332     let (key_operation_with_general_info, key_operation_with_purpose_and_modes_info) =
333         process_key_operation_event_stats(
334             sec_level,
335             key_purpose,
336             op_params,
337             op_outcome,
338             key_upgraded,
339         );
340     METRICS_STORE
341         .insert_atom(AtomID::KEY_OPERATION_WITH_GENERAL_INFO, key_operation_with_general_info);
342     METRICS_STORE.insert_atom(
343         AtomID::KEY_OPERATION_WITH_PURPOSE_AND_MODES_INFO,
344         key_operation_with_purpose_and_modes_info,
345     );
346 }
347 
348 // Process the statistics related to key operations and return the two atom objects related to key
349 // operations: i) KeyOperationWithGeneralInfo ii) KeyOperationWithPurposeAndModesInfo
process_key_operation_event_stats( sec_level: SecurityLevel, key_purpose: KeyPurpose, op_params: &[KeyParameter], op_outcome: &Outcome, key_upgraded: bool, ) -> (KeystoreAtomPayload, KeystoreAtomPayload)350 fn process_key_operation_event_stats(
351     sec_level: SecurityLevel,
352     key_purpose: KeyPurpose,
353     op_params: &[KeyParameter],
354     op_outcome: &Outcome,
355     key_upgraded: bool,
356 ) -> (KeystoreAtomPayload, KeystoreAtomPayload) {
357     let mut key_operation_with_general_info = KeyOperationWithGeneralInfo {
358         outcome: MetricsOutcome::OUTCOME_UNSPECIFIED,
359         error_code: 1,
360         security_level: MetricsSecurityLevel::SECURITY_LEVEL_UNSPECIFIED,
361         // Default for bool is false (for key_upgraded field).
362         ..Default::default()
363     };
364 
365     let mut key_operation_with_purpose_and_modes_info = KeyOperationWithPurposeAndModesInfo {
366         purpose: MetricsPurpose::KEY_PURPOSE_UNSPECIFIED,
367         // Default for i32 is 0 (for the remaining bitmap fields).
368         ..Default::default()
369     };
370 
371     key_operation_with_general_info.security_level = process_security_level(sec_level);
372 
373     key_operation_with_general_info.key_upgraded = key_upgraded;
374 
375     key_operation_with_purpose_and_modes_info.purpose = match key_purpose {
376         KeyPurpose::ENCRYPT => MetricsPurpose::ENCRYPT,
377         KeyPurpose::DECRYPT => MetricsPurpose::DECRYPT,
378         KeyPurpose::SIGN => MetricsPurpose::SIGN,
379         KeyPurpose::VERIFY => MetricsPurpose::VERIFY,
380         KeyPurpose::WRAP_KEY => MetricsPurpose::WRAP_KEY,
381         KeyPurpose::AGREE_KEY => MetricsPurpose::AGREE_KEY,
382         KeyPurpose::ATTEST_KEY => MetricsPurpose::ATTEST_KEY,
383         _ => MetricsPurpose::KEY_PURPOSE_UNSPECIFIED,
384     };
385 
386     key_operation_with_general_info.outcome = match op_outcome {
387         Outcome::Unknown | Outcome::Dropped => MetricsOutcome::DROPPED,
388         Outcome::Success => MetricsOutcome::SUCCESS,
389         Outcome::Abort => MetricsOutcome::ABORT,
390         Outcome::Pruned => MetricsOutcome::PRUNED,
391         Outcome::ErrorCode(e) => {
392             key_operation_with_general_info.error_code = e.0;
393             MetricsOutcome::ERROR
394         }
395     };
396 
397     for key_param in op_params.iter().map(KsKeyParamValue::from) {
398         match key_param {
399             KsKeyParamValue::PaddingMode(p) => {
400                 compute_padding_mode_bitmap(
401                     &mut key_operation_with_purpose_and_modes_info.padding_mode_bitmap,
402                     p,
403                 );
404             }
405             KsKeyParamValue::Digest(d) => {
406                 compute_digest_bitmap(
407                     &mut key_operation_with_purpose_and_modes_info.digest_bitmap,
408                     d,
409                 );
410             }
411             KsKeyParamValue::BlockMode(b) => {
412                 compute_block_mode_bitmap(
413                     &mut key_operation_with_purpose_and_modes_info.block_mode_bitmap,
414                     b,
415                 );
416             }
417             _ => {}
418         }
419     }
420 
421     (
422         KeystoreAtomPayload::KeyOperationWithGeneralInfo(key_operation_with_general_info),
423         KeystoreAtomPayload::KeyOperationWithPurposeAndModesInfo(
424             key_operation_with_purpose_and_modes_info,
425         ),
426     )
427 }
428 
process_security_level(sec_level: SecurityLevel) -> MetricsSecurityLevel429 fn process_security_level(sec_level: SecurityLevel) -> MetricsSecurityLevel {
430     match sec_level {
431         SecurityLevel::SOFTWARE => MetricsSecurityLevel::SECURITY_LEVEL_SOFTWARE,
432         SecurityLevel::TRUSTED_ENVIRONMENT => {
433             MetricsSecurityLevel::SECURITY_LEVEL_TRUSTED_ENVIRONMENT
434         }
435         SecurityLevel::STRONGBOX => MetricsSecurityLevel::SECURITY_LEVEL_STRONGBOX,
436         SecurityLevel::KEYSTORE => MetricsSecurityLevel::SECURITY_LEVEL_KEYSTORE,
437         _ => MetricsSecurityLevel::SECURITY_LEVEL_UNSPECIFIED,
438     }
439 }
440 
compute_padding_mode_bitmap(padding_mode_bitmap: &mut i32, padding_mode: PaddingMode)441 fn compute_padding_mode_bitmap(padding_mode_bitmap: &mut i32, padding_mode: PaddingMode) {
442     match padding_mode {
443         PaddingMode::NONE => {
444             *padding_mode_bitmap |= 1 << PaddingModeBitPosition::NONE_BIT_POSITION as i32;
445         }
446         PaddingMode::RSA_OAEP => {
447             *padding_mode_bitmap |= 1 << PaddingModeBitPosition::RSA_OAEP_BIT_POS as i32;
448         }
449         PaddingMode::RSA_PSS => {
450             *padding_mode_bitmap |= 1 << PaddingModeBitPosition::RSA_PSS_BIT_POS as i32;
451         }
452         PaddingMode::RSA_PKCS1_1_5_ENCRYPT => {
453             *padding_mode_bitmap |=
454                 1 << PaddingModeBitPosition::RSA_PKCS1_1_5_ENCRYPT_BIT_POS as i32;
455         }
456         PaddingMode::RSA_PKCS1_1_5_SIGN => {
457             *padding_mode_bitmap |= 1 << PaddingModeBitPosition::RSA_PKCS1_1_5_SIGN_BIT_POS as i32;
458         }
459         PaddingMode::PKCS7 => {
460             *padding_mode_bitmap |= 1 << PaddingModeBitPosition::PKCS7_BIT_POS as i32;
461         }
462         _ => {}
463     }
464 }
465 
compute_digest_bitmap(digest_bitmap: &mut i32, digest: Digest)466 fn compute_digest_bitmap(digest_bitmap: &mut i32, digest: Digest) {
467     match digest {
468         Digest::NONE => {
469             *digest_bitmap |= 1 << DigestBitPosition::NONE_BIT_POSITION as i32;
470         }
471         Digest::MD5 => {
472             *digest_bitmap |= 1 << DigestBitPosition::MD5_BIT_POS as i32;
473         }
474         Digest::SHA1 => {
475             *digest_bitmap |= 1 << DigestBitPosition::SHA_1_BIT_POS as i32;
476         }
477         Digest::SHA_2_224 => {
478             *digest_bitmap |= 1 << DigestBitPosition::SHA_2_224_BIT_POS as i32;
479         }
480         Digest::SHA_2_256 => {
481             *digest_bitmap |= 1 << DigestBitPosition::SHA_2_256_BIT_POS as i32;
482         }
483         Digest::SHA_2_384 => {
484             *digest_bitmap |= 1 << DigestBitPosition::SHA_2_384_BIT_POS as i32;
485         }
486         Digest::SHA_2_512 => {
487             *digest_bitmap |= 1 << DigestBitPosition::SHA_2_512_BIT_POS as i32;
488         }
489         _ => {}
490     }
491 }
492 
compute_block_mode_bitmap(block_mode_bitmap: &mut i32, block_mode: BlockMode)493 fn compute_block_mode_bitmap(block_mode_bitmap: &mut i32, block_mode: BlockMode) {
494     match block_mode {
495         BlockMode::ECB => {
496             *block_mode_bitmap |= 1 << BlockModeBitPosition::ECB_BIT_POS as i32;
497         }
498         BlockMode::CBC => {
499             *block_mode_bitmap |= 1 << BlockModeBitPosition::CBC_BIT_POS as i32;
500         }
501         BlockMode::CTR => {
502             *block_mode_bitmap |= 1 << BlockModeBitPosition::CTR_BIT_POS as i32;
503         }
504         BlockMode::GCM => {
505             *block_mode_bitmap |= 1 << BlockModeBitPosition::GCM_BIT_POS as i32;
506         }
507         _ => {}
508     }
509 }
510 
compute_purpose_bitmap(purpose_bitmap: &mut i32, purpose: KeyPurpose)511 fn compute_purpose_bitmap(purpose_bitmap: &mut i32, purpose: KeyPurpose) {
512     match purpose {
513         KeyPurpose::ENCRYPT => {
514             *purpose_bitmap |= 1 << KeyPurposeBitPosition::ENCRYPT_BIT_POS as i32;
515         }
516         KeyPurpose::DECRYPT => {
517             *purpose_bitmap |= 1 << KeyPurposeBitPosition::DECRYPT_BIT_POS as i32;
518         }
519         KeyPurpose::SIGN => {
520             *purpose_bitmap |= 1 << KeyPurposeBitPosition::SIGN_BIT_POS as i32;
521         }
522         KeyPurpose::VERIFY => {
523             *purpose_bitmap |= 1 << KeyPurposeBitPosition::VERIFY_BIT_POS as i32;
524         }
525         KeyPurpose::WRAP_KEY => {
526             *purpose_bitmap |= 1 << KeyPurposeBitPosition::WRAP_KEY_BIT_POS as i32;
527         }
528         KeyPurpose::AGREE_KEY => {
529             *purpose_bitmap |= 1 << KeyPurposeBitPosition::AGREE_KEY_BIT_POS as i32;
530         }
531         KeyPurpose::ATTEST_KEY => {
532             *purpose_bitmap |= 1 << KeyPurposeBitPosition::ATTEST_KEY_BIT_POS as i32;
533         }
534         _ => {}
535     }
536 }
537 
pull_storage_stats() -> Result<Vec<KeystoreAtom>>538 pub(crate) fn pull_storage_stats() -> Result<Vec<KeystoreAtom>> {
539     let mut atom_vec: Vec<KeystoreAtom> = Vec::new();
540     let mut append = |stat| {
541         match stat {
542             Ok(s) => atom_vec.push(KeystoreAtom {
543                 payload: KeystoreAtomPayload::StorageStats(s),
544                 ..Default::default()
545             }),
546             Err(error) => {
547                 log::error!("pull_metrics_callback: Error getting storage stat: {}", error)
548             }
549         };
550     };
551     DB.with(|db| {
552         let mut db = db.borrow_mut();
553         append(db.get_storage_stat(MetricsStorage::DATABASE));
554         append(db.get_storage_stat(MetricsStorage::KEY_ENTRY));
555         append(db.get_storage_stat(MetricsStorage::KEY_ENTRY_ID_INDEX));
556         append(db.get_storage_stat(MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX));
557         append(db.get_storage_stat(MetricsStorage::BLOB_ENTRY));
558         append(db.get_storage_stat(MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX));
559         append(db.get_storage_stat(MetricsStorage::KEY_PARAMETER));
560         append(db.get_storage_stat(MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX));
561         append(db.get_storage_stat(MetricsStorage::KEY_METADATA));
562         append(db.get_storage_stat(MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX));
563         append(db.get_storage_stat(MetricsStorage::GRANT));
564         append(db.get_storage_stat(MetricsStorage::AUTH_TOKEN));
565         append(db.get_storage_stat(MetricsStorage::BLOB_METADATA));
566         append(db.get_storage_stat(MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX));
567     });
568     Ok(atom_vec)
569 }
570 
571 /// Log error events related to Remote Key Provisioning (RKP).
log_rkp_error_stats(rkp_error: MetricsRkpError, sec_level: &SecurityLevel)572 pub fn log_rkp_error_stats(rkp_error: MetricsRkpError, sec_level: &SecurityLevel) {
573     let rkp_error_stats = KeystoreAtomPayload::RkpErrorStats(RkpErrorStats {
574         rkpError: rkp_error,
575         security_level: process_security_level(*sec_level),
576     });
577     METRICS_STORE.insert_atom(AtomID::RKP_ERROR_STATS, rkp_error_stats);
578 }
579 
580 /// This function tries to read and update the system property: keystore.crash_count.
581 /// If the property is absent, it sets the property with value 0. If the property is present, it
582 /// increments the value. This helps tracking keystore crashes internally.
update_keystore_crash_sysprop()583 pub fn update_keystore_crash_sysprop() {
584     let new_count = match read_keystore_crash_count() {
585         Ok(Some(count)) => count + 1,
586         // If the property is absent, then this is the first start up during the boot.
587         // Proceed to write the system property with value 0.
588         Ok(None) => 0,
589         Err(error) => {
590             log::warn!(
591                 concat!(
592                     "In update_keystore_crash_sysprop: ",
593                     "Failed to read the existing system property due to: {:?}.",
594                     "Therefore, keystore crashes will not be logged."
595                 ),
596                 error
597             );
598             return;
599         }
600     };
601 
602     if let Err(e) =
603         rustutils::system_properties::write(KEYSTORE_CRASH_COUNT_PROPERTY, &new_count.to_string())
604     {
605         log::error!(
606             concat!(
607                 "In update_keystore_crash_sysprop:: ",
608                 "Failed to write the system property due to error: {:?}"
609             ),
610             e
611         );
612     }
613 }
614 
615 /// Read the system property: keystore.crash_count.
read_keystore_crash_count() -> Result<Option<i32>>616 pub fn read_keystore_crash_count() -> Result<Option<i32>> {
617     match rustutils::system_properties::read("keystore.crash_count") {
618         Ok(Some(count)) => count.parse::<i32>().map(Some).map_err(std::convert::Into::into),
619         Ok(None) => Ok(None),
620         Err(e) => Err(e).context(ks_err!("Failed to read crash count property.")),
621     }
622 }
623 
624 /// Enum defining the bit position for each padding mode. Since padding mode can be repeatable, it
625 /// is represented using a bitmap.
626 #[allow(non_camel_case_types)]
627 #[repr(i32)]
628 enum PaddingModeBitPosition {
629     ///Bit position in the PaddingMode bitmap for NONE.
630     NONE_BIT_POSITION = 0,
631     ///Bit position in the PaddingMode bitmap for RSA_OAEP.
632     RSA_OAEP_BIT_POS = 1,
633     ///Bit position in the PaddingMode bitmap for RSA_PSS.
634     RSA_PSS_BIT_POS = 2,
635     ///Bit position in the PaddingMode bitmap for RSA_PKCS1_1_5_ENCRYPT.
636     RSA_PKCS1_1_5_ENCRYPT_BIT_POS = 3,
637     ///Bit position in the PaddingMode bitmap for RSA_PKCS1_1_5_SIGN.
638     RSA_PKCS1_1_5_SIGN_BIT_POS = 4,
639     ///Bit position in the PaddingMode bitmap for RSA_PKCS7.
640     PKCS7_BIT_POS = 5,
641 }
642 
643 /// Enum defining the bit position for each digest type. Since digest can be repeatable in
644 /// key parameters, it is represented using a bitmap.
645 #[allow(non_camel_case_types)]
646 #[repr(i32)]
647 enum DigestBitPosition {
648     ///Bit position in the Digest bitmap for NONE.
649     NONE_BIT_POSITION = 0,
650     ///Bit position in the Digest bitmap for MD5.
651     MD5_BIT_POS = 1,
652     ///Bit position in the Digest bitmap for SHA1.
653     SHA_1_BIT_POS = 2,
654     ///Bit position in the Digest bitmap for SHA_2_224.
655     SHA_2_224_BIT_POS = 3,
656     ///Bit position in the Digest bitmap for SHA_2_256.
657     SHA_2_256_BIT_POS = 4,
658     ///Bit position in the Digest bitmap for SHA_2_384.
659     SHA_2_384_BIT_POS = 5,
660     ///Bit position in the Digest bitmap for SHA_2_512.
661     SHA_2_512_BIT_POS = 6,
662 }
663 
664 /// Enum defining the bit position for each block mode type. Since block mode can be repeatable in
665 /// key parameters, it is represented using a bitmap.
666 #[allow(non_camel_case_types)]
667 #[repr(i32)]
668 enum BlockModeBitPosition {
669     ///Bit position in the BlockMode bitmap for ECB.
670     ECB_BIT_POS = 1,
671     ///Bit position in the BlockMode bitmap for CBC.
672     CBC_BIT_POS = 2,
673     ///Bit position in the BlockMode bitmap for CTR.
674     CTR_BIT_POS = 3,
675     ///Bit position in the BlockMode bitmap for GCM.
676     GCM_BIT_POS = 4,
677 }
678 
679 /// Enum defining the bit position for each key purpose. Since key purpose can be repeatable in
680 /// key parameters, it is represented using a bitmap.
681 #[allow(non_camel_case_types)]
682 #[repr(i32)]
683 enum KeyPurposeBitPosition {
684     ///Bit position in the KeyPurpose bitmap for Encrypt.
685     ENCRYPT_BIT_POS = 1,
686     ///Bit position in the KeyPurpose bitmap for Decrypt.
687     DECRYPT_BIT_POS = 2,
688     ///Bit position in the KeyPurpose bitmap for Sign.
689     SIGN_BIT_POS = 3,
690     ///Bit position in the KeyPurpose bitmap for Verify.
691     VERIFY_BIT_POS = 4,
692     ///Bit position in the KeyPurpose bitmap for Wrap Key.
693     WRAP_KEY_BIT_POS = 5,
694     ///Bit position in the KeyPurpose bitmap for Agree Key.
695     AGREE_KEY_BIT_POS = 6,
696     ///Bit position in the KeyPurpose bitmap for Attest Key.
697     ATTEST_KEY_BIT_POS = 7,
698 }
699 
700 /// The various metrics-related types are not defined in this crate, so the orphan
701 /// trait rule means that `std::fmt::Debug` cannot be implemented for them.
702 /// Instead, create our own local trait that generates a debug string for a type.
703 trait Summary {
show(&self) -> String704     fn show(&self) -> String;
705 }
706 
707 /// Implement the [`Summary`] trait for AIDL-derived pseudo-enums, mapping named enum values to
708 /// specified short names, all padded with spaces to the specified width (to allow improved
709 /// readability when printed in a group).
710 macro_rules! impl_summary_enum {
711     {  $enum:ident, $width:literal, $( $variant:ident => $short:literal ),+ $(,)? } => {
712         impl Summary for $enum{
713             fn show(&self) -> String {
714                 match self.0 {
715                     $(
716                         x if x == Self::$variant.0 => format!(concat!("{:",
717                                                                       stringify!($width),
718                                                                       "}"),
719                                                               $short),
720                     )*
721                     v => format!("Unknown({})", v),
722                 }
723             }
724         }
725     }
726 }
727 
728 impl_summary_enum!(AtomID, 14,
729     STORAGE_STATS => "STORAGE",
730     KEYSTORE2_ATOM_WITH_OVERFLOW => "OVERFLOW",
731     KEY_CREATION_WITH_GENERAL_INFO => "KEYGEN_GENERAL",
732     KEY_CREATION_WITH_AUTH_INFO => "KEYGEN_AUTH",
733     KEY_CREATION_WITH_PURPOSE_AND_MODES_INFO => "KEYGEN_MODES",
734     KEY_OPERATION_WITH_PURPOSE_AND_MODES_INFO => "KEYOP_MODES",
735     KEY_OPERATION_WITH_GENERAL_INFO => "KEYOP_GENERAL",
736     RKP_ERROR_STATS => "RKP_ERR",
737     CRASH_STATS => "CRASH",
738 );
739 
740 impl_summary_enum!(MetricsStorage, 28,
741     STORAGE_UNSPECIFIED => "UNSPECIFIED",
742     KEY_ENTRY => "KEY_ENTRY",
743     KEY_ENTRY_ID_INDEX => "KEY_ENTRY_ID_IDX" ,
744     KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => "KEY_ENTRY_DOMAIN_NS_IDX" ,
745     BLOB_ENTRY => "BLOB_ENTRY",
746     BLOB_ENTRY_KEY_ENTRY_ID_INDEX => "BLOB_ENTRY_KEY_ENTRY_ID_IDX" ,
747     KEY_PARAMETER => "KEY_PARAMETER",
748     KEY_PARAMETER_KEY_ENTRY_ID_INDEX => "KEY_PARAM_KEY_ENTRY_ID_IDX" ,
749     KEY_METADATA => "KEY_METADATA",
750     KEY_METADATA_KEY_ENTRY_ID_INDEX => "KEY_META_KEY_ENTRY_ID_IDX" ,
751     GRANT => "GRANT",
752     AUTH_TOKEN => "AUTH_TOKEN",
753     BLOB_METADATA => "BLOB_METADATA",
754     BLOB_METADATA_BLOB_ENTRY_ID_INDEX => "BLOB_META_BLOB_ENTRY_ID_IDX" ,
755     METADATA => "METADATA",
756     DATABASE => "DATABASE",
757     LEGACY_STORAGE => "LEGACY_STORAGE",
758 );
759 
760 impl_summary_enum!(MetricsAlgorithm, 4,
761     ALGORITHM_UNSPECIFIED => "NONE",
762     RSA => "RSA",
763     EC => "EC",
764     AES => "AES",
765     TRIPLE_DES => "DES",
766     HMAC => "HMAC",
767 );
768 
769 impl_summary_enum!(MetricsEcCurve, 5,
770     EC_CURVE_UNSPECIFIED => "NONE",
771     P_224 => "P-224",
772     P_256 => "P-256",
773     P_384 => "P-384",
774     P_521 => "P-521",
775     CURVE_25519 => "25519",
776 );
777 
778 impl_summary_enum!(MetricsKeyOrigin, 10,
779     ORIGIN_UNSPECIFIED => "UNSPEC",
780     GENERATED => "GENERATED",
781     DERIVED => "DERIVED",
782     IMPORTED => "IMPORTED",
783     RESERVED => "RESERVED",
784     SECURELY_IMPORTED => "SEC-IMPORT",
785 );
786 
787 impl_summary_enum!(MetricsSecurityLevel, 9,
788     SECURITY_LEVEL_UNSPECIFIED => "UNSPEC",
789     SECURITY_LEVEL_SOFTWARE => "SOFTWARE",
790     SECURITY_LEVEL_TRUSTED_ENVIRONMENT => "TEE",
791     SECURITY_LEVEL_STRONGBOX => "STRONGBOX",
792     SECURITY_LEVEL_KEYSTORE => "KEYSTORE",
793 );
794 
795 // Metrics values for HardwareAuthenticatorType are broken -- the AIDL type is a bitmask
796 // not an enum, so offseting the enum values by 1 doesn't work.
797 impl_summary_enum!(MetricsHardwareAuthenticatorType, 6,
798     AUTH_TYPE_UNSPECIFIED => "UNSPEC",
799     NONE => "NONE",
800     PASSWORD => "PASSWD",
801     FINGERPRINT => "FPRINT",
802     ANY => "ANY",
803 );
804 
805 impl_summary_enum!(MetricsPurpose, 7,
806     KEY_PURPOSE_UNSPECIFIED => "UNSPEC",
807     ENCRYPT => "ENCRYPT",
808     DECRYPT => "DECRYPT",
809     SIGN => "SIGN",
810     VERIFY => "VERIFY",
811     WRAP_KEY => "WRAPKEY",
812     AGREE_KEY => "AGREEKY",
813     ATTEST_KEY => "ATTESTK",
814 );
815 
816 impl_summary_enum!(MetricsOutcome, 7,
817     OUTCOME_UNSPECIFIED => "UNSPEC",
818     DROPPED => "DROPPED",
819     SUCCESS => "SUCCESS",
820     ABORT => "ABORT",
821     PRUNED => "PRUNED",
822     ERROR => "ERROR",
823 );
824 
825 impl_summary_enum!(MetricsRkpError, 6,
826     RKP_ERROR_UNSPECIFIED => "UNSPEC",
827     OUT_OF_KEYS => "OOKEYS",
828     FALL_BACK_DURING_HYBRID => "FALLBK",
829 );
830 
831 /// Convert an argument into a corresponding format clause.  (This is needed because
832 /// macro expansion text for repeated inputs needs to mention one of the repeated
833 /// inputs.)
834 macro_rules! format_clause {
835     {  $ignored:ident } => { "{}" }
836 }
837 
838 /// Generate code to print a string corresponding to a bitmask, where the given
839 /// enum identifies which bits mean what.  If additional bits (not included in
840 /// the enum variants) are set, include the whole bitmask in the output so no
841 /// information is lost.
842 macro_rules! show_enum_bitmask {
843     {  $v:expr, $enum:ident, $( $variant:ident => $short:literal ),+ $(,)? } => {
844         {
845             let v: i32 = $v;
846             let mut displayed_mask = 0i32;
847             $(
848                 displayed_mask |= 1 << $enum::$variant as i32;
849             )*
850             let undisplayed_mask = !displayed_mask;
851             let undisplayed = v & undisplayed_mask;
852             let extra = if undisplayed == 0 {
853                 "".to_string()
854             } else {
855                 format!("(full:{v:#010x})")
856             };
857             format!(
858                 concat!( $( format_clause!($variant), )* "{}"),
859                 $(
860                     if v & 1 << $enum::$variant as i32 != 0 { $short } else { "-" },
861                 )*
862                 extra
863             )
864         }
865     }
866 }
867 
show_purpose(v: i32) -> String868 fn show_purpose(v: i32) -> String {
869     show_enum_bitmask!(v, KeyPurposeBitPosition,
870         ATTEST_KEY_BIT_POS => "A",
871         AGREE_KEY_BIT_POS => "G",
872         WRAP_KEY_BIT_POS => "W",
873         VERIFY_BIT_POS => "V",
874         SIGN_BIT_POS => "S",
875         DECRYPT_BIT_POS => "D",
876         ENCRYPT_BIT_POS => "E",
877     )
878 }
879 
show_padding(v: i32) -> String880 fn show_padding(v: i32) -> String {
881     show_enum_bitmask!(v, PaddingModeBitPosition,
882         PKCS7_BIT_POS => "7",
883         RSA_PKCS1_1_5_SIGN_BIT_POS => "S",
884         RSA_PKCS1_1_5_ENCRYPT_BIT_POS => "E",
885         RSA_PSS_BIT_POS => "P",
886         RSA_OAEP_BIT_POS => "O",
887         NONE_BIT_POSITION => "N",
888     )
889 }
890 
show_digest(v: i32) -> String891 fn show_digest(v: i32) -> String {
892     show_enum_bitmask!(v, DigestBitPosition,
893         SHA_2_512_BIT_POS => "5",
894         SHA_2_384_BIT_POS => "3",
895         SHA_2_256_BIT_POS => "2",
896         SHA_2_224_BIT_POS => "4",
897         SHA_1_BIT_POS => "1",
898         MD5_BIT_POS => "M",
899         NONE_BIT_POSITION => "N",
900     )
901 }
902 
show_blockmode(v: i32) -> String903 fn show_blockmode(v: i32) -> String {
904     show_enum_bitmask!(v, BlockModeBitPosition,
905         GCM_BIT_POS => "G",
906         CTR_BIT_POS => "T",
907         CBC_BIT_POS => "C",
908         ECB_BIT_POS => "E",
909     )
910 }
911 
912 impl Summary for KeystoreAtomPayload {
show(&self) -> String913     fn show(&self) -> String {
914         match self {
915             KeystoreAtomPayload::StorageStats(v) => {
916                 format!("{} sz={} unused={}", v.storage_type.show(), v.size, v.unused_size)
917             }
918             KeystoreAtomPayload::KeyCreationWithGeneralInfo(v) => {
919                 format!(
920                     "{} ksz={:>4} crv={} {} rc={:4} attest? {}",
921                     v.algorithm.show(),
922                     v.key_size,
923                     v.ec_curve.show(),
924                     v.key_origin.show(),
925                     v.error_code,
926                     if v.attestation_requested { "Y" } else { "N" }
927                 )
928             }
929             KeystoreAtomPayload::KeyCreationWithAuthInfo(v) => {
930                 format!(
931                     "auth={} log(time)={:3} sec={}",
932                     v.user_auth_type.show(),
933                     v.log10_auth_key_timeout_seconds,
934                     v.security_level.show()
935                 )
936             }
937             KeystoreAtomPayload::KeyCreationWithPurposeAndModesInfo(v) => {
938                 format!(
939                     "{} purpose={} padding={} digest={} blockmode={}",
940                     v.algorithm.show(),
941                     show_purpose(v.purpose_bitmap),
942                     show_padding(v.padding_mode_bitmap),
943                     show_digest(v.digest_bitmap),
944                     show_blockmode(v.block_mode_bitmap),
945                 )
946             }
947             KeystoreAtomPayload::KeyOperationWithGeneralInfo(v) => {
948                 format!(
949                     "{} {:>8} upgraded? {} sec={}",
950                     v.outcome.show(),
951                     v.error_code,
952                     if v.key_upgraded { "Y" } else { "N" },
953                     v.security_level.show()
954                 )
955             }
956             KeystoreAtomPayload::KeyOperationWithPurposeAndModesInfo(v) => {
957                 format!(
958                     "{} padding={} digest={} blockmode={}",
959                     v.purpose.show(),
960                     show_padding(v.padding_mode_bitmap),
961                     show_digest(v.digest_bitmap),
962                     show_blockmode(v.block_mode_bitmap)
963                 )
964             }
965             KeystoreAtomPayload::RkpErrorStats(v) => {
966                 format!("{} sec={}", v.rkpError.show(), v.security_level.show())
967             }
968             KeystoreAtomPayload::CrashStats(v) => {
969                 format!("count={}", v.count_of_crash_events)
970             }
971             KeystoreAtomPayload::Keystore2AtomWithOverflow(v) => {
972                 format!("atom={}", v.atom_id.show())
973             }
974         }
975     }
976 }
977 
978 #[cfg(test)]
979 mod tests {
980     use super::*;
981 
982     #[test]
test_enum_show()983     fn test_enum_show() {
984         let algo = MetricsAlgorithm::RSA;
985         assert_eq!("RSA ", algo.show());
986         let algo = MetricsAlgorithm(42);
987         assert_eq!("Unknown(42)", algo.show());
988     }
989 
990     #[test]
test_enum_bitmask_show()991     fn test_enum_bitmask_show() {
992         let mut modes = 0i32;
993         compute_block_mode_bitmap(&mut modes, BlockMode::ECB);
994         compute_block_mode_bitmap(&mut modes, BlockMode::CTR);
995 
996         assert_eq!(show_blockmode(modes), "-T-E");
997 
998         // Add some bits not covered by the enum of valid bit positions.
999         modes |= 0xa0;
1000         assert_eq!(show_blockmode(modes), "-T-E(full:0x000000aa)");
1001         modes |= 0x300;
1002         assert_eq!(show_blockmode(modes), "-T-E(full:0x000003aa)");
1003     }
1004 }
1005