blob: 3fca4c9db9771cf990519f2ce176db5d5b22352d [file] [log] [blame]
Darren Krahn69a3dbc2015-09-22 16:21:04 -07001// 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
Darren Krahn251cb282015-09-28 08:51:18 -070015#define LOG_TAG "keystore_client"
16
Darren Krahn69a3dbc2015-09-22 16:21:04 -070017#include "keystore/keystore_client_impl.h"
18
Rob Barnesbb6cabd2018-10-04 17:10:37 -060019#include <future>
Victor Hsieh8b3b6fc2019-09-05 14:27:38 -070020#include <optional>
Darren Krahn69a3dbc2015-09-22 16:21:04 -070021#include <string>
22#include <vector>
23
Rob Barnesbb6cabd2018-10-04 17:10:37 -060024#include <android/security/keystore/IKeystoreService.h>
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010025#include <binder/IBinder.h>
26#include <binder/IInterface.h>
27#include <binder/IServiceManager.h>
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010028#include <keystore/keystore.h>
29#include <log/log.h>
30#include <utils/String16.h>
31#include <utils/String8.h>
Darren Krahn69a3dbc2015-09-22 16:21:04 -070032
Shawn Willdenbb22a6c2017-12-06 19:35:28 -070033#include <keystore/keymaster_types.h>
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010034#include <keystore/keystore_hidl_support.h>
Rob Barnesbb6cabd2018-10-04 17:10:37 -060035#include <keystore/keystore_promises.h>
Darren Krahn251cb282015-09-28 08:51:18 -070036
Shawn Willdenbb22a6c2017-12-06 19:35:28 -070037#include "keystore_client.pb.h"
38
Darren Krahn69a3dbc2015-09-22 16:21:04 -070039namespace {
40
41// Use the UID of the current process.
42const int kDefaultUID = -1;
Darren Krahn251cb282015-09-28 08:51:18 -070043const char kEncryptSuffix[] = "_ENC";
44const char kAuthenticateSuffix[] = "_AUTH";
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010045constexpr uint32_t kAESKeySize = 256; // bits
46constexpr uint32_t kHMACKeySize = 256; // bits
47constexpr uint32_t kHMACOutputSize = 256; // bits
Darren Krahnc8eca232015-10-16 10:54:43 -070048
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070049using android::String16;
50using android::security::keymaster::ExportResult;
51using android::security::keymaster::OperationResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -060052using android::security::keystore::KeystoreResponse;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070053using keystore::AuthorizationSet;
54using keystore::AuthorizationSetBuilder;
55using keystore::KeyCharacteristics;
56using keystore::KeyStoreServiceReturnCode;
Darren Krahn69a3dbc2015-09-22 16:21:04 -070057} // namespace
58
59namespace keystore {
60
61KeystoreClientImpl::KeystoreClientImpl() {
62 service_manager_ = android::defaultServiceManager();
63 keystore_binder_ = service_manager_->getService(String16("android.security.keystore"));
Rob Barnesbb6cabd2018-10-04 17:10:37 -060064 keystore_ =
65 android::interface_cast<android::security::keystore::IKeystoreService>(keystore_binder_);
Darren Krahn69a3dbc2015-09-22 16:21:04 -070066}
67
Darren Krahn251cb282015-09-28 08:51:18 -070068bool KeystoreClientImpl::encryptWithAuthentication(const std::string& key_name,
Janis Danisevskisc1460142017-12-18 16:48:46 -080069 const std::string& data, int32_t flags,
Darren Krahn251cb282015-09-28 08:51:18 -070070 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;
Janis Danisevskisc1460142017-12-18 16:48:46 -080076 if (!createOrVerifyEncryptionKey(encryption_key_name, flags)) {
Darren Krahn251cb282015-09-28 08:51:18 -070077 return false;
78 }
79 std::string authentication_key_name = key_name + kAuthenticateSuffix;
Janis Danisevskisc1460142017-12-18 16:48:46 -080080 if (!createOrVerifyAuthenticationKey(authentication_key_name, flags)) {
Darren Krahn251cb282015-09-28 08:51:18 -070081 return false;
82 }
83 AuthorizationSetBuilder encrypt_params;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010084 encrypt_params.Padding(PaddingMode::PKCS7);
85 encrypt_params.Authorization(TAG_BLOCK_MODE, BlockMode::CBC);
Darren Krahn251cb282015-09-28 08:51:18 -070086 AuthorizationSet output_params;
87 std::string raw_encrypted_data;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010088 if (!oneShotOperation(KeyPurpose::ENCRYPT, encryption_key_name, encrypt_params, data,
Darren Krahn251cb282015-09-28 08:51:18 -070089 std::string(), /* signature_to_verify */
90 &output_params, &raw_encrypted_data)) {
91 ALOGE("Encrypt: AES operation failed.");
92 return false;
93 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010094 auto init_vector_blob = output_params.GetTagValue(TAG_NONCE);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070095 if (!init_vector_blob.isOk()) {
Darren Krahn251cb282015-09-28 08:51:18 -070096 ALOGE("Encrypt: Missing initialization vector.");
97 return false;
98 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010099 std::string init_vector = hidlVec2String(init_vector_blob.value());
Darren Krahn251cb282015-09-28 08:51:18 -0700100
101 AuthorizationSetBuilder authenticate_params;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100102 authenticate_params.Digest(Digest::SHA_2_256);
103 authenticate_params.Authorization(TAG_MAC_LENGTH, kHMACOutputSize);
Darren Krahn251cb282015-09-28 08:51:18 -0700104 std::string raw_authentication_data;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100105 if (!oneShotOperation(KeyPurpose::SIGN, authentication_key_name, authenticate_params,
Darren Krahn251cb282015-09-28 08:51:18 -0700106 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
122bool 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;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100132 authenticate_params.Digest(Digest::SHA_2_256);
Darren Krahn251cb282015-09-28 08:51:18 -0700133 AuthorizationSet output_params;
134 std::string output_data;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100135 if (!oneShotOperation(KeyPurpose::VERIFY, authentication_key_name, authenticate_params,
Darren Krahn251cb282015-09-28 08:51:18 -0700136 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;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100143 encrypt_params.Padding(PaddingMode::PKCS7);
144 encrypt_params.Authorization(TAG_BLOCK_MODE, BlockMode::CBC);
145 encrypt_params.Authorization(TAG_NONCE, protobuf.init_vector().data(),
Darren Krahn251cb282015-09-28 08:51:18 -0700146 protobuf.init_vector().size());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100147 if (!oneShotOperation(KeyPurpose::DECRYPT, encryption_key_name, encrypt_params,
Darren Krahn251cb282015-09-28 08:51:18 -0700148 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
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100156bool KeystoreClientImpl::oneShotOperation(KeyPurpose purpose, const std::string& key_name,
157 const AuthorizationSet& input_parameters,
Darren Krahn251cb282015-09-28 08:51:18 -0700158 const std::string& input_data,
159 const std::string& signature_to_verify,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100160 AuthorizationSet* output_parameters,
Darren Krahn251cb282015-09-28 08:51:18 -0700161 std::string* output_data) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100162 uint64_t handle;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700163 auto result = beginOperation(purpose, key_name, input_parameters, output_parameters, &handle);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100164 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800165 ALOGE("BeginOperation failed: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700166 return false;
167 }
168 AuthorizationSet empty_params;
169 size_t num_input_bytes_consumed;
170 AuthorizationSet ignored_params;
171 result = updateOperation(handle, empty_params, input_data, &num_input_bytes_consumed,
172 &ignored_params, output_data);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100173 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800174 ALOGE("UpdateOperation failed: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700175 return false;
176 }
177 result =
178 finishOperation(handle, empty_params, signature_to_verify, &ignored_params, output_data);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100179 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800180 ALOGE("FinishOperation failed: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700181 return false;
182 }
183 return true;
184}
185
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700186KeyStoreNativeReturnCode
Janis Danisevskisc1460142017-12-18 16:48:46 -0800187KeystoreClientImpl::addRandomNumberGeneratorEntropy(const std::string& entropy, int32_t flags) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600188 int32_t error_code;
189
190 android::sp<KeystoreResponsePromise> promise(new KeystoreResponsePromise());
191 auto future = promise->get_future();
192
193 auto binder_result =
194 keystore_->addRngEntropy(promise, blob2hidlVec(entropy), flags, &error_code);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700195 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600196
197 KeyStoreNativeReturnCode rc(error_code);
198 if (!rc.isOk()) return rc;
199
200 auto result = future.get();
201
202 return KeyStoreNativeReturnCode(result.response_code());
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700203}
204
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700205KeyStoreNativeReturnCode
206KeystoreClientImpl::generateKey(const std::string& key_name, const AuthorizationSet& key_parameters,
Janis Danisevskisc1460142017-12-18 16:48:46 -0800207 int32_t flags, AuthorizationSet* hardware_enforced_characteristics,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700208 AuthorizationSet* software_enforced_characteristics) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700209 String16 key_name16(key_name.data(), key_name.size());
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600210 int32_t error_code;
211 android::sp<KeyCharacteristicsPromise> promise(new KeyCharacteristicsPromise);
212 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700213 auto binder_result = keystore_->generateKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600214 promise, key_name16,
215 ::android::security::keymaster::KeymasterArguments(key_parameters.hidl_data()),
216 hidl_vec<uint8_t>() /* entropy */, kDefaultUID, flags, &error_code);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700217 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100218
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600219 KeyStoreNativeReturnCode rc(error_code);
220 if (!rc.isOk()) return rc;
221
222 auto [km_response, characteristics] = future.get();
223
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100224 /* assignment (hidl_vec<KeyParameter> -> AuthorizationSet) makes a deep copy.
225 * There are no references to Parcel memory after that, and ownership of the newly acquired
226 * memory is with the AuthorizationSet objects. */
Shawn Willden0329a822017-12-04 13:55:14 -0700227 *hardware_enforced_characteristics = characteristics.hardwareEnforced.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700228 *software_enforced_characteristics = characteristics.softwareEnforced.getParameters();
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600229 return KeyStoreNativeReturnCode(km_response.response_code());
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700230}
231
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100232KeyStoreNativeReturnCode
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700233KeystoreClientImpl::getKeyCharacteristics(const std::string& key_name,
234 AuthorizationSet* hardware_enforced_characteristics,
235 AuthorizationSet* software_enforced_characteristics) {
236 String16 key_name16(key_name.data(), key_name.size());
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600237 int32_t error_code;
238 android::sp<KeyCharacteristicsPromise> promise(new KeyCharacteristicsPromise);
239 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700240 auto binder_result = keystore_->getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600241 promise, key_name16, android::security::keymaster::KeymasterBlob(),
242 android::security::keymaster::KeymasterBlob(), kDefaultUID, &error_code);
243 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
244
245 KeyStoreNativeReturnCode rc(error_code);
246 if (!rc.isOk()) return rc;
247
248 auto [km_response, characteristics] = future.get();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100249
250 /* assignment (hidl_vec<KeyParameter> -> AuthorizationSet) makes a deep copy.
251 * There are no references to Parcel memory after that, and ownership of the newly acquired
252 * memory is with the AuthorizationSet objects. */
Shawn Willden0329a822017-12-04 13:55:14 -0700253 *hardware_enforced_characteristics = characteristics.hardwareEnforced.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700254 *software_enforced_characteristics = characteristics.softwareEnforced.getParameters();
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600255 return KeyStoreNativeReturnCode(km_response.response_code());
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700256}
257
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700258KeyStoreNativeReturnCode
259KeystoreClientImpl::importKey(const std::string& key_name, const AuthorizationSet& key_parameters,
260 KeyFormat key_format, const std::string& key_data,
261 AuthorizationSet* hardware_enforced_characteristics,
262 AuthorizationSet* software_enforced_characteristics) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700263 String16 key_name16(key_name.data(), key_name.size());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100264 auto hidlKeyData = blob2hidlVec(key_data);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600265 int32_t error_code;
266 android::sp<KeyCharacteristicsPromise> promise(new KeyCharacteristicsPromise);
267 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700268 auto binder_result = keystore_->importKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600269 promise, key_name16,
270 ::android::security::keymaster::KeymasterArguments(key_parameters.hidl_data()),
271 (int)key_format, hidlKeyData, kDefaultUID, KEYSTORE_FLAG_NONE, &error_code);
272 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
273
274 KeyStoreNativeReturnCode rc(error_code);
275 if (!rc.isOk()) return rc;
276
277 auto [km_response, characteristics] = future.get();
278
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100279 /* assignment (hidl_vec<KeyParameter> -> AuthorizationSet) makes a deep copy.
280 * There are no references to Parcel memory after that, and ownership of the newly acquired
281 * memory is with the AuthorizationSet objects. */
Shawn Willden0329a822017-12-04 13:55:14 -0700282 *hardware_enforced_characteristics = characteristics.hardwareEnforced.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700283 *software_enforced_characteristics = characteristics.softwareEnforced.getParameters();
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600284 return KeyStoreNativeReturnCode(km_response.response_code());
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700285}
286
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100287KeyStoreNativeReturnCode KeystoreClientImpl::exportKey(KeyFormat export_format,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700288 const std::string& key_name,
289 std::string* export_data) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700290 String16 key_name16(key_name.data(), key_name.size());
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600291 int32_t error_code;
292 android::sp<KeystoreExportPromise> promise(new KeystoreExportPromise);
293 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700294 auto binder_result = keystore_->exportKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600295 promise, key_name16, (int)export_format, android::security::keymaster::KeymasterBlob(),
296 android::security::keymaster::KeymasterBlob(), kDefaultUID, &error_code);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700297 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600298
299 KeyStoreNativeReturnCode rc(error_code);
300 if (!rc.isOk()) return rc;
301
302 auto export_result = future.get();
303 if (!export_result.resultCode.isOk()) return export_result.resultCode;
304
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100305 *export_data = hidlVec2String(export_result.exportData);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600306
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100307 return export_result.resultCode;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700308}
309
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100310KeyStoreNativeReturnCode KeystoreClientImpl::deleteKey(const std::string& key_name) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700311 String16 key_name16(key_name.data(), key_name.size());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700312 int32_t result;
313 auto binder_result = keystore_->del(key_name16, kDefaultUID, &result);
314 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
315 return KeyStoreNativeReturnCode(result);
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700316}
317
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100318KeyStoreNativeReturnCode KeystoreClientImpl::deleteAllKeys() {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700319 int32_t result;
320 auto binder_result = keystore_->clear_uid(kDefaultUID, &result);
321 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
322 return KeyStoreNativeReturnCode(result);
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700323}
324
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700325KeyStoreNativeReturnCode
326KeystoreClientImpl::beginOperation(KeyPurpose purpose, const std::string& key_name,
327 const AuthorizationSet& input_parameters,
328 AuthorizationSet* output_parameters, uint64_t* handle) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700329 android::sp<android::IBinder> token(new android::BBinder);
330 String16 key_name16(key_name.data(), key_name.size());
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600331 int32_t error_code;
332 android::sp<OperationResultPromise> promise(new OperationResultPromise{});
333 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700334 auto binder_result = keystore_->begin(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600335 promise, token, key_name16, (int)purpose, true /*pruneable*/,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700336 android::security::keymaster::KeymasterArguments(input_parameters.hidl_data()),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600337 hidl_vec<uint8_t>() /* entropy */, kDefaultUID, &error_code);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700338 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600339 KeyStoreNativeReturnCode rc(error_code);
340 if (!rc.isOk()) return rc;
341
342 OperationResult result = future.get();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100343 if (result.resultCode.isOk()) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700344 *handle = getNextVirtualHandle();
345 active_operations_[*handle] = result.token;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100346 if (result.outParams.size()) {
347 *output_parameters = result.outParams;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700348 }
349 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100350 return result.resultCode;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700351}
352
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700353KeyStoreNativeReturnCode
354KeystoreClientImpl::updateOperation(uint64_t handle, const AuthorizationSet& input_parameters,
355 const std::string& input_data, size_t* num_input_bytes_consumed,
356 AuthorizationSet* output_parameters, std::string* output_data) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700357 if (active_operations_.count(handle) == 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100358 return ErrorCode::INVALID_OPERATION_HANDLE;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700359 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100360 auto hidlInputData = blob2hidlVec(input_data);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600361 int32_t error_code;
362 android::sp<OperationResultPromise> promise(new OperationResultPromise{});
363 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700364 auto binder_result = keystore_->update(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600365 promise, active_operations_[handle],
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700366 android::security::keymaster::KeymasterArguments(input_parameters.hidl_data()),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600367 hidlInputData, &error_code);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700368 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600369 KeyStoreNativeReturnCode rc(error_code);
370 if (!rc.isOk()) return rc;
371
372 OperationResult result = future.get();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100373
374 if (result.resultCode.isOk()) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700375 *num_input_bytes_consumed = result.inputConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100376 if (result.outParams.size()) {
377 *output_parameters = result.outParams;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700378 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100379 // TODO verify that append should not be assign
380 output_data->append(hidlVec2String(result.data));
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700381 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100382 return result.resultCode;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700383}
384
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700385KeyStoreNativeReturnCode
386KeystoreClientImpl::finishOperation(uint64_t handle, const AuthorizationSet& input_parameters,
387 const std::string& signature_to_verify,
388 AuthorizationSet* output_parameters, std::string* output_data) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700389 if (active_operations_.count(handle) == 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100390 return ErrorCode::INVALID_OPERATION_HANDLE;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700391 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600392 int32_t error_code;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100393 auto hidlSignature = blob2hidlVec(signature_to_verify);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600394 android::sp<OperationResultPromise> promise(new OperationResultPromise{});
395 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700396 auto binder_result = keystore_->finish(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600397 promise, active_operations_[handle],
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700398 android::security::keymaster::KeymasterArguments(input_parameters.hidl_data()),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600399 (std::vector<uint8_t>)hidlSignature, hidl_vec<uint8_t>(), &error_code);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700400 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600401 KeyStoreNativeReturnCode rc(error_code);
402 if (!rc.isOk()) return rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100403
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600404 OperationResult result = future.get();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100405 if (result.resultCode.isOk()) {
406 if (result.outParams.size()) {
407 *output_parameters = result.outParams;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700408 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100409 // TODO verify that append should not be assign
410 output_data->append(hidlVec2String(result.data));
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700411 active_operations_.erase(handle);
412 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100413 return result.resultCode;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700414}
415
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100416KeyStoreNativeReturnCode KeystoreClientImpl::abortOperation(uint64_t handle) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700417 if (active_operations_.count(handle) == 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100418 return ErrorCode::INVALID_OPERATION_HANDLE;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700419 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700420 int32_t result;
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600421 android::sp<KeystoreResponsePromise> promise(new KeystoreResponsePromise{});
422 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700423 // Current implementation does not return exceptions in android::binder::Status
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600424 auto binder_result = keystore_->abort(promise, active_operations_[handle], &result);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700425 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600426 KeyStoreNativeReturnCode rc(result);
427 if (!rc.isOk()) return rc;
428 rc = KeyStoreNativeReturnCode(future.get().response_code());
429 if (rc.isOk()) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700430 active_operations_.erase(handle);
431 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600432 return rc;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700433}
434
435bool KeystoreClientImpl::doesKeyExist(const std::string& key_name) {
436 String16 key_name16(key_name.data(), key_name.size());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700437 int32_t result;
438 auto binder_result = keystore_->exist(key_name16, kDefaultUID, &result);
439 if (!binder_result.isOk()) return false; // binder error
Branden Archer1a87fdc2018-11-21 14:58:01 -0800440 return result == static_cast<int32_t>(ResponseCode::NO_ERROR);
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700441}
442
443bool KeystoreClientImpl::listKeys(const std::string& prefix,
444 std::vector<std::string>* key_name_list) {
Victor Hsieh8b3b6fc2019-09-05 14:27:38 -0700445 return listKeysOfUid(prefix, kDefaultUID, key_name_list);
446}
447
448bool KeystoreClientImpl::listKeysOfUid(const std::string& prefix, int uid,
449 std::vector<std::string>* key_name_list) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700450 String16 prefix16(prefix.data(), prefix.size());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700451 std::vector<::android::String16> matches;
Victor Hsieh8b3b6fc2019-09-05 14:27:38 -0700452 auto binder_result = keystore_->list(prefix16, uid, &matches);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700453 if (!binder_result.isOk()) return false;
454
455 for (const auto& match : matches) {
456 android::String8 key_name(match);
457 key_name_list->push_back(prefix + std::string(key_name.string(), key_name.size()));
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700458 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700459 return true;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700460}
461
Victor Hsieh8b3b6fc2019-09-05 14:27:38 -0700462std::optional<std::vector<uint8_t>> KeystoreClientImpl::getKey(const std::string& alias, int uid) {
463 String16 alias16(alias.data(), alias.size());
464 std::vector<uint8_t> output;
465 auto binder_result = keystore_->get(alias16, uid, &output);
466 if (!binder_result.isOk()) return std::nullopt;
467 return output;
468}
469
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100470uint64_t KeystoreClientImpl::getNextVirtualHandle() {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700471 return next_virtual_handle_++;
472}
473
Janis Danisevskisc1460142017-12-18 16:48:46 -0800474bool KeystoreClientImpl::createOrVerifyEncryptionKey(const std::string& key_name, int32_t flags) {
Darren Krahn251cb282015-09-28 08:51:18 -0700475 bool key_exists = doesKeyExist(key_name);
476 if (key_exists) {
477 bool verified = false;
478 if (!verifyEncryptionKeyAttributes(key_name, &verified)) {
479 return false;
480 }
481 if (!verified) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100482 auto result = deleteKey(key_name);
483 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800484 ALOGE("Failed to delete invalid encryption key: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700485 return false;
486 }
487 key_exists = false;
488 }
489 }
490 if (!key_exists) {
491 AuthorizationSetBuilder key_parameters;
492 key_parameters.AesEncryptionKey(kAESKeySize)
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100493 .Padding(PaddingMode::PKCS7)
494 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
495 .Authorization(TAG_NO_AUTH_REQUIRED);
Darren Krahn251cb282015-09-28 08:51:18 -0700496 AuthorizationSet hardware_enforced_characteristics;
497 AuthorizationSet software_enforced_characteristics;
Janis Danisevskisc1460142017-12-18 16:48:46 -0800498 auto result =
499 generateKey(key_name, key_parameters, flags, &hardware_enforced_characteristics,
500 &software_enforced_characteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100501 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800502 ALOGE("Failed to generate encryption key: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700503 return false;
504 }
505 if (hardware_enforced_characteristics.size() == 0) {
506 ALOGW("WARNING: Encryption key is not hardware-backed.");
507 }
508 }
509 return true;
510}
511
Janis Danisevskisc1460142017-12-18 16:48:46 -0800512bool KeystoreClientImpl::createOrVerifyAuthenticationKey(const std::string& key_name,
513 int32_t flags) {
Darren Krahn251cb282015-09-28 08:51:18 -0700514 bool key_exists = doesKeyExist(key_name);
515 if (key_exists) {
516 bool verified = false;
517 if (!verifyAuthenticationKeyAttributes(key_name, &verified)) {
518 return false;
519 }
520 if (!verified) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100521 auto result = deleteKey(key_name);
522 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800523 ALOGE("Failed to delete invalid authentication key: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700524 return false;
525 }
526 key_exists = false;
527 }
528 }
529 if (!key_exists) {
530 AuthorizationSetBuilder key_parameters;
531 key_parameters.HmacKey(kHMACKeySize)
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100532 .Digest(Digest::SHA_2_256)
533 .Authorization(TAG_MIN_MAC_LENGTH, kHMACOutputSize)
534 .Authorization(TAG_NO_AUTH_REQUIRED);
Darren Krahn251cb282015-09-28 08:51:18 -0700535 AuthorizationSet hardware_enforced_characteristics;
536 AuthorizationSet software_enforced_characteristics;
Janis Danisevskisc1460142017-12-18 16:48:46 -0800537 auto result =
538 generateKey(key_name, key_parameters, flags, &hardware_enforced_characteristics,
539 &software_enforced_characteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100540 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800541 ALOGE("Failed to generate authentication key: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700542 return false;
543 }
544 if (hardware_enforced_characteristics.size() == 0) {
545 ALOGW("WARNING: Authentication key is not hardware-backed.");
546 }
547 }
548 return true;
549}
550
551bool KeystoreClientImpl::verifyEncryptionKeyAttributes(const std::string& key_name,
552 bool* verified) {
553 AuthorizationSet hardware_enforced_characteristics;
554 AuthorizationSet software_enforced_characteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100555 auto result = getKeyCharacteristics(key_name, &hardware_enforced_characteristics,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700556 &software_enforced_characteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100557 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800558 ALOGE("Failed to query encryption key: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700559 return false;
560 }
561 *verified = true;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100562 auto algorithm = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_ALGORITHM),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700563 software_enforced_characteristics.GetTagValue(TAG_ALGORITHM));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100564 if (!algorithm.isOk() || algorithm.value() != Algorithm::AES) {
Darren Krahn251cb282015-09-28 08:51:18 -0700565 ALOGW("Found encryption key with invalid algorithm.");
566 *verified = false;
567 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100568 auto key_size = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_KEY_SIZE),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700569 software_enforced_characteristics.GetTagValue(TAG_KEY_SIZE));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100570 if (!key_size.isOk() || key_size.value() != kAESKeySize) {
Darren Krahn251cb282015-09-28 08:51:18 -0700571 ALOGW("Found encryption key with invalid size.");
572 *verified = false;
573 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100574 auto block_mode = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_BLOCK_MODE),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700575 software_enforced_characteristics.GetTagValue(TAG_BLOCK_MODE));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100576 if (!block_mode.isOk() || block_mode.value() != BlockMode::CBC) {
Darren Krahn251cb282015-09-28 08:51:18 -0700577 ALOGW("Found encryption key with invalid block mode.");
578 *verified = false;
579 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100580 auto padding_mode = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_PADDING),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700581 software_enforced_characteristics.GetTagValue(TAG_PADDING));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100582 if (!padding_mode.isOk() || padding_mode.value() != PaddingMode::PKCS7) {
Darren Krahn251cb282015-09-28 08:51:18 -0700583 ALOGW("Found encryption key with invalid padding mode.");
584 *verified = false;
585 }
586 if (hardware_enforced_characteristics.size() == 0) {
587 ALOGW("WARNING: Encryption key is not hardware-backed.");
588 }
589 return true;
590}
591
592bool KeystoreClientImpl::verifyAuthenticationKeyAttributes(const std::string& key_name,
593 bool* verified) {
594 AuthorizationSet hardware_enforced_characteristics;
595 AuthorizationSet software_enforced_characteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100596 auto result = getKeyCharacteristics(key_name, &hardware_enforced_characteristics,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700597 &software_enforced_characteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100598 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800599 ALOGE("Failed to query authentication key: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700600 return false;
601 }
602 *verified = true;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100603 auto algorithm = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_ALGORITHM),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700604 software_enforced_characteristics.GetTagValue(TAG_ALGORITHM));
605 if (!algorithm.isOk() || algorithm.value() != Algorithm::HMAC) {
Darren Krahn251cb282015-09-28 08:51:18 -0700606 ALOGW("Found authentication key with invalid algorithm.");
607 *verified = false;
608 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100609 auto key_size = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_KEY_SIZE),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700610 software_enforced_characteristics.GetTagValue(TAG_KEY_SIZE));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100611 if (!key_size.isOk() || key_size.value() != kHMACKeySize) {
Darren Krahn251cb282015-09-28 08:51:18 -0700612 ALOGW("Found authentication key with invalid size.");
613 *verified = false;
614 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100615 auto mac_size = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_MIN_MAC_LENGTH),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700616 software_enforced_characteristics.GetTagValue(TAG_MIN_MAC_LENGTH));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100617 if (!mac_size.isOk() || mac_size.value() != kHMACOutputSize) {
Darren Krahn251cb282015-09-28 08:51:18 -0700618 ALOGW("Found authentication key with invalid minimum mac size.");
619 *verified = false;
620 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100621 auto digest = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_DIGEST),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700622 software_enforced_characteristics.GetTagValue(TAG_DIGEST));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100623 if (!digest.isOk() || digest.value() != Digest::SHA_2_256) {
Darren Krahn251cb282015-09-28 08:51:18 -0700624 ALOGW("Found authentication key with invalid digest list.");
625 *verified = false;
626 }
627 if (hardware_enforced_characteristics.size() == 0) {
628 ALOGW("WARNING: Authentication key is not hardware-backed.");
629 }
630 return true;
631}
632
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700633} // namespace keystore