• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022, 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 use nix::unistd::getuid;
16 
17 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
18     Algorithm::Algorithm, BlockMode::BlockMode, Digest::Digest, EcCurve::EcCurve,
19     ErrorCode::ErrorCode, KeyPurpose::KeyPurpose, PaddingMode::PaddingMode,
20     SecurityLevel::SecurityLevel, Tag::Tag,
21 };
22 use android_system_keystore2::aidl::android::system::keystore2::{
23     Domain::Domain, IKeystoreService::IKeystoreService, KeyDescriptor::KeyDescriptor,
24     ResponseCode::ResponseCode,
25 };
26 
27 use keystore2_test_utils::{
28     authorizations, get_keystore_service, key_generations, key_generations::Error,
29 };
30 
31 use keystore2_test_utils::ffi_test_utils::{get_value_from_attest_record, validate_certchain};
32 
33 use crate::{
34     skip_device_id_attestation_tests, skip_test_if_no_app_attest_key_feature,
35     skip_test_if_no_device_id_attestation_feature,
36 };
37 
38 use crate::keystore2_client_test_utils::{
39     app_attest_key_feature_exists, device_id_attestation_feature_exists, get_attest_id_value,
40     is_second_imei_id_attestation_required, skip_device_id_attest_tests,
41 };
42 
43 /// Generate RSA and EC attestation keys and use them for signing RSA-signing keys.
44 /// Test should be able to generate attestation keys and use them successfully.
45 #[test]
keystore2_attest_rsa_signing_key_success()46 fn keystore2_attest_rsa_signing_key_success() {
47     skip_test_if_no_app_attest_key_feature!();
48 
49     let keystore2 = get_keystore_service();
50     let sec_level = keystore2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
51     let att_challenge: &[u8] = b"foo";
52 
53     for algo in [Algorithm::RSA, Algorithm::EC] {
54         // Create attestation key.
55         let attestation_key_metadata =
56             key_generations::generate_attestation_key(&sec_level, algo, att_challenge).unwrap();
57 
58         let mut cert_chain: Vec<u8> = Vec::new();
59         cert_chain.extend(attestation_key_metadata.certificate.as_ref().unwrap());
60         cert_chain.extend(attestation_key_metadata.certificateChain.as_ref().unwrap());
61         validate_certchain(&cert_chain).expect("Error while validating cert chain.");
62 
63         // Create RSA signing key and use attestation key to sign it.
64         let sign_key_alias = format!("ks_attest_rsa_signing_key_{}", getuid());
65         let sign_key_metadata = key_generations::generate_rsa_key(
66             &sec_level,
67             Domain::APP,
68             -1,
69             Some(sign_key_alias),
70             &key_generations::KeyParams {
71                 key_size: 2048,
72                 purpose: vec![KeyPurpose::SIGN, KeyPurpose::VERIFY],
73                 padding: Some(PaddingMode::RSA_PKCS1_1_5_SIGN),
74                 digest: Some(Digest::SHA_2_256),
75                 mgf_digest: None,
76                 block_mode: None,
77                 att_challenge: Some(att_challenge.to_vec()),
78             },
79             Some(&attestation_key_metadata.key),
80         )
81         .unwrap();
82 
83         let mut cert_chain: Vec<u8> = Vec::new();
84         cert_chain.extend(sign_key_metadata.certificate.as_ref().unwrap());
85         cert_chain.extend(attestation_key_metadata.certificate.as_ref().unwrap());
86         cert_chain.extend(attestation_key_metadata.certificateChain.as_ref().unwrap());
87         validate_certchain(&cert_chain).expect("Error while validating cert chain");
88     }
89 }
90 
91 /// Generate RSA and EC attestation keys and use them for signing RSA encrypt/decrypt keys.
92 /// Test should be able to generate attestation keys and use them successfully.
93 #[test]
keystore2_attest_rsa_encrypt_key_success()94 fn keystore2_attest_rsa_encrypt_key_success() {
95     skip_test_if_no_app_attest_key_feature!();
96 
97     let keystore2 = get_keystore_service();
98     let sec_level = keystore2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
99     let att_challenge: &[u8] = b"foo";
100 
101     for algo in [Algorithm::RSA, Algorithm::EC] {
102         // Create attestation key.
103         let attestation_key_metadata =
104             key_generations::generate_attestation_key(&sec_level, algo, att_challenge).unwrap();
105 
106         let mut cert_chain: Vec<u8> = Vec::new();
107         cert_chain.extend(attestation_key_metadata.certificate.as_ref().unwrap());
108         cert_chain.extend(attestation_key_metadata.certificateChain.as_ref().unwrap());
109         validate_certchain(&cert_chain).expect("Error while validating cert chain.");
110 
111         // Create RSA encrypt/decrypt key and use attestation key to sign it.
112         let decrypt_key_alias = format!("ks_attest_rsa_encrypt_key_{}", getuid());
113         let decrypt_key_metadata = key_generations::generate_rsa_key(
114             &sec_level,
115             Domain::APP,
116             -1,
117             Some(decrypt_key_alias),
118             &key_generations::KeyParams {
119                 key_size: 2048,
120                 purpose: vec![KeyPurpose::ENCRYPT, KeyPurpose::DECRYPT],
121                 padding: Some(PaddingMode::RSA_PKCS1_1_5_ENCRYPT),
122                 digest: Some(Digest::SHA_2_256),
123                 mgf_digest: None,
124                 block_mode: None,
125                 att_challenge: Some(att_challenge.to_vec()),
126             },
127             Some(&attestation_key_metadata.key),
128         )
129         .unwrap();
130 
131         let mut cert_chain: Vec<u8> = Vec::new();
132         cert_chain.extend(decrypt_key_metadata.certificate.as_ref().unwrap());
133         cert_chain.extend(attestation_key_metadata.certificate.as_ref().unwrap());
134         cert_chain.extend(attestation_key_metadata.certificateChain.as_ref().unwrap());
135 
136         validate_certchain(&cert_chain).expect("Error while validating cert chain.");
137     }
138 }
139 
140 /// Generate RSA and EC attestation keys and use them for signing EC keys.
141 /// Test should be able to generate attestation keys and use them successfully.
142 #[test]
keystore2_attest_ec_key_success()143 fn keystore2_attest_ec_key_success() {
144     skip_test_if_no_app_attest_key_feature!();
145 
146     let keystore2 = get_keystore_service();
147     let sec_level = keystore2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
148     let att_challenge: &[u8] = b"foo";
149 
150     for algo in [Algorithm::RSA, Algorithm::EC] {
151         // Create attestation key.
152         let attestation_key_metadata =
153             key_generations::generate_attestation_key(&sec_level, algo, att_challenge).unwrap();
154 
155         let mut cert_chain: Vec<u8> = Vec::new();
156         cert_chain.extend(attestation_key_metadata.certificate.as_ref().unwrap());
157         cert_chain.extend(attestation_key_metadata.certificateChain.as_ref().unwrap());
158         validate_certchain(&cert_chain).expect("Error while validating cert chain.");
159 
160         // Create EC key and use attestation key to sign it.
161         let ec_key_alias = format!("ks_ec_attested_test_key_{}", getuid());
162         let ec_key_metadata = key_generations::generate_ec_256_attested_key(
163             &sec_level,
164             Some(ec_key_alias),
165             att_challenge,
166             &attestation_key_metadata.key,
167         )
168         .unwrap();
169 
170         let mut cert_chain: Vec<u8> = Vec::new();
171         cert_chain.extend(ec_key_metadata.certificate.as_ref().unwrap());
172         cert_chain.extend(attestation_key_metadata.certificate.as_ref().unwrap());
173         cert_chain.extend(attestation_key_metadata.certificateChain.as_ref().unwrap());
174 
175         validate_certchain(&cert_chain).expect("Error while validating cert chain.");
176     }
177 }
178 
179 /// Generate EC-CURVE_25519 attestation key and use it for signing RSA-signing keys.
180 /// Test should be able to generate RSA signing key with EC-CURVE_25519 as attestation key
181 /// successfully.
182 #[test]
keystore2_attest_rsa_signing_key_with_ec_25519_key_success()183 fn keystore2_attest_rsa_signing_key_with_ec_25519_key_success() {
184     skip_test_if_no_app_attest_key_feature!();
185 
186     let keystore2 = get_keystore_service();
187     let sec_level = keystore2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
188     let att_challenge: &[u8] = b"foo";
189 
190     // Create EcCurve::CURVE_25519 attestation key.
191     let attestation_key_metadata = key_generations::generate_ec_attestation_key(
192         &sec_level,
193         att_challenge,
194         Digest::NONE,
195         EcCurve::CURVE_25519,
196     )
197     .unwrap();
198 
199     let mut cert_chain: Vec<u8> = Vec::new();
200     cert_chain.extend(attestation_key_metadata.certificate.as_ref().unwrap());
201     cert_chain.extend(attestation_key_metadata.certificateChain.as_ref().unwrap());
202     validate_certchain(&cert_chain).expect("Error while validating cert chain.");
203 
204     // Create RSA signing key and use attestation key to sign it.
205     let sign_key_alias = format!("ksrsa_attested_sign_test_key_{}", getuid());
206     let sign_key_metadata = key_generations::generate_rsa_key(
207         &sec_level,
208         Domain::APP,
209         -1,
210         Some(sign_key_alias),
211         &key_generations::KeyParams {
212             key_size: 2048,
213             purpose: vec![KeyPurpose::SIGN, KeyPurpose::VERIFY],
214             padding: Some(PaddingMode::RSA_PKCS1_1_5_SIGN),
215             digest: Some(Digest::SHA_2_256),
216             mgf_digest: None,
217             block_mode: None,
218             att_challenge: Some(att_challenge.to_vec()),
219         },
220         Some(&attestation_key_metadata.key),
221     )
222     .unwrap();
223 
224     let mut cert_chain: Vec<u8> = Vec::new();
225     cert_chain.extend(sign_key_metadata.certificate.as_ref().unwrap());
226     cert_chain.extend(attestation_key_metadata.certificate.as_ref().unwrap());
227     cert_chain.extend(attestation_key_metadata.certificateChain.as_ref().unwrap());
228     validate_certchain(&cert_chain).expect("Error while validating cert chain");
229 }
230 
231 /// Try to generate RSA attestation key with multiple purposes. Test should fail with error code
232 /// `INCOMPATIBLE_PURPOSE` to generate an attestation key.
233 #[test]
keystore2_generate_rsa_attest_key_with_multi_purpose_fail()234 fn keystore2_generate_rsa_attest_key_with_multi_purpose_fail() {
235     skip_test_if_no_app_attest_key_feature!();
236 
237     let keystore2 = get_keystore_service();
238     let sec_level = keystore2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
239 
240     let digest = Digest::SHA_2_256;
241     let padding = PaddingMode::RSA_PKCS1_1_5_SIGN;
242     let key_size = 2048;
243 
244     let attest_key_alias =
245         format!("ksrsa_attest_multipurpose_key_{}{}{}", getuid(), key_size, digest.0);
246 
247     let attest_gen_params = authorizations::AuthSetBuilder::new()
248         .no_auth_required()
249         .algorithm(Algorithm::RSA)
250         .purpose(KeyPurpose::ATTEST_KEY)
251         .purpose(KeyPurpose::SIGN)
252         .purpose(KeyPurpose::VERIFY)
253         .digest(digest)
254         .key_size(key_size)
255         .rsa_public_exponent(65537)
256         .padding_mode(padding);
257 
258     let result = key_generations::map_ks_error(sec_level.generateKey(
259         &KeyDescriptor {
260             domain: Domain::APP,
261             nspace: -1,
262             alias: Some(attest_key_alias),
263             blob: None,
264         },
265         None,
266         &attest_gen_params,
267         0,
268         b"entropy",
269     ));
270     assert!(result.is_err());
271     assert_eq!(Error::Km(ErrorCode::INCOMPATIBLE_PURPOSE), result.unwrap_err());
272 }
273 
274 /// Try to generate EC attestation key with multiple purposes. Test should fail with error code
275 /// `INCOMPATIBLE_PURPOSE` to generate an attestation key.
276 #[test]
keystore2_ec_attest_key_with_multi_purpose_fail()277 fn keystore2_ec_attest_key_with_multi_purpose_fail() {
278     skip_test_if_no_app_attest_key_feature!();
279 
280     let keystore2 = get_keystore_service();
281     let sec_level = keystore2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
282 
283     let attest_key_alias = format!("ks_ec_attest_multipurpose_key_{}", getuid());
284 
285     let attest_gen_params = authorizations::AuthSetBuilder::new()
286         .no_auth_required()
287         .algorithm(Algorithm::EC)
288         .purpose(KeyPurpose::ATTEST_KEY)
289         .purpose(KeyPurpose::SIGN)
290         .purpose(KeyPurpose::VERIFY)
291         .digest(Digest::SHA_2_256)
292         .ec_curve(EcCurve::P_256);
293 
294     let result = key_generations::map_ks_error(sec_level.generateKey(
295         &KeyDescriptor {
296             domain: Domain::APP,
297             nspace: -1,
298             alias: Some(attest_key_alias),
299             blob: None,
300         },
301         None,
302         &attest_gen_params,
303         0,
304         b"entropy",
305     ));
306     assert!(result.is_err());
307     assert_eq!(Error::Km(ErrorCode::INCOMPATIBLE_PURPOSE), result.unwrap_err());
308 }
309 
310 /// Generate RSA attestation key and try to use it for signing RSA key without providing
311 /// attestation challenge. Test should fail to generate a key with error code
312 /// `ATTESTATION_CHALLENGE_MISSING`.
313 #[test]
keystore2_attest_key_fails_missing_challenge()314 fn keystore2_attest_key_fails_missing_challenge() {
315     skip_test_if_no_app_attest_key_feature!();
316 
317     let keystore2 = get_keystore_service();
318     let sec_level = keystore2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
319     let att_challenge: &[u8] = b"foo";
320 
321     // Create RSA attestation key.
322     let attestation_key_metadata =
323         key_generations::generate_attestation_key(&sec_level, Algorithm::RSA, att_challenge)
324             .unwrap();
325 
326     let mut cert_chain: Vec<u8> = Vec::new();
327     cert_chain.extend(attestation_key_metadata.certificate.as_ref().unwrap());
328     cert_chain.extend(attestation_key_metadata.certificateChain.as_ref().unwrap());
329     validate_certchain(&cert_chain).expect("Error while validating cert chain.");
330 
331     // Try to attest RSA signing key without providing attestation challenge.
332     let sign_key_alias = format!("ksrsa_attested_test_key_missing_challenge{}", getuid());
333     let result = key_generations::map_ks_error(key_generations::generate_rsa_key(
334         &sec_level,
335         Domain::APP,
336         -1,
337         Some(sign_key_alias),
338         &key_generations::KeyParams {
339             key_size: 2048,
340             purpose: vec![KeyPurpose::SIGN, KeyPurpose::VERIFY],
341             padding: Some(PaddingMode::RSA_PKCS1_1_5_SIGN),
342             digest: Some(Digest::SHA_2_256),
343             mgf_digest: None,
344             block_mode: None,
345             att_challenge: None,
346         },
347         Some(&attestation_key_metadata.key),
348     ));
349     assert!(result.is_err());
350     assert_eq!(Error::Km(ErrorCode::ATTESTATION_CHALLENGE_MISSING), result.unwrap_err());
351 }
352 
353 /// Generate an asymmetric key which doesn't possess ATTEST_KEY purpose. Try to use this key as
354 /// attestation key while generating RSA key. Test should fail to generate a key with error
355 /// code `INCOMPATIBLE_PURPOSE`.
356 #[test]
keystore2_attest_rsa_key_with_non_attest_key_fails_incompat_purpose_error()357 fn keystore2_attest_rsa_key_with_non_attest_key_fails_incompat_purpose_error() {
358     skip_test_if_no_app_attest_key_feature!();
359 
360     let keystore2 = get_keystore_service();
361     let sec_level = keystore2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
362     let att_challenge: &[u8] = b"foo";
363 
364     let alias = format!("non_attest_key_{}", getuid());
365     let non_attest_key_metadata = key_generations::generate_ec_p256_signing_key(
366         &sec_level,
367         Domain::APP,
368         -1,
369         Some(alias),
370         None,
371     )
372     .unwrap();
373 
374     // Try to generate RSA signing key with non-attestation key to sign it.
375     let sign_key_alias = format!("ksrsa_attested_sign_test_key_non_attest_{}", getuid());
376     let result = key_generations::map_ks_error(key_generations::generate_rsa_key(
377         &sec_level,
378         Domain::APP,
379         -1,
380         Some(sign_key_alias),
381         &key_generations::KeyParams {
382             key_size: 2048,
383             purpose: vec![KeyPurpose::SIGN, KeyPurpose::VERIFY],
384             padding: Some(PaddingMode::RSA_PKCS1_1_5_SIGN),
385             digest: Some(Digest::SHA_2_256),
386             mgf_digest: None,
387             block_mode: None,
388             att_challenge: Some(att_challenge.to_vec()),
389         },
390         Some(&non_attest_key_metadata.key),
391     ));
392     assert!(result.is_err());
393     assert_eq!(Error::Km(ErrorCode::INCOMPATIBLE_PURPOSE), result.unwrap_err());
394 }
395 
396 /// Generate a symmetric key. Try to use this symmetric key as attestation key while generating RSA
397 /// key. Test should fail to generate a key with response code `INVALID_ARGUMENT`.
398 #[test]
keystore2_attest_rsa_key_with_symmetric_key_fails_sys_error()399 fn keystore2_attest_rsa_key_with_symmetric_key_fails_sys_error() {
400     skip_test_if_no_app_attest_key_feature!();
401 
402     let keystore2 = get_keystore_service();
403     let sec_level = keystore2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
404     let att_challenge: &[u8] = b"foo";
405 
406     let alias = "aes_attest_key";
407     let sym_key_metadata = key_generations::generate_sym_key(
408         &sec_level,
409         Algorithm::AES,
410         128,
411         alias,
412         &PaddingMode::NONE,
413         &BlockMode::ECB,
414         None,
415     )
416     .unwrap();
417 
418     // Try to generate RSA signing key with symmetric key as attestation key.
419     let sign_key_alias = format!("ksrsa_attested_sign_test_key_sym_attest_{}", getuid());
420     let result = key_generations::map_ks_error(key_generations::generate_rsa_key(
421         &sec_level,
422         Domain::APP,
423         -1,
424         Some(sign_key_alias),
425         &key_generations::KeyParams {
426             key_size: 2048,
427             purpose: vec![KeyPurpose::SIGN, KeyPurpose::VERIFY],
428             padding: Some(PaddingMode::RSA_PKCS1_1_5_SIGN),
429             digest: Some(Digest::SHA_2_256),
430             mgf_digest: None,
431             block_mode: None,
432             att_challenge: Some(att_challenge.to_vec()),
433         },
434         Some(&sym_key_metadata.key),
435     ));
436     assert!(result.is_err());
437     assert_eq!(Error::Rc(ResponseCode::INVALID_ARGUMENT), result.unwrap_err());
438 }
439 
440 /// Generate RSA attestation key and try to use it as attestation key while generating symmetric
441 /// key. Test should generate symmetric key successfully. Verify that generated symmetric key
442 /// should not have attestation record or certificate.
443 #[test]
keystore2_attest_symmetric_key_fail_sys_error()444 fn keystore2_attest_symmetric_key_fail_sys_error() {
445     skip_test_if_no_app_attest_key_feature!();
446 
447     let keystore2 = get_keystore_service();
448     let sec_level = keystore2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
449     let att_challenge: &[u8] = b"foo";
450 
451     // Create attestation key.
452     let attestation_key_metadata =
453         key_generations::generate_attestation_key(&sec_level, Algorithm::RSA, att_challenge)
454             .unwrap();
455 
456     let mut cert_chain: Vec<u8> = Vec::new();
457     cert_chain.extend(attestation_key_metadata.certificate.as_ref().unwrap());
458     cert_chain.extend(attestation_key_metadata.certificateChain.as_ref().unwrap());
459     validate_certchain(&cert_chain).expect("Error while validating cert chain.");
460 
461     // Generate symmetric key with above generated key as attestation key.
462     let gen_params = authorizations::AuthSetBuilder::new()
463         .no_auth_required()
464         .algorithm(Algorithm::AES)
465         .purpose(KeyPurpose::ENCRYPT)
466         .purpose(KeyPurpose::DECRYPT)
467         .key_size(128)
468         .padding_mode(PaddingMode::NONE)
469         .block_mode(BlockMode::ECB)
470         .attestation_challenge(att_challenge.to_vec());
471 
472     let alias = format!("ks_test_sym_key_attest_{}", getuid());
473     let aes_key_metadata = sec_level
474         .generateKey(
475             &KeyDescriptor { domain: Domain::APP, nspace: -1, alias: Some(alias), blob: None },
476             Some(&attestation_key_metadata.key),
477             &gen_params,
478             0,
479             b"entropy",
480         )
481         .unwrap();
482 
483     // Should not have public certificate.
484     assert!(aes_key_metadata.certificate.is_none());
485 
486     // Should not have an attestation record.
487     assert!(aes_key_metadata.certificateChain.is_none());
488 }
489 
get_attestation_ids(keystore2: &binder::Strong<dyn IKeystoreService>) -> Vec<(Tag, Vec<u8>)>490 fn get_attestation_ids(keystore2: &binder::Strong<dyn IKeystoreService>) -> Vec<(Tag, Vec<u8>)> {
491     let attest_ids = vec![
492         (Tag::ATTESTATION_ID_BRAND, "brand"),
493         (Tag::ATTESTATION_ID_DEVICE, "device"),
494         (Tag::ATTESTATION_ID_PRODUCT, "name"),
495         (Tag::ATTESTATION_ID_SERIAL, "serialno"),
496         (Tag::ATTESTATION_ID_MANUFACTURER, "manufacturer"),
497         (Tag::ATTESTATION_ID_MODEL, "model"),
498         (Tag::ATTESTATION_ID_IMEI, ""), //Get this value from Telephony service.
499         (Tag::ATTESTATION_ID_SECOND_IMEI, ""), //Get this value from Telephony service.
500     ];
501 
502     let mut attest_id_params: Vec<(Tag, Vec<u8>)> = vec![];
503     for (attest_id, prop_name) in attest_ids {
504         if attest_id == Tag::ATTESTATION_ID_SECOND_IMEI
505             && !is_second_imei_id_attestation_required(keystore2)
506         {
507             continue;
508         }
509 
510         if let Some(value) = get_attest_id_value(attest_id, prop_name) {
511             if !value.is_empty() {
512                 attest_id_params.push((attest_id, value));
513             }
514         }
515     }
516 
517     attest_id_params
518 }
519 
520 /// Generate an attested key with attestation of the device's identifiers. Test should succeed in
521 /// generating a attested key with attestation of device identifiers. Test might fail on devices
522 /// which don't support device id attestation with error response code `CANNOT_ATTEST_IDS or
523 /// INVALID_TAG`
generate_attested_key_with_device_attest_ids(algorithm: Algorithm)524 fn generate_attested_key_with_device_attest_ids(algorithm: Algorithm) {
525     skip_test_if_no_device_id_attestation_feature!();
526     skip_device_id_attestation_tests!();
527     skip_test_if_no_app_attest_key_feature!();
528     let keystore2 = get_keystore_service();
529     let sec_level = keystore2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
530 
531     let att_challenge: &[u8] = b"foo";
532 
533     let attest_key_metadata =
534         key_generations::generate_attestation_key(&sec_level, algorithm, att_challenge).unwrap();
535 
536     let attest_id_params = get_attestation_ids(&keystore2);
537 
538     for (attest_id, value) in attest_id_params {
539         // Create RSA/EC key and use attestation key to sign it.
540         let key_alias = format!("ks_attested_test_key_{}", getuid());
541         let key_metadata =
542             key_generations::map_ks_error(key_generations::generate_key_with_attest_id(
543                 &sec_level,
544                 algorithm,
545                 Some(key_alias),
546                 att_challenge,
547                 &attest_key_metadata.key,
548                 attest_id,
549                 value.clone(),
550             ))
551             .unwrap();
552 
553         assert!(key_metadata.certificate.is_some());
554         assert!(key_metadata.certificateChain.is_none());
555 
556         let mut cert_chain: Vec<u8> = Vec::new();
557         cert_chain.extend(key_metadata.certificate.as_ref().unwrap());
558         cert_chain.extend(attest_key_metadata.certificate.as_ref().unwrap());
559         cert_chain.extend(attest_key_metadata.certificateChain.as_ref().unwrap());
560 
561         validate_certchain(&cert_chain).expect("Error while validating cert chain");
562         let attest_id_value = get_value_from_attest_record(
563             key_metadata.certificate.as_ref().unwrap(),
564             attest_id,
565             SecurityLevel::TRUSTED_ENVIRONMENT,
566         )
567         .expect("Attest id verification failed.");
568         assert_eq!(attest_id_value, value);
569     }
570 }
571 
572 #[test]
keystore2_attest_ecdsa_attestation_id()573 fn keystore2_attest_ecdsa_attestation_id() {
574     generate_attested_key_with_device_attest_ids(Algorithm::EC);
575 }
576 
577 #[test]
keystore2_attest_rsa_attestation_id()578 fn keystore2_attest_rsa_attestation_id() {
579     generate_attested_key_with_device_attest_ids(Algorithm::RSA);
580 }
581 
582 /// Try to generate an attested key with attestation of invalid device's identifiers. Test should
583 /// fail with error response code `CANNOT_ATTEST_IDS`.
584 #[test]
keystore2_attest_key_fails_with_invalid_attestation_id()585 fn keystore2_attest_key_fails_with_invalid_attestation_id() {
586     skip_test_if_no_device_id_attestation_feature!();
587 
588     let keystore2 = get_keystore_service();
589     let sec_level = keystore2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
590 
591     let digest = Digest::SHA_2_256;
592     let att_challenge: &[u8] = b"foo";
593 
594     // Create EC-Attestation key.
595     let attest_key_metadata = key_generations::generate_ec_attestation_key(
596         &sec_level,
597         att_challenge,
598         digest,
599         EcCurve::P_256,
600     )
601     .unwrap();
602 
603     let attest_id_params = vec![
604         (Tag::ATTESTATION_ID_BRAND, b"invalid-brand".to_vec()),
605         (Tag::ATTESTATION_ID_DEVICE, b"invalid-device-name".to_vec()),
606         (Tag::ATTESTATION_ID_PRODUCT, b"invalid-product-name".to_vec()),
607         (Tag::ATTESTATION_ID_SERIAL, b"invalid-ro-serial".to_vec()),
608         (Tag::ATTESTATION_ID_MANUFACTURER, b"invalid-ro-product-manufacturer".to_vec()),
609         (Tag::ATTESTATION_ID_MODEL, b"invalid-ro-product-model".to_vec()),
610         (Tag::ATTESTATION_ID_IMEI, b"invalid-imei".to_vec()),
611     ];
612 
613     for (attest_id, value) in attest_id_params {
614         // Create EC key and use attestation key to sign it.
615         let ec_key_alias = format!("ks_ec_attested_test_key_fail_{}{}", getuid(), digest.0);
616         let result = key_generations::map_ks_error(key_generations::generate_key_with_attest_id(
617             &sec_level,
618             Algorithm::EC,
619             Some(ec_key_alias),
620             att_challenge,
621             &attest_key_metadata.key,
622             attest_id,
623             value,
624         ));
625 
626         assert!(result.is_err());
627         assert_eq!(result.unwrap_err(), Error::Km(ErrorCode::CANNOT_ATTEST_IDS));
628     }
629 }
630 
631 ///  If `DEVICE_ID_ATTESTATION_FEATURE` is not supported then test tries to generate an attested
632 ///  key with attestation of valid device's identifiers. Test should fail to generate key with
633 ///  error code `CANNOT_ATTEST_IDS`.
634 #[test]
keystore2_attest_key_without_attestation_id_support_fails_with_cannot_attest_id()635 fn keystore2_attest_key_without_attestation_id_support_fails_with_cannot_attest_id() {
636     if device_id_attestation_feature_exists() {
637         // Skip this test on device supporting `DEVICE_ID_ATTESTATION_FEATURE`.
638         return;
639     }
640 
641     let keystore2 = get_keystore_service();
642     let sec_level = keystore2.getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT).unwrap();
643 
644     let att_challenge: &[u8] = b"foo";
645     let attest_key_metadata =
646         key_generations::generate_attestation_key(&sec_level, Algorithm::RSA, att_challenge)
647             .unwrap();
648 
649     let attest_id_params = get_attestation_ids(&keystore2);
650     for (attest_id, value) in attest_id_params {
651         // Create RSA/EC key and use attestation key to sign it.
652         let key_alias = format!("ks_attested_test_key_{}", getuid());
653         let result = key_generations::map_ks_error(key_generations::generate_key_with_attest_id(
654             &sec_level,
655             Algorithm::RSA,
656             Some(key_alias),
657             att_challenge,
658             &attest_key_metadata.key,
659             attest_id,
660             value.clone(),
661         ));
662         assert!(
663             result.is_err(),
664             "Expected to fail as FEATURE_DEVICE_ID_ATTESTATION is not supported."
665         );
666         assert_eq!(result.unwrap_err(), Error::Km(ErrorCode::CANNOT_ATTEST_IDS));
667     }
668 }
669