1 #include "ffi_test_utils.hpp"
2 
3 #include <iostream>
4 #include <vector>
5 
6 #include <android-base/logging.h>
7 #include <keymaster/km_openssl/attestation_record.h>
8 #include <keymaster/km_openssl/openssl_err.h>
9 #include <keymaster/km_openssl/openssl_utils.h>
10 #include <keymint_support/attestation_record.h>
11 #include <keymint_support/keymint_utils.h>
12 #include <openssl/mem.h>
13 
14 using keymaster::ASN1_OBJECT_Ptr;
15 using keymaster::EVP_PKEY_Ptr;
16 using keymaster::X509_Ptr;
17 using std::endl;
18 using std::string;
19 using std::vector;
20 
21 #define TAG_SEQUENCE 0x30
22 #define LENGTH_MASK 0x80
23 #define LENGTH_VALUE_MASK 0x7F
24 
25 /* EVP_PKEY_from_keystore is from system/security/keystore-engine. */
26 extern "C" EVP_PKEY* EVP_PKEY_from_keystore(const char* key_id);
27 
28 typedef std::vector<uint8_t> certificate_t;
29 
30 /**
31  * ASN.1 structure for `KeyDescription` Schema.
32  * See `IKeyMintDevice.aidl` for documentation of the `KeyDescription` schema.
33  *    KeyDescription ::= SEQUENCE(
34  *        keyFormat INTEGER,                   # Values from KeyFormat enum.
35  *        keyParams AuthorizationList,
36  *    )
37  */
38 typedef struct key_description {
39     ASN1_INTEGER* key_format;
40     keymaster::KM_AUTH_LIST* key_params;
41 } TEST_KEY_DESCRIPTION;
42 
43 ASN1_SEQUENCE(TEST_KEY_DESCRIPTION) = {
44     ASN1_SIMPLE(TEST_KEY_DESCRIPTION, key_format, ASN1_INTEGER),
45     ASN1_SIMPLE(TEST_KEY_DESCRIPTION, key_params, keymaster::KM_AUTH_LIST),
46 } ASN1_SEQUENCE_END(TEST_KEY_DESCRIPTION);
47 DECLARE_ASN1_FUNCTIONS(TEST_KEY_DESCRIPTION);
48 
49 /**
50  * ASN.1 structure for `SecureKeyWrapper` Schema.
51  * See `IKeyMintDevice.aidl` for documentation of the `SecureKeyWrapper` schema.
52  *    SecureKeyWrapper ::= SEQUENCE(
53  *        version INTEGER,                     # Contains value 0
54  *        encryptedTransportKey OCTET_STRING,
55  *        initializationVector OCTET_STRING,
56  *        keyDescription KeyDescription,
57  *        encryptedKey OCTET_STRING,
58  *        tag OCTET_STRING
59  *    )
60  */
61 typedef struct secure_key_wrapper {
62     ASN1_INTEGER* version;
63     ASN1_OCTET_STRING* encrypted_transport_key;
64     ASN1_OCTET_STRING* initialization_vector;
65     TEST_KEY_DESCRIPTION* key_desc;
66     ASN1_OCTET_STRING* encrypted_key;
67     ASN1_OCTET_STRING* tag;
68 } TEST_SECURE_KEY_WRAPPER;
69 
70 ASN1_SEQUENCE(TEST_SECURE_KEY_WRAPPER) = {
71     ASN1_SIMPLE(TEST_SECURE_KEY_WRAPPER, version, ASN1_INTEGER),
72     ASN1_SIMPLE(TEST_SECURE_KEY_WRAPPER, encrypted_transport_key, ASN1_OCTET_STRING),
73     ASN1_SIMPLE(TEST_SECURE_KEY_WRAPPER, initialization_vector, ASN1_OCTET_STRING),
74     ASN1_SIMPLE(TEST_SECURE_KEY_WRAPPER, key_desc, TEST_KEY_DESCRIPTION),
75     ASN1_SIMPLE(TEST_SECURE_KEY_WRAPPER, encrypted_key, ASN1_OCTET_STRING),
76     ASN1_SIMPLE(TEST_SECURE_KEY_WRAPPER, tag, ASN1_OCTET_STRING),
77 } ASN1_SEQUENCE_END(TEST_SECURE_KEY_WRAPPER);
78 DECLARE_ASN1_FUNCTIONS(TEST_SECURE_KEY_WRAPPER);
79 
80 IMPLEMENT_ASN1_FUNCTIONS(TEST_SECURE_KEY_WRAPPER);
81 IMPLEMENT_ASN1_FUNCTIONS(TEST_KEY_DESCRIPTION);
82 
83 struct TEST_KEY_DESCRIPTION_Delete {
operator ()TEST_KEY_DESCRIPTION_Delete84     void operator()(TEST_KEY_DESCRIPTION* p) { TEST_KEY_DESCRIPTION_free(p); }
85 };
86 struct TEST_SECURE_KEY_WRAPPER_Delete {
operator ()TEST_SECURE_KEY_WRAPPER_Delete87     void operator()(TEST_SECURE_KEY_WRAPPER* p) { TEST_SECURE_KEY_WRAPPER_free(p); }
88 };
89 
90 const std::string keystore2_grant_id_prefix("ks2_keystore-engine_grant_id:");
91 
bin2hex(const vector<uint8_t> & data)92 string bin2hex(const vector<uint8_t>& data) {
93     string retval;
94     char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
95                            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
96     retval.reserve(data.size() * 2 + 1);
97     for (uint8_t byte : data) {
98         retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
99         retval.push_back(nibble2hex[0x0F & byte]);
100     }
101     return retval;
102 }
103 
x509NameToStr(X509_NAME * name)104 string x509NameToStr(X509_NAME* name) {
105     char* s = X509_NAME_oneline(name, nullptr, 0);
106     string retval(s);
107     OPENSSL_free(s);
108     return retval;
109 }
110 
parseCertBlob(const vector<uint8_t> & blob)111 X509_Ptr parseCertBlob(const vector<uint8_t>& blob) {
112     const uint8_t* p = blob.data();
113     return X509_Ptr(d2i_X509(nullptr /* allocate new */, &p, blob.size()));
114 }
115 
116 // Extract attestation record from cert. Returned object is still part of cert; don't free it
117 // separately.
getAttestationRecord(X509 * certificate)118 ASN1_OCTET_STRING* getAttestationRecord(X509* certificate) {
119     ASN1_OBJECT_Ptr oid(OBJ_txt2obj(aidl::android::hardware::security::keymint::kAttestionRecordOid,
120                                     1 /* dotted string format */));
121     if (!oid.get()) return nullptr;
122 
123     int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
124     if (location == -1) return nullptr;
125 
126     X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
127     if (!attest_rec_ext) return nullptr;
128 
129     ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
130     return attest_rec;
131 }
132 
ChainSignaturesAreValid(const vector<certificate_t> & chain,bool strict_issuer_check)133 bool ChainSignaturesAreValid(const vector<certificate_t>& chain, bool strict_issuer_check) {
134     std::stringstream cert_data;
135 
136     for (size_t i = 0; i < chain.size(); ++i) {
137         cert_data << bin2hex(chain[i]) << std::endl;
138 
139         X509_Ptr key_cert(parseCertBlob(chain[i]));
140         X509_Ptr signing_cert;
141         if (i < chain.size() - 1) {
142             signing_cert = parseCertBlob(chain[i + 1]);
143         } else {
144             signing_cert = parseCertBlob(chain[i]);
145         }
146         if (!key_cert.get() || !signing_cert.get()) {
147             LOG(ERROR) << cert_data.str();
148             return false;
149         }
150 
151         EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
152         if (!signing_pubkey.get()) {
153             LOG(ERROR) << cert_data.str();
154             return false;
155         }
156 
157         if (!X509_verify(key_cert.get(), signing_pubkey.get())) {
158             // Handles the case of device-unique attestation chain which is not expected to be
159             // self-signed - b/191361618
160             // For device-unique attestation chain `strict_issuer_check` is not set, so ignore the
161             // root certificate signature verification result and in all other cases return the
162             // error.
163             bool is_root_cert = (i == chain.size() - 1);
164             if (strict_issuer_check || !is_root_cert) {
165                 LOG(ERROR) << "Verification of certificate " << i << " failed "
166                            << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL)
167                            << '\n'
168                            << cert_data.str();
169                 return false;
170             }
171         }
172 
173         string cert_issuer = x509NameToStr(X509_get_issuer_name(key_cert.get()));
174         string signer_subj = x509NameToStr(X509_get_subject_name(signing_cert.get()));
175         if (cert_issuer != signer_subj && strict_issuer_check) {
176             LOG(ERROR) << "Cert " << i << " has wrong issuer.\n"
177                        << " Signer subject is " << signer_subj << " Issuer subject is "
178                        << cert_issuer << endl
179                        << cert_data.str();
180         }
181     }
182 
183     // Dump cert data.
184     LOG(ERROR) << cert_data.str();
185     return true;
186 }
187 
188 /* This function extracts a certificate from the certs_chain_buffer at the given
189  * offset. Each DER encoded certificate starts with TAG_SEQUENCE followed by the
190  * total length of the certificate. The length of the certificate is determined
191  * as per ASN.1 encoding rules for the length octets.
192  *
193  * @param certs_chain_buffer: buffer containing DER encoded X.509 certificates
194  *                            arranged sequentially.
195  * @data_size: Length of the DER encoded X.509 certificates buffer.
196  * @index: DER encoded X.509 certificates buffer offset.
197  * @cert: Encoded certificate to be extracted from buffer as outcome.
198  * @return: true on success, otherwise false.
199  */
extractCertFromCertChainBuffer(uint8_t * certs_chain_buffer,int certs_chain_buffer_size,int & index,certificate_t & cert)200 bool extractCertFromCertChainBuffer(uint8_t* certs_chain_buffer, int certs_chain_buffer_size,
201                                     int& index, certificate_t& cert) {
202     if (index >= certs_chain_buffer_size) {
203         return false;
204     }
205 
206     uint32_t length = 0;
207     std::vector<uint8_t> cert_bytes;
208     if (certs_chain_buffer[index] == TAG_SEQUENCE) {
209         // Short form. One octet. Bit 8 has value "0" and bits 7-1 give the length.
210         if (0 == (certs_chain_buffer[index + 1] & LENGTH_MASK)) {
211             length = (uint32_t)certs_chain_buffer[index];
212             // Add SEQ and Length fields
213             length += 2;
214         } else {
215             // Long form. Two to 127 octets. Bit 8 of first octet has value "1" and
216             // bits 7-1 give the number of additional length octets. Second and following
217             // octets give the actual length.
218             int additionalBytes = certs_chain_buffer[index + 1] & LENGTH_VALUE_MASK;
219             if (additionalBytes == 0x01) {
220                 length = certs_chain_buffer[index + 2];
221                 // Add SEQ and Length fields
222                 length += 3;
223             } else if (additionalBytes == 0x02) {
224                 length = (certs_chain_buffer[index + 2] << 8 | certs_chain_buffer[index + 3]);
225                 // Add SEQ and Length fields
226                 length += 4;
227             } else if (additionalBytes == 0x04) {
228                 length = certs_chain_buffer[index + 2] << 24;
229                 length |= certs_chain_buffer[index + 3] << 16;
230                 length |= certs_chain_buffer[index + 4] << 8;
231                 length |= certs_chain_buffer[index + 5];
232                 // Add SEQ and Length fields
233                 length += 6;
234             } else {
235                 // Length is larger than uint32_t max limit.
236                 return false;
237             }
238         }
239         cert_bytes.insert(cert_bytes.end(), (certs_chain_buffer + index),
240                           (certs_chain_buffer + index + length));
241         index += length;
242 
243         for (int i = 0; i < cert_bytes.size(); i++) {
244             cert = std::move(cert_bytes);
245         }
246     } else {
247         // SEQUENCE TAG MISSING.
248         return false;
249     }
250 
251     return true;
252 }
253 
getCertificateChain(rust::Vec<rust::u8> & chainBuffer,std::vector<certificate_t> & certChain)254 bool getCertificateChain(rust::Vec<rust::u8>& chainBuffer, std::vector<certificate_t>& certChain) {
255     uint8_t* data = chainBuffer.data();
256     int index = 0;
257     int data_size = chainBuffer.size();
258 
259     while (index < data_size) {
260         certificate_t cert;
261         if (!extractCertFromCertChainBuffer(data, data_size, index, cert)) {
262             return false;
263         }
264         certChain.push_back(std::move(cert));
265     }
266     return true;
267 }
268 
validateCertChain(rust::Vec<rust::u8> cert_buf,uint32_t cert_len,bool strict_issuer_check)269 bool validateCertChain(rust::Vec<rust::u8> cert_buf, uint32_t cert_len, bool strict_issuer_check) {
270     std::vector<certificate_t> cert_chain = std::vector<certificate_t>();
271     if (cert_len <= 0) {
272         return false;
273     }
274     if (!getCertificateChain(cert_buf, cert_chain)) {
275         return false;
276     }
277 
278     std::stringstream cert_data;
279     for (int i = 0; i < cert_chain.size(); i++) {
280         cert_data << bin2hex(cert_chain[i]) << std::endl;
281     }
282     LOG(INFO) << cert_data.str() << "\n";
283 
284     return ChainSignaturesAreValid(cert_chain, strict_issuer_check);
285 }
286 
287 /**
288  * Below mentioned key parameters are used to create authorization list of
289  * secure key.
290  *    Algorithm: AES-256
291  *    Padding: PKCS7
292  *    Blockmode: ECB
293  *    Purpose: Encrypt, Decrypt
294  */
build_wrapped_key_auth_list()295 keymaster::AuthorizationSet build_wrapped_key_auth_list() {
296     return keymaster::AuthorizationSet(keymaster::AuthorizationSetBuilder()
297                                            .AesEncryptionKey(256)
298                                            .Authorization(keymaster::TAG_BLOCK_MODE, KM_MODE_ECB)
299                                            .Authorization(keymaster::TAG_PADDING, KM_PAD_PKCS7)
300                                            .Authorization(keymaster::TAG_NO_AUTH_REQUIRED));
301 }
302 
303 /**
304  * Creates ASN.1 DER-encoded data corresponding to `KeyDescription` schema as
305  * AAD. See `IKeyMintDevice.aidl` for documentation of the `KeyDescription` schema.
306  */
buildAsn1DerEncodedWrappedKeyDescription()307 CxxResult buildAsn1DerEncodedWrappedKeyDescription() {
308     CxxResult cxx_result{};
309     keymaster_error_t error;
310     cxx_result.error = KM_ERROR_OK;
311 
312     keymaster::UniquePtr<TEST_KEY_DESCRIPTION, TEST_KEY_DESCRIPTION_Delete> key_description(
313         TEST_KEY_DESCRIPTION_new());
314     if (!key_description.get()) {
315         cxx_result.error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
316         return cxx_result;
317     }
318 
319     // Fill secure key authorizations.
320     keymaster::AuthorizationSet auth_list = build_wrapped_key_auth_list();
321     error = build_auth_list(auth_list, key_description->key_params);
322     if (error != KM_ERROR_OK) {
323         cxx_result.error = error;
324         return cxx_result;
325     }
326 
327     // Fill secure key format.
328     if (!ASN1_INTEGER_set(key_description->key_format, KM_KEY_FORMAT_RAW)) {
329         cxx_result.error = keymaster::TranslateLastOpenSslError();
330         return cxx_result;
331     }
332 
333     // Perform ASN.1 DER encoding of KeyDescription.
334     int asn1_data_len = i2d_TEST_KEY_DESCRIPTION(key_description.get(), nullptr);
335     if (asn1_data_len < 0) {
336         cxx_result.error = keymaster::TranslateLastOpenSslError();
337         return cxx_result;
338     }
339     std::vector<uint8_t> asn1_data(asn1_data_len, 0);
340 
341     if (!asn1_data.data()) {
342         cxx_result.error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
343         return cxx_result;
344     }
345 
346     uint8_t* p = asn1_data.data();
347     asn1_data_len = i2d_TEST_KEY_DESCRIPTION(key_description.get(), &p);
348     if (asn1_data_len < 0) {
349         cxx_result.error = keymaster::TranslateLastOpenSslError();
350         return cxx_result;
351     }
352 
353     std::move(asn1_data.begin(), asn1_data.end(), std::back_inserter(cxx_result.data));
354 
355     return cxx_result;
356 }
357 
358 /**
359  * Creates wrapped key material to import in ASN.1 DER-encoded data corresponding to
360  * `SecureKeyWrapper` schema. See `IKeyMintDevice.aidl` for documentation of the `SecureKeyWrapper`
361  * schema.
362  */
createWrappedKey(rust::Vec<rust::u8> encrypted_secure_key,rust::Vec<rust::u8> encrypted_transport_key,rust::Vec<rust::u8> iv,rust::Vec<rust::u8> tag)363 CxxResult createWrappedKey(rust::Vec<rust::u8> encrypted_secure_key,
364                            rust::Vec<rust::u8> encrypted_transport_key, rust::Vec<rust::u8> iv,
365                            rust::Vec<rust::u8> tag) {
366     CxxResult cxx_result{};
367     keymaster_error_t error;
368     cxx_result.error = false;
369 
370     uint8_t* enc_secure_key_data = encrypted_secure_key.data();
371     int enc_secure_key_size = encrypted_secure_key.size();
372 
373     uint8_t* iv_data = iv.data();
374     int iv_size = iv.size();
375 
376     uint8_t* tag_data = tag.data();
377     int tag_size = tag.size();
378 
379     uint8_t* enc_transport_key_data = encrypted_transport_key.data();
380     int enc_transport_key_size = encrypted_transport_key.size();
381 
382     keymaster::UniquePtr<TEST_SECURE_KEY_WRAPPER, TEST_SECURE_KEY_WRAPPER_Delete> sec_key_wrapper(
383         TEST_SECURE_KEY_WRAPPER_new());
384     if (!sec_key_wrapper.get()) {
385         LOG(ERROR) << "createWrappedKey - Failed to allocate a memory";
386         cxx_result.error = true;
387         return cxx_result;
388     }
389 
390     // Fill version = 0
391     if (!ASN1_INTEGER_set(sec_key_wrapper->version, 0)) {
392         LOG(ERROR) << "createWrappedKey - Error while filling version: "
393                    << keymaster::TranslateLastOpenSslError();
394         cxx_result.error = true;
395         return cxx_result;
396     }
397 
398     // Fill encrypted transport key.
399     if (enc_transport_key_size &&
400         !ASN1_OCTET_STRING_set(sec_key_wrapper->encrypted_transport_key, enc_transport_key_data,
401                                enc_transport_key_size)) {
402         LOG(ERROR) << "createWrappedKey - Error while filling encrypted transport key: "
403                    << keymaster::TranslateLastOpenSslError();
404         cxx_result.error = true;
405         return cxx_result;
406     }
407 
408     // Fill encrypted secure key.
409     if (enc_secure_key_size && !ASN1_OCTET_STRING_set(sec_key_wrapper->encrypted_key,
410                                                       enc_secure_key_data, enc_secure_key_size)) {
411         LOG(ERROR) << "createWrappedKey - Error while filling encrypted secure key: "
412                    << keymaster::TranslateLastOpenSslError();
413         cxx_result.error = true;
414         return cxx_result;
415     }
416 
417     // Fill secure key authorization list.
418     keymaster::AuthorizationSet auth_list = build_wrapped_key_auth_list();
419     error = build_auth_list(auth_list, sec_key_wrapper->key_desc->key_params);
420     if (error != KM_ERROR_OK) {
421         cxx_result.error = true;
422         return cxx_result;
423     }
424 
425     // Fill secure key format.
426     if (!ASN1_INTEGER_set(sec_key_wrapper->key_desc->key_format, KM_KEY_FORMAT_RAW)) {
427         LOG(ERROR) << "createWrappedKey - Error while filling secure key format: "
428                    << keymaster::TranslateLastOpenSslError();
429         cxx_result.error = true;
430         return cxx_result;
431     }
432 
433     // Fill initialization vector used for encrypting secure key.
434     if (iv_size &&
435         !ASN1_OCTET_STRING_set(sec_key_wrapper->initialization_vector, iv_data, iv_size)) {
436         LOG(ERROR) << "createWrappedKey - Error while filling IV: "
437                    << keymaster::TranslateLastOpenSslError();
438         cxx_result.error = true;
439         return cxx_result;
440     }
441 
442     // Fill GCM-tag, extracted during secure key encryption.
443     if (tag_size && !ASN1_OCTET_STRING_set(sec_key_wrapper->tag, tag_data, tag_size)) {
444         LOG(ERROR) << "createWrappedKey - Error while filling GCM-tag: "
445                    << keymaster::TranslateLastOpenSslError();
446         cxx_result.error = true;
447         return cxx_result;
448     }
449 
450     // ASN.1 DER-encoding of secure key wrapper.
451     int asn1_data_len = i2d_TEST_SECURE_KEY_WRAPPER(sec_key_wrapper.get(), nullptr);
452     if (asn1_data_len < 0) {
453         LOG(ERROR) << "createWrappedKey - Error while performing DER encode: "
454                    << keymaster::TranslateLastOpenSslError();
455         cxx_result.error = true;
456         return cxx_result;
457     }
458     std::vector<uint8_t> asn1_data(asn1_data_len, 0);
459 
460     if (!asn1_data.data()) {
461         LOG(ERROR) << "createWrappedKey - Failed to allocate a memory for asn1_data";
462         cxx_result.error = true;
463         return cxx_result;
464     }
465 
466     uint8_t* p = asn1_data.data();
467     asn1_data_len = i2d_TEST_SECURE_KEY_WRAPPER(sec_key_wrapper.get(), &p);
468     if (asn1_data_len < 0) {
469         cxx_result.error = true;
470         return cxx_result;
471     }
472 
473     std::move(asn1_data.begin(), asn1_data.end(), std::back_inserter(cxx_result.data));
474 
475     return cxx_result;
476 }
477 
478 /**
479  * Perform EC/RSA sign operation using `EVP_PKEY`.
480  */
performSignData(const char * data,size_t data_len,EVP_PKEY * pkey,unsigned char ** signature,size_t * signature_len)481 bool performSignData(const char* data, size_t data_len, EVP_PKEY* pkey, unsigned char** signature,
482                      size_t* signature_len) {
483     // Create the signing context
484     EVP_MD_CTX* md_ctx = EVP_MD_CTX_new();
485     if (md_ctx == NULL) {
486         LOG(ERROR) << "Failed to create signing context";
487         return false;
488     }
489 
490     // Initialize the signing operation
491     if (EVP_DigestSignInit(md_ctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
492         LOG(ERROR) << "Failed to initialize signing operation";
493         EVP_MD_CTX_free(md_ctx);
494         return false;
495     }
496 
497     // Sign the data
498     if (EVP_DigestSignUpdate(md_ctx, data, data_len) != 1) {
499         LOG(ERROR) << "Failed to sign data";
500         EVP_MD_CTX_free(md_ctx);
501         return false;
502     }
503 
504     // Determine the length of the signature
505     if (EVP_DigestSignFinal(md_ctx, NULL, signature_len) != 1) {
506         LOG(ERROR) << "Failed to determine signature length";
507         EVP_MD_CTX_free(md_ctx);
508         return false;
509     }
510 
511     // Allocate memory for the signature
512     *signature = (unsigned char*)malloc(*signature_len);
513     if (*signature == NULL) {
514         LOG(ERROR) << "Failed to allocate memory for the signature";
515         EVP_MD_CTX_free(md_ctx);
516         return false;
517     }
518 
519     // Perform the final signing operation
520     if (EVP_DigestSignFinal(md_ctx, *signature, signature_len) != 1) {
521         LOG(ERROR) << "Failed to perform signing operation";
522         free(*signature);
523         EVP_MD_CTX_free(md_ctx);
524         return false;
525     }
526 
527     EVP_MD_CTX_free(md_ctx);
528     return true;
529 }
530 
531 /**
532  * Perform EC/RSA verify operation using `EVP_PKEY`.
533  */
performVerifySignature(const char * data,size_t data_len,EVP_PKEY * pkey,const unsigned char * signature,size_t signature_len)534 int performVerifySignature(const char* data, size_t data_len, EVP_PKEY* pkey,
535                            const unsigned char* signature, size_t signature_len) {
536     // Create the verification context
537     EVP_MD_CTX* md_ctx = EVP_MD_CTX_new();
538     if (md_ctx == NULL) {
539         LOG(ERROR) << "Failed to create verification context";
540         return false;
541     }
542 
543     // Initialize the verification operation
544     if (EVP_DigestVerifyInit(md_ctx, NULL, EVP_sha256(), NULL, pkey) != 1) {
545         LOG(ERROR) << "Failed to initialize verification operation";
546         EVP_MD_CTX_free(md_ctx);
547         return false;
548     }
549 
550     // Verify the data
551     if (EVP_DigestVerifyUpdate(md_ctx, data, data_len) != 1) {
552         LOG(ERROR) << "Failed to verify data";
553         EVP_MD_CTX_free(md_ctx);
554         return false;
555     }
556 
557     // Perform the verification operation
558     int ret = EVP_DigestVerifyFinal(md_ctx, signature, signature_len);
559     EVP_MD_CTX_free(md_ctx);
560 
561     return ret == 1;
562 }
563 
564 /**
565  * Extract the `EVP_PKEY` for the given KeyMint Key and perform Sign/Verify operations
566  * using extracted `EVP_PKEY`.
567  */
performCryptoOpUsingKeystoreEngine(int64_t grant_id)568 bool performCryptoOpUsingKeystoreEngine(int64_t grant_id) {
569     const int KEY_ID_LEN = 20;
570     char key_id[KEY_ID_LEN] = "";
571     snprintf(key_id, KEY_ID_LEN, "%" PRIx64, grant_id);
572     std::string str_key = std::string(keystore2_grant_id_prefix) + key_id;
573     bool result = false;
574 
575 #if defined(OPENSSL_IS_BORINGSSL)
576     EVP_PKEY* evp = EVP_PKEY_from_keystore(str_key.c_str());
577     if (!evp) {
578         LOG(ERROR) << "Error while loading a key from keystore-engine";
579         return false;
580     }
581 
582     int algo_type = EVP_PKEY_id(evp);
583     if (algo_type != EVP_PKEY_RSA && algo_type != EVP_PKEY_EC) {
584         LOG(ERROR) << "Unsupported Algorithm. Only RSA and EC are allowed.";
585         EVP_PKEY_free(evp);
586         return false;
587     }
588 
589     unsigned char* signature = NULL;
590     size_t signature_len = 0;
591     const char* INPUT_DATA = "MY MESSAGE FOR SIGN";
592     size_t data_len = strlen(INPUT_DATA);
593     if (!performSignData(INPUT_DATA, data_len, evp, &signature, &signature_len)) {
594         LOG(ERROR) << "Failed to sign data";
595         EVP_PKEY_free(evp);
596         return false;
597     }
598 
599     result = performVerifySignature(INPUT_DATA, data_len, evp, signature, signature_len);
600     if (!result) {
601         LOG(ERROR) << "Signature verification failed";
602     } else {
603         LOG(INFO) << "Signature verification success";
604     }
605 
606     free(signature);
607     EVP_PKEY_free(evp);
608 #endif
609     return result;
610 }
611 
getValueFromAttestRecord(rust::Vec<rust::u8> cert_buf,int32_t tag,int32_t expected_sec_level)612 CxxResult getValueFromAttestRecord(rust::Vec<rust::u8> cert_buf, int32_t tag,
613                                    int32_t expected_sec_level) {
614     CxxResult cxx_result{};
615     cxx_result.error = false;
616 
617     uint8_t* cert_data = cert_buf.data();
618     int cert_data_size = cert_buf.size();
619 
620     std::vector<uint8_t> cert_bytes;
621     cert_bytes.insert(cert_bytes.end(), cert_data, (cert_data + cert_data_size));
622 
623     X509_Ptr cert(parseCertBlob(cert_bytes));
624     if (!cert.get()) {
625         LOG(ERROR) << "getValueFromAttestRecord - Failed to allocate a memory for certificate";
626         cxx_result.error = true;
627         return cxx_result;
628     }
629 
630     ASN1_OCTET_STRING* attest_rec = getAttestationRecord(cert.get());
631     if (!attest_rec) {
632         LOG(ERROR) << "getValueFromAttestRecord - Error in getAttestationRecord: "
633                    << keymaster::TranslateLastOpenSslError();
634         cxx_result.error = true;
635         return cxx_result;
636     }
637 
638     aidl::android::hardware::security::keymint::AuthorizationSet att_sw_enforced;
639     aidl::android::hardware::security::keymint::AuthorizationSet att_hw_enforced;
640     uint32_t att_attestation_version;
641     uint32_t att_keymint_version;
642     aidl::android::hardware::security::keymint::SecurityLevel att_attestation_security_level;
643     aidl::android::hardware::security::keymint::SecurityLevel att_keymint_security_level;
644     std::vector<uint8_t> att_challenge;
645     std::vector<uint8_t> att_unique_id;
646     std::vector<uint8_t> att_app_id;
647 
648     int32_t error =
649         static_cast<int32_t>(aidl::android::hardware::security::keymint::parse_attestation_record(
650             attest_rec->data, attest_rec->length, &att_attestation_version,
651             &att_attestation_security_level, &att_keymint_version, &att_keymint_security_level,
652             &att_challenge, &att_sw_enforced, &att_hw_enforced, &att_unique_id));
653     if (error) {
654         LOG(ERROR) << "getValueFromAttestRecord - Error in parse_attestation_record: " << error;
655         cxx_result.error = true;
656         return cxx_result;
657     }
658 
659     aidl::android::hardware::security::keymint::Tag auth_tag =
660         static_cast<aidl::android::hardware::security::keymint::Tag>(tag);
661     aidl::android::hardware::security::keymint::SecurityLevel tag_security_level =
662         static_cast<aidl::android::hardware::security::keymint::SecurityLevel>(expected_sec_level);
663 
664     if (auth_tag == aidl::android::hardware::security::keymint::Tag::ATTESTATION_APPLICATION_ID) {
665         int pos = att_sw_enforced.find(
666             aidl::android::hardware::security::keymint::Tag::ATTESTATION_APPLICATION_ID);
667         if (pos == -1) {
668             LOG(ERROR) << "getValueFromAttestRecord - Attestation-application-id missing.";
669             cxx_result.error = true;
670             return cxx_result;
671         }
672         aidl::android::hardware::security::keymint::KeyParameter param = att_sw_enforced[pos];
673         std::vector<uint8_t> val =
674             param.value.get<aidl::android::hardware::security::keymint::KeyParameterValue::blob>();
675         std::move(val.begin(), val.end(), std::back_inserter(cxx_result.data));
676         return cxx_result;
677     }
678 
679     if (auth_tag == aidl::android::hardware::security::keymint::Tag::ATTESTATION_CHALLENGE) {
680         if (att_challenge.size() == 0) {
681             LOG(ERROR) << "getValueFromAttestRecord - Attestation-challenge missing.";
682             cxx_result.error = true;
683             return cxx_result;
684         }
685         std::move(att_challenge.begin(), att_challenge.end(), std::back_inserter(cxx_result.data));
686         return cxx_result;
687     }
688 
689     if (auth_tag == aidl::android::hardware::security::keymint::Tag::UNIQUE_ID) {
690         if (att_unique_id.size() == 0) {
691             LOG(ERROR) << "getValueFromAttestRecord - unsupported tag - UNIQUE_ID.";
692             cxx_result.error = true;
693             return cxx_result;
694         }
695         std::move(att_unique_id.begin(), att_unique_id.end(), std::back_inserter(cxx_result.data));
696         return cxx_result;
697     }
698 
699     if (auth_tag == aidl::android::hardware::security::keymint::Tag::USAGE_COUNT_LIMIT) {
700         aidl::android::hardware::security::keymint::KeyParameter param;
701         int pos = att_hw_enforced.find(auth_tag);
702         if (tag_security_level ==
703                 aidl::android::hardware::security::keymint::SecurityLevel::SOFTWARE ||
704             tag_security_level ==
705                 aidl::android::hardware::security::keymint::SecurityLevel::KEYSTORE) {
706             pos = att_sw_enforced.find(auth_tag);
707             if (pos == -1) {
708                 LOG(ERROR) << "USAGE_COUNT_LIMIT not found in software enforced auth list";
709                 cxx_result.error = KM_ERROR_INVALID_TAG;
710                 return cxx_result;
711             }
712             param = att_sw_enforced[pos];
713         } else {
714             pos = att_hw_enforced.find(auth_tag);
715             if (pos == -1) {
716                 LOG(ERROR) << "USAGE_COUNT_LIMIT not found in hardware enforced auth list";
717                 cxx_result.error = KM_ERROR_INVALID_TAG;
718                 return cxx_result;
719             }
720             param = att_hw_enforced[pos];
721         }
722         std::string val = std::to_string(
723             param.value
724                 .get<aidl::android::hardware::security::keymint::KeyParameterValue::integer>());
725         std::move(val.begin(), val.end(), std::back_inserter(cxx_result.data));
726         return cxx_result;
727     }
728 
729     int pos = att_hw_enforced.find(auth_tag);
730     if (pos == -1) {
731         LOG(ERROR) << "getValueFromAttestRecord - unsupported tag.";
732         cxx_result.error = true;
733         return cxx_result;
734     }
735     aidl::android::hardware::security::keymint::KeyParameter param = att_hw_enforced[pos];
736     std::vector<uint8_t> val =
737         param.value.get<aidl::android::hardware::security::keymint::KeyParameterValue::blob>();
738     std::move(val.begin(), val.end(), std::back_inserter(cxx_result.data));
739     return cxx_result;
740 }
741 
getOsVersion()742 uint32_t getOsVersion() {
743     return aidl::android::hardware::security::keymint::getOsVersion();
744 }
745 
getOsPatchlevel()746 uint32_t getOsPatchlevel() {
747     return aidl::android::hardware::security::keymint::getOsPatchlevel();
748 }
749 
getVendorPatchlevel()750 uint32_t getVendorPatchlevel() {
751     return aidl::android::hardware::security::keymint::getVendorPatchlevel();
752 }
753