1 // Copyright 2015 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 #define LOG_TAG "keystore_client"
16 
17 #include "keystore/keystore_client_impl.h"
18 
19 #include <future>
20 #include <optional>
21 #include <string>
22 #include <vector>
23 
24 #include <android/security/keystore/IKeystoreService.h>
25 #include <binder/IBinder.h>
26 #include <binder/IInterface.h>
27 #include <binder/IServiceManager.h>
28 #include <keystore/keystore.h>
29 #include <log/log.h>
30 #include <utils/String16.h>
31 #include <utils/String8.h>
32 
33 #include <keystore/keymaster_types.h>
34 #include <keystore/keystore_hidl_support.h>
35 #include <keystore/keystore_promises.h>
36 
37 #include "keystore_client.pb.h"
38 
39 namespace {
40 
41 // Use the UID of the current process.
42 const int kDefaultUID = -1;
43 const char kEncryptSuffix[] = "_ENC";
44 const char kAuthenticateSuffix[] = "_AUTH";
45 constexpr uint32_t kAESKeySize = 256;      // bits
46 constexpr uint32_t kHMACKeySize = 256;     // bits
47 constexpr uint32_t kHMACOutputSize = 256;  // bits
48 
49 using android::String16;
50 using android::security::keymaster::ExportResult;
51 using android::security::keymaster::OperationResult;
52 using android::security::keystore::KeystoreResponse;
53 using keystore::AuthorizationSet;
54 using keystore::AuthorizationSetBuilder;
55 using keystore::KeyCharacteristics;
56 using keystore::KeyStoreServiceReturnCode;
57 }  // namespace
58 
59 namespace keystore {
60 
KeystoreClientImpl()61 KeystoreClientImpl::KeystoreClientImpl() {
62     service_manager_ = android::defaultServiceManager();
63     keystore_binder_ = service_manager_->getService(String16("android.security.keystore"));
64     keystore_ =
65         android::interface_cast<android::security::keystore::IKeystoreService>(keystore_binder_);
66 }
67 
encryptWithAuthentication(const std::string & key_name,const std::string & data,int32_t flags,std::string * encrypted_data)68 bool KeystoreClientImpl::encryptWithAuthentication(const std::string& key_name,
69                                                    const std::string& data, int32_t flags,
70                                                    std::string* encrypted_data) {
71     // The encryption algorithm is AES-256-CBC with PKCS #7 padding and a random
72     // IV. The authentication algorithm is HMAC-SHA256 and is computed over the
73     // cipher-text (i.e. Encrypt-then-MAC approach). This was chosen over AES-GCM
74     // because hardware support for GCM is not mandatory for all Brillo devices.
75     std::string encryption_key_name = key_name + kEncryptSuffix;
76     if (!createOrVerifyEncryptionKey(encryption_key_name, flags)) {
77         return false;
78     }
79     std::string authentication_key_name = key_name + kAuthenticateSuffix;
80     if (!createOrVerifyAuthenticationKey(authentication_key_name, flags)) {
81         return false;
82     }
83     AuthorizationSetBuilder encrypt_params;
84     encrypt_params.Padding(PaddingMode::PKCS7);
85     encrypt_params.Authorization(TAG_BLOCK_MODE, BlockMode::CBC);
86     AuthorizationSet output_params;
87     std::string raw_encrypted_data;
88     if (!oneShotOperation(KeyPurpose::ENCRYPT, encryption_key_name, encrypt_params, data,
89                           std::string(), /* signature_to_verify */
90                           &output_params, &raw_encrypted_data)) {
91         ALOGE("Encrypt: AES operation failed.");
92         return false;
93     }
94     auto init_vector_blob = output_params.GetTagValue(TAG_NONCE);
95     if (!init_vector_blob.isOk()) {
96         ALOGE("Encrypt: Missing initialization vector.");
97         return false;
98     }
99     std::string init_vector = hidlVec2String(init_vector_blob.value());
100 
101     AuthorizationSetBuilder authenticate_params;
102     authenticate_params.Digest(Digest::SHA_2_256);
103     authenticate_params.Authorization(TAG_MAC_LENGTH, kHMACOutputSize);
104     std::string raw_authentication_data;
105     if (!oneShotOperation(KeyPurpose::SIGN, authentication_key_name, authenticate_params,
106                           init_vector + raw_encrypted_data, std::string(), /* signature_to_verify */
107                           &output_params, &raw_authentication_data)) {
108         ALOGE("Encrypt: HMAC operation failed.");
109         return false;
110     }
111     EncryptedData protobuf;
112     protobuf.set_init_vector(init_vector);
113     protobuf.set_authentication_data(raw_authentication_data);
114     protobuf.set_encrypted_data(raw_encrypted_data);
115     if (!protobuf.SerializeToString(encrypted_data)) {
116         ALOGE("Encrypt: Failed to serialize EncryptedData protobuf.");
117         return false;
118     }
119     return true;
120 }
121 
decryptWithAuthentication(const std::string & key_name,const std::string & encrypted_data,std::string * data)122 bool KeystoreClientImpl::decryptWithAuthentication(const std::string& key_name,
123                                                    const std::string& encrypted_data,
124                                                    std::string* data) {
125     EncryptedData protobuf;
126     if (!protobuf.ParseFromString(encrypted_data)) {
127         ALOGE("Decrypt: Failed to parse EncryptedData protobuf.");
128     }
129     // Verify authentication before attempting decryption.
130     std::string authentication_key_name = key_name + kAuthenticateSuffix;
131     AuthorizationSetBuilder authenticate_params;
132     authenticate_params.Digest(Digest::SHA_2_256);
133     AuthorizationSet output_params;
134     std::string output_data;
135     if (!oneShotOperation(KeyPurpose::VERIFY, authentication_key_name, authenticate_params,
136                           protobuf.init_vector() + protobuf.encrypted_data(),
137                           protobuf.authentication_data(), &output_params, &output_data)) {
138         ALOGE("Decrypt: HMAC operation failed.");
139         return false;
140     }
141     std::string encryption_key_name = key_name + kEncryptSuffix;
142     AuthorizationSetBuilder encrypt_params;
143     encrypt_params.Padding(PaddingMode::PKCS7);
144     encrypt_params.Authorization(TAG_BLOCK_MODE, BlockMode::CBC);
145     encrypt_params.Authorization(TAG_NONCE, protobuf.init_vector().data(),
146                                  protobuf.init_vector().size());
147     if (!oneShotOperation(KeyPurpose::DECRYPT, encryption_key_name, encrypt_params,
148                           protobuf.encrypted_data(), std::string(), /* signature_to_verify */
149                           &output_params, data)) {
150         ALOGE("Decrypt: AES operation failed.");
151         return false;
152     }
153     return true;
154 }
155 
oneShotOperation(KeyPurpose purpose,const std::string & key_name,const AuthorizationSet & input_parameters,const std::string & input_data,const std::string & signature_to_verify,AuthorizationSet * output_parameters,std::string * output_data)156 bool KeystoreClientImpl::oneShotOperation(KeyPurpose purpose, const std::string& key_name,
157                                           const AuthorizationSet& input_parameters,
158                                           const std::string& input_data,
159                                           const std::string& signature_to_verify,
160                                           AuthorizationSet* output_parameters,
161                                           std::string* output_data) {
162     uint64_t handle;
163     auto result = beginOperation(purpose, key_name, input_parameters, output_parameters, &handle);
164     if (!result.isOk()) {
165         ALOGE("BeginOperation failed: %d", result.getErrorCode());
166         return false;
167     }
168     AuthorizationSet empty_params;
169     AuthorizationSet ignored_params;
170     result = finishOperation(handle, empty_params, input_data, signature_to_verify, &ignored_params,
171                              output_data);
172     if (!result.isOk()) {
173         ALOGE("FinishOperation failed: %d", result.getErrorCode());
174         return false;
175     }
176     return true;
177 }
178 
179 KeyStoreNativeReturnCode
addRandomNumberGeneratorEntropy(const std::string & entropy,int32_t flags)180 KeystoreClientImpl::addRandomNumberGeneratorEntropy(const std::string& entropy, int32_t flags) {
181     int32_t error_code;
182 
183     android::sp<KeystoreResponsePromise> promise(new KeystoreResponsePromise());
184     auto future = promise->get_future();
185 
186     auto binder_result =
187         keystore_->addRngEntropy(promise, blob2hidlVec(entropy), flags, &error_code);
188     if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
189 
190     KeyStoreNativeReturnCode rc(error_code);
191     if (!rc.isOk()) return rc;
192 
193     auto result = future.get();
194 
195     return KeyStoreNativeReturnCode(result.response_code());
196 }
197 
198 KeyStoreNativeReturnCode
generateKey(const std::string & key_name,const AuthorizationSet & key_parameters,int32_t flags,AuthorizationSet * hardware_enforced_characteristics,AuthorizationSet * software_enforced_characteristics)199 KeystoreClientImpl::generateKey(const std::string& key_name, const AuthorizationSet& key_parameters,
200                                 int32_t flags, AuthorizationSet* hardware_enforced_characteristics,
201                                 AuthorizationSet* software_enforced_characteristics) {
202     String16 key_name16(key_name.data(), key_name.size());
203     int32_t error_code;
204     android::sp<KeyCharacteristicsPromise> promise(new KeyCharacteristicsPromise);
205     auto future = promise->get_future();
206     auto binder_result = keystore_->generateKey(
207         promise, key_name16,
208         ::android::security::keymaster::KeymasterArguments(key_parameters.hidl_data()),
209         hidl_vec<uint8_t>() /* entropy */, kDefaultUID, flags, &error_code);
210     if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
211 
212     KeyStoreNativeReturnCode rc(error_code);
213     if (!rc.isOk()) return rc;
214 
215     auto [km_response, characteristics] = future.get();
216 
217     /* assignment (hidl_vec<KeyParameter> -> AuthorizationSet) makes a deep copy.
218      * There are no references to Parcel memory after that, and ownership of the newly acquired
219      * memory is with the AuthorizationSet objects. */
220     *hardware_enforced_characteristics = characteristics.hardwareEnforced.getParameters();
221     *software_enforced_characteristics = characteristics.softwareEnforced.getParameters();
222     return KeyStoreNativeReturnCode(km_response.response_code());
223 }
224 
225 KeyStoreNativeReturnCode
getKeyCharacteristics(const std::string & key_name,AuthorizationSet * hardware_enforced_characteristics,AuthorizationSet * software_enforced_characteristics)226 KeystoreClientImpl::getKeyCharacteristics(const std::string& key_name,
227                                           AuthorizationSet* hardware_enforced_characteristics,
228                                           AuthorizationSet* software_enforced_characteristics) {
229     String16 key_name16(key_name.data(), key_name.size());
230     int32_t error_code;
231     android::sp<KeyCharacteristicsPromise> promise(new KeyCharacteristicsPromise);
232     auto future = promise->get_future();
233     auto binder_result = keystore_->getKeyCharacteristics(
234         promise, key_name16, android::security::keymaster::KeymasterBlob(),
235         android::security::keymaster::KeymasterBlob(), kDefaultUID, &error_code);
236     if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
237 
238     KeyStoreNativeReturnCode rc(error_code);
239     if (!rc.isOk()) return rc;
240 
241     auto [km_response, characteristics] = future.get();
242 
243     /* assignment (hidl_vec<KeyParameter> -> AuthorizationSet) makes a deep copy.
244      * There are no references to Parcel memory after that, and ownership of the newly acquired
245      * memory is with the AuthorizationSet objects. */
246     *hardware_enforced_characteristics = characteristics.hardwareEnforced.getParameters();
247     *software_enforced_characteristics = characteristics.softwareEnforced.getParameters();
248     return KeyStoreNativeReturnCode(km_response.response_code());
249 }
250 
251 KeyStoreNativeReturnCode
importKey(const std::string & key_name,const AuthorizationSet & key_parameters,KeyFormat key_format,const std::string & key_data,AuthorizationSet * hardware_enforced_characteristics,AuthorizationSet * software_enforced_characteristics)252 KeystoreClientImpl::importKey(const std::string& key_name, const AuthorizationSet& key_parameters,
253                               KeyFormat key_format, const std::string& key_data,
254                               AuthorizationSet* hardware_enforced_characteristics,
255                               AuthorizationSet* software_enforced_characteristics) {
256     String16 key_name16(key_name.data(), key_name.size());
257     auto hidlKeyData = blob2hidlVec(key_data);
258     int32_t error_code;
259     android::sp<KeyCharacteristicsPromise> promise(new KeyCharacteristicsPromise);
260     auto future = promise->get_future();
261     auto binder_result = keystore_->importKey(
262         promise, key_name16,
263         ::android::security::keymaster::KeymasterArguments(key_parameters.hidl_data()),
264         (int)key_format, hidlKeyData, kDefaultUID, KEYSTORE_FLAG_NONE, &error_code);
265     if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
266 
267     KeyStoreNativeReturnCode rc(error_code);
268     if (!rc.isOk()) return rc;
269 
270     auto [km_response, characteristics] = future.get();
271 
272     /* assignment (hidl_vec<KeyParameter> -> AuthorizationSet) makes a deep copy.
273      * There are no references to Parcel memory after that, and ownership of the newly acquired
274      * memory is with the AuthorizationSet objects. */
275     *hardware_enforced_characteristics = characteristics.hardwareEnforced.getParameters();
276     *software_enforced_characteristics = characteristics.softwareEnforced.getParameters();
277     return KeyStoreNativeReturnCode(km_response.response_code());
278 }
279 
exportKey(KeyFormat export_format,const std::string & key_name,std::string * export_data)280 KeyStoreNativeReturnCode KeystoreClientImpl::exportKey(KeyFormat export_format,
281                                                        const std::string& key_name,
282                                                        std::string* export_data) {
283     String16 key_name16(key_name.data(), key_name.size());
284     int32_t error_code;
285     android::sp<KeystoreExportPromise> promise(new KeystoreExportPromise);
286     auto future = promise->get_future();
287     auto binder_result = keystore_->exportKey(
288         promise, key_name16, (int)export_format, android::security::keymaster::KeymasterBlob(),
289         android::security::keymaster::KeymasterBlob(), kDefaultUID, &error_code);
290     if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
291 
292     KeyStoreNativeReturnCode rc(error_code);
293     if (!rc.isOk()) return rc;
294 
295     auto export_result = future.get();
296     if (!export_result.resultCode.isOk()) return export_result.resultCode;
297 
298     *export_data = hidlVec2String(export_result.exportData);
299 
300     return export_result.resultCode;
301 }
302 
deleteKey(const std::string & key_name)303 KeyStoreNativeReturnCode KeystoreClientImpl::deleteKey(const std::string& key_name) {
304     String16 key_name16(key_name.data(), key_name.size());
305     int32_t result;
306     auto binder_result = keystore_->del(key_name16, kDefaultUID, &result);
307     if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
308     return KeyStoreNativeReturnCode(result);
309 }
310 
deleteAllKeys()311 KeyStoreNativeReturnCode KeystoreClientImpl::deleteAllKeys() {
312     int32_t result;
313     auto binder_result = keystore_->clear_uid(kDefaultUID, &result);
314     if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
315     return KeyStoreNativeReturnCode(result);
316 }
317 
318 KeyStoreNativeReturnCode
beginOperation(KeyPurpose purpose,const std::string & key_name,const AuthorizationSet & input_parameters,AuthorizationSet * output_parameters,uint64_t * handle)319 KeystoreClientImpl::beginOperation(KeyPurpose purpose, const std::string& key_name,
320                                    const AuthorizationSet& input_parameters,
321                                    AuthorizationSet* output_parameters, uint64_t* handle) {
322     android::sp<android::IBinder> token(new android::BBinder);
323     String16 key_name16(key_name.data(), key_name.size());
324     int32_t error_code;
325     android::sp<OperationResultPromise> promise(new OperationResultPromise{});
326     auto future = promise->get_future();
327     auto binder_result = keystore_->begin(
328         promise, token, key_name16, (int)purpose, true /*pruneable*/,
329         android::security::keymaster::KeymasterArguments(input_parameters.hidl_data()),
330         hidl_vec<uint8_t>() /* entropy */, kDefaultUID, &error_code);
331     if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
332     KeyStoreNativeReturnCode rc(error_code);
333     if (!rc.isOk()) return rc;
334 
335     OperationResult result = future.get();
336     if (result.resultCode.isOk()) {
337         *handle = getNextVirtualHandle();
338         active_operations_[*handle] = result.token;
339         if (result.outParams.size()) {
340             *output_parameters = result.outParams;
341         }
342     }
343     return result.resultCode;
344 }
345 
346 KeyStoreNativeReturnCode
updateOperation(uint64_t handle,const AuthorizationSet & input_parameters,const std::string & input_data,size_t * num_input_bytes_consumed,AuthorizationSet * output_parameters,std::string * output_data)347 KeystoreClientImpl::updateOperation(uint64_t handle, const AuthorizationSet& input_parameters,
348                                     const std::string& input_data, size_t* num_input_bytes_consumed,
349                                     AuthorizationSet* output_parameters, std::string* output_data) {
350     if (active_operations_.count(handle) == 0) {
351         return ErrorCode::INVALID_OPERATION_HANDLE;
352     }
353     auto hidlInputData = blob2hidlVec(input_data);
354     int32_t error_code;
355     android::sp<OperationResultPromise> promise(new OperationResultPromise{});
356     auto future = promise->get_future();
357     auto binder_result = keystore_->update(
358         promise, active_operations_[handle],
359         android::security::keymaster::KeymasterArguments(input_parameters.hidl_data()),
360         hidlInputData, &error_code);
361     if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
362     KeyStoreNativeReturnCode rc(error_code);
363     if (!rc.isOk()) return rc;
364 
365     OperationResult result = future.get();
366 
367     if (result.resultCode.isOk()) {
368         *num_input_bytes_consumed = result.inputConsumed;
369         if (result.outParams.size()) {
370             *output_parameters = result.outParams;
371         }
372         // TODO verify that append should not be assign
373         output_data->append(hidlVec2String(result.data));
374     }
375     return result.resultCode;
376 }
377 
378 KeyStoreNativeReturnCode
finishOperation(uint64_t handle,const AuthorizationSet & input_parameters,const std::string & input_data,const std::string & signature_to_verify,AuthorizationSet * output_parameters,std::string * output_data)379 KeystoreClientImpl::finishOperation(uint64_t handle, const AuthorizationSet& input_parameters,
380                                     const std::string& input_data,
381                                     const std::string& signature_to_verify,
382                                     AuthorizationSet* output_parameters, std::string* output_data) {
383     if (active_operations_.count(handle) == 0) {
384         return ErrorCode::INVALID_OPERATION_HANDLE;
385     }
386     int32_t error_code;
387     auto hidlSignature = blob2hidlVec(signature_to_verify);
388     auto hidlInput = blob2hidlVec(input_data);
389     android::sp<OperationResultPromise> promise(new OperationResultPromise{});
390     auto future = promise->get_future();
391     auto binder_result = keystore_->finish(
392         promise, active_operations_[handle],
393         android::security::keymaster::KeymasterArguments(input_parameters.hidl_data()),
394         (std::vector<uint8_t>)hidlInput, (std::vector<uint8_t>)hidlSignature, hidl_vec<uint8_t>(),
395         &error_code);
396     if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
397     KeyStoreNativeReturnCode rc(error_code);
398     if (!rc.isOk()) return rc;
399 
400     OperationResult result = future.get();
401     if (result.resultCode.isOk()) {
402         if (result.outParams.size()) {
403             *output_parameters = result.outParams;
404         }
405         // TODO verify that append should not be assign
406         output_data->append(hidlVec2String(result.data));
407         active_operations_.erase(handle);
408     }
409     return result.resultCode;
410 }
411 
abortOperation(uint64_t handle)412 KeyStoreNativeReturnCode KeystoreClientImpl::abortOperation(uint64_t handle) {
413     if (active_operations_.count(handle) == 0) {
414         return ErrorCode::INVALID_OPERATION_HANDLE;
415     }
416     int32_t result;
417     android::sp<KeystoreResponsePromise> promise(new KeystoreResponsePromise{});
418     auto future = promise->get_future();
419     // Current implementation does not return exceptions in android::binder::Status
420     auto binder_result = keystore_->abort(promise, active_operations_[handle], &result);
421     if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
422     KeyStoreNativeReturnCode rc(result);
423     if (!rc.isOk()) return rc;
424     rc = KeyStoreNativeReturnCode(future.get().response_code());
425     if (rc.isOk()) {
426         active_operations_.erase(handle);
427     }
428     return rc;
429 }
430 
doesKeyExist(const std::string & key_name)431 bool KeystoreClientImpl::doesKeyExist(const std::string& key_name) {
432     String16 key_name16(key_name.data(), key_name.size());
433     int32_t result;
434     auto binder_result = keystore_->exist(key_name16, kDefaultUID, &result);
435     if (!binder_result.isOk()) return false;  // binder error
436     return result == static_cast<int32_t>(ResponseCode::NO_ERROR);
437 }
438 
listKeys(const std::string & prefix,std::vector<std::string> * key_name_list)439 bool KeystoreClientImpl::listKeys(const std::string& prefix,
440                                   std::vector<std::string>* key_name_list) {
441     return listKeysOfUid(prefix, kDefaultUID, key_name_list);
442 }
443 
listKeysOfUid(const std::string & prefix,int uid,std::vector<std::string> * key_name_list)444 bool KeystoreClientImpl::listKeysOfUid(const std::string& prefix, int uid,
445                                        std::vector<std::string>* key_name_list) {
446     String16 prefix16(prefix.data(), prefix.size());
447     std::vector<::android::String16> matches;
448     auto binder_result = keystore_->list(prefix16, uid, &matches);
449     if (!binder_result.isOk()) return false;
450 
451     for (const auto& match : matches) {
452         android::String8 key_name(match);
453         key_name_list->push_back(prefix + std::string(key_name.string(), key_name.size()));
454     }
455     return true;
456 }
457 
getKey(const std::string & alias,int uid)458 std::optional<std::vector<uint8_t>> KeystoreClientImpl::getKey(const std::string& alias, int uid) {
459     String16 alias16(alias.data(), alias.size());
460     std::vector<uint8_t> output;
461     auto binder_result = keystore_->get(alias16, uid, &output);
462     if (!binder_result.isOk()) return std::nullopt;
463     return output;
464 }
465 
getNextVirtualHandle()466 uint64_t KeystoreClientImpl::getNextVirtualHandle() {
467     return next_virtual_handle_++;
468 }
469 
createOrVerifyEncryptionKey(const std::string & key_name,int32_t flags)470 bool KeystoreClientImpl::createOrVerifyEncryptionKey(const std::string& key_name, int32_t flags) {
471     bool key_exists = doesKeyExist(key_name);
472     if (key_exists) {
473         bool verified = false;
474         if (!verifyEncryptionKeyAttributes(key_name, &verified)) {
475             return false;
476         }
477         if (!verified) {
478             auto result = deleteKey(key_name);
479             if (!result.isOk()) {
480                 ALOGE("Failed to delete invalid encryption key: %d", result.getErrorCode());
481                 return false;
482             }
483             key_exists = false;
484         }
485     }
486     if (!key_exists) {
487         AuthorizationSetBuilder key_parameters;
488         key_parameters.AesEncryptionKey(kAESKeySize)
489             .Padding(PaddingMode::PKCS7)
490             .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
491             .Authorization(TAG_NO_AUTH_REQUIRED);
492         AuthorizationSet hardware_enforced_characteristics;
493         AuthorizationSet software_enforced_characteristics;
494         auto result =
495             generateKey(key_name, key_parameters, flags, &hardware_enforced_characteristics,
496                         &software_enforced_characteristics);
497         if (!result.isOk()) {
498             ALOGE("Failed to generate encryption key: %d", result.getErrorCode());
499             return false;
500         }
501         if (hardware_enforced_characteristics.size() == 0) {
502             ALOGW("WARNING: Encryption key is not hardware-backed.");
503         }
504     }
505     return true;
506 }
507 
createOrVerifyAuthenticationKey(const std::string & key_name,int32_t flags)508 bool KeystoreClientImpl::createOrVerifyAuthenticationKey(const std::string& key_name,
509                                                          int32_t flags) {
510     bool key_exists = doesKeyExist(key_name);
511     if (key_exists) {
512         bool verified = false;
513         if (!verifyAuthenticationKeyAttributes(key_name, &verified)) {
514             return false;
515         }
516         if (!verified) {
517             auto result = deleteKey(key_name);
518             if (!result.isOk()) {
519                 ALOGE("Failed to delete invalid authentication key: %d", result.getErrorCode());
520                 return false;
521             }
522             key_exists = false;
523         }
524     }
525     if (!key_exists) {
526         AuthorizationSetBuilder key_parameters;
527         key_parameters.HmacKey(kHMACKeySize)
528             .Digest(Digest::SHA_2_256)
529             .Authorization(TAG_MIN_MAC_LENGTH, kHMACOutputSize)
530             .Authorization(TAG_NO_AUTH_REQUIRED);
531         AuthorizationSet hardware_enforced_characteristics;
532         AuthorizationSet software_enforced_characteristics;
533         auto result =
534             generateKey(key_name, key_parameters, flags, &hardware_enforced_characteristics,
535                         &software_enforced_characteristics);
536         if (!result.isOk()) {
537             ALOGE("Failed to generate authentication key: %d", result.getErrorCode());
538             return false;
539         }
540         if (hardware_enforced_characteristics.size() == 0) {
541             ALOGW("WARNING: Authentication key is not hardware-backed.");
542         }
543     }
544     return true;
545 }
546 
verifyEncryptionKeyAttributes(const std::string & key_name,bool * verified)547 bool KeystoreClientImpl::verifyEncryptionKeyAttributes(const std::string& key_name,
548                                                        bool* verified) {
549     AuthorizationSet hardware_enforced_characteristics;
550     AuthorizationSet software_enforced_characteristics;
551     auto result = getKeyCharacteristics(key_name, &hardware_enforced_characteristics,
552                                         &software_enforced_characteristics);
553     if (!result.isOk()) {
554         ALOGE("Failed to query encryption key: %d", result.getErrorCode());
555         return false;
556     }
557     *verified = true;
558     auto algorithm = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_ALGORITHM),
559                               software_enforced_characteristics.GetTagValue(TAG_ALGORITHM));
560     if (!algorithm.isOk() || algorithm.value() != Algorithm::AES) {
561         ALOGW("Found encryption key with invalid algorithm.");
562         *verified = false;
563     }
564     auto key_size = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_KEY_SIZE),
565                              software_enforced_characteristics.GetTagValue(TAG_KEY_SIZE));
566     if (!key_size.isOk() || key_size.value() != kAESKeySize) {
567         ALOGW("Found encryption key with invalid size.");
568         *verified = false;
569     }
570     auto block_mode = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_BLOCK_MODE),
571                                software_enforced_characteristics.GetTagValue(TAG_BLOCK_MODE));
572     if (!block_mode.isOk() || block_mode.value() != BlockMode::CBC) {
573         ALOGW("Found encryption key with invalid block mode.");
574         *verified = false;
575     }
576     auto padding_mode = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_PADDING),
577                                  software_enforced_characteristics.GetTagValue(TAG_PADDING));
578     if (!padding_mode.isOk() || padding_mode.value() != PaddingMode::PKCS7) {
579         ALOGW("Found encryption key with invalid padding mode.");
580         *verified = false;
581     }
582     if (hardware_enforced_characteristics.size() == 0) {
583         ALOGW("WARNING: Encryption key is not hardware-backed.");
584     }
585     return true;
586 }
587 
verifyAuthenticationKeyAttributes(const std::string & key_name,bool * verified)588 bool KeystoreClientImpl::verifyAuthenticationKeyAttributes(const std::string& key_name,
589                                                            bool* verified) {
590     AuthorizationSet hardware_enforced_characteristics;
591     AuthorizationSet software_enforced_characteristics;
592     auto result = getKeyCharacteristics(key_name, &hardware_enforced_characteristics,
593                                         &software_enforced_characteristics);
594     if (!result.isOk()) {
595         ALOGE("Failed to query authentication key: %d", result.getErrorCode());
596         return false;
597     }
598     *verified = true;
599     auto algorithm = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_ALGORITHM),
600                               software_enforced_characteristics.GetTagValue(TAG_ALGORITHM));
601     if (!algorithm.isOk() || algorithm.value() != Algorithm::HMAC) {
602         ALOGW("Found authentication key with invalid algorithm.");
603         *verified = false;
604     }
605     auto key_size = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_KEY_SIZE),
606                              software_enforced_characteristics.GetTagValue(TAG_KEY_SIZE));
607     if (!key_size.isOk() || key_size.value() != kHMACKeySize) {
608         ALOGW("Found authentication key with invalid size.");
609         *verified = false;
610     }
611     auto mac_size = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_MIN_MAC_LENGTH),
612                              software_enforced_characteristics.GetTagValue(TAG_MIN_MAC_LENGTH));
613     if (!mac_size.isOk() || mac_size.value() != kHMACOutputSize) {
614         ALOGW("Found authentication key with invalid minimum mac size.");
615         *verified = false;
616     }
617     auto digest = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_DIGEST),
618                            software_enforced_characteristics.GetTagValue(TAG_DIGEST));
619     if (!digest.isOk() || digest.value() != Digest::SHA_2_256) {
620         ALOGW("Found authentication key with invalid digest list.");
621         *verified = false;
622     }
623     if (hardware_enforced_characteristics.size() == 0) {
624         ALOGW("WARNING: Authentication key is not hardware-backed.");
625     }
626     return true;
627 }
628 
629 }  // namespace keystore
630