blob: f88868394602352288e3d781e14f0c9922f48a09 [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;
Darren Krahn251cb282015-09-28 08:51:18 -0700169 AuthorizationSet ignored_params;
Rob Barnes3af223f2019-11-14 14:50:30 -0700170 result = finishOperation(handle, empty_params, input_data, signature_to_verify, &ignored_params,
171 output_data);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100172 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800173 ALOGE("FinishOperation failed: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700174 return false;
175 }
176 return true;
177}
178
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700179KeyStoreNativeReturnCode
Janis Danisevskisc1460142017-12-18 16:48:46 -0800180KeystoreClientImpl::addRandomNumberGeneratorEntropy(const std::string& entropy, int32_t flags) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600181 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);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700188 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600189
190 KeyStoreNativeReturnCode rc(error_code);
191 if (!rc.isOk()) return rc;
192
193 auto result = future.get();
194
195 return KeyStoreNativeReturnCode(result.response_code());
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700196}
197
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700198KeyStoreNativeReturnCode
199KeystoreClientImpl::generateKey(const std::string& key_name, const AuthorizationSet& key_parameters,
Janis Danisevskisc1460142017-12-18 16:48:46 -0800200 int32_t flags, AuthorizationSet* hardware_enforced_characteristics,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700201 AuthorizationSet* software_enforced_characteristics) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700202 String16 key_name16(key_name.data(), key_name.size());
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600203 int32_t error_code;
204 android::sp<KeyCharacteristicsPromise> promise(new KeyCharacteristicsPromise);
205 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700206 auto binder_result = keystore_->generateKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600207 promise, key_name16,
208 ::android::security::keymaster::KeymasterArguments(key_parameters.hidl_data()),
209 hidl_vec<uint8_t>() /* entropy */, kDefaultUID, flags, &error_code);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700210 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100211
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600212 KeyStoreNativeReturnCode rc(error_code);
213 if (!rc.isOk()) return rc;
214
215 auto [km_response, characteristics] = future.get();
216
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100217 /* 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. */
Shawn Willden0329a822017-12-04 13:55:14 -0700220 *hardware_enforced_characteristics = characteristics.hardwareEnforced.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700221 *software_enforced_characteristics = characteristics.softwareEnforced.getParameters();
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600222 return KeyStoreNativeReturnCode(km_response.response_code());
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700223}
224
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100225KeyStoreNativeReturnCode
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700226KeystoreClientImpl::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());
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600230 int32_t error_code;
231 android::sp<KeyCharacteristicsPromise> promise(new KeyCharacteristicsPromise);
232 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700233 auto binder_result = keystore_->getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600234 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();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100242
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. */
Shawn Willden0329a822017-12-04 13:55:14 -0700246 *hardware_enforced_characteristics = characteristics.hardwareEnforced.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700247 *software_enforced_characteristics = characteristics.softwareEnforced.getParameters();
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600248 return KeyStoreNativeReturnCode(km_response.response_code());
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700249}
250
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700251KeyStoreNativeReturnCode
252KeystoreClientImpl::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) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700256 String16 key_name16(key_name.data(), key_name.size());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100257 auto hidlKeyData = blob2hidlVec(key_data);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600258 int32_t error_code;
259 android::sp<KeyCharacteristicsPromise> promise(new KeyCharacteristicsPromise);
260 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700261 auto binder_result = keystore_->importKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600262 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
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100272 /* 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. */
Shawn Willden0329a822017-12-04 13:55:14 -0700275 *hardware_enforced_characteristics = characteristics.hardwareEnforced.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700276 *software_enforced_characteristics = characteristics.softwareEnforced.getParameters();
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600277 return KeyStoreNativeReturnCode(km_response.response_code());
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700278}
279
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100280KeyStoreNativeReturnCode KeystoreClientImpl::exportKey(KeyFormat export_format,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700281 const std::string& key_name,
282 std::string* export_data) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700283 String16 key_name16(key_name.data(), key_name.size());
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600284 int32_t error_code;
285 android::sp<KeystoreExportPromise> promise(new KeystoreExportPromise);
286 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700287 auto binder_result = keystore_->exportKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600288 promise, key_name16, (int)export_format, android::security::keymaster::KeymasterBlob(),
289 android::security::keymaster::KeymasterBlob(), kDefaultUID, &error_code);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700290 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600291
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
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100298 *export_data = hidlVec2String(export_result.exportData);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600299
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100300 return export_result.resultCode;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700301}
302
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100303KeyStoreNativeReturnCode KeystoreClientImpl::deleteKey(const std::string& key_name) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700304 String16 key_name16(key_name.data(), key_name.size());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700305 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);
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700309}
310
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100311KeyStoreNativeReturnCode KeystoreClientImpl::deleteAllKeys() {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700312 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);
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700316}
317
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700318KeyStoreNativeReturnCode
319KeystoreClientImpl::beginOperation(KeyPurpose purpose, const std::string& key_name,
320 const AuthorizationSet& input_parameters,
321 AuthorizationSet* output_parameters, uint64_t* handle) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700322 android::sp<android::IBinder> token(new android::BBinder);
323 String16 key_name16(key_name.data(), key_name.size());
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600324 int32_t error_code;
325 android::sp<OperationResultPromise> promise(new OperationResultPromise{});
326 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700327 auto binder_result = keystore_->begin(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600328 promise, token, key_name16, (int)purpose, true /*pruneable*/,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700329 android::security::keymaster::KeymasterArguments(input_parameters.hidl_data()),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600330 hidl_vec<uint8_t>() /* entropy */, kDefaultUID, &error_code);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700331 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600332 KeyStoreNativeReturnCode rc(error_code);
333 if (!rc.isOk()) return rc;
334
335 OperationResult result = future.get();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100336 if (result.resultCode.isOk()) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700337 *handle = getNextVirtualHandle();
338 active_operations_[*handle] = result.token;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100339 if (result.outParams.size()) {
340 *output_parameters = result.outParams;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700341 }
342 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100343 return result.resultCode;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700344}
345
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700346KeyStoreNativeReturnCode
347KeystoreClientImpl::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) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700350 if (active_operations_.count(handle) == 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100351 return ErrorCode::INVALID_OPERATION_HANDLE;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700352 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100353 auto hidlInputData = blob2hidlVec(input_data);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600354 int32_t error_code;
355 android::sp<OperationResultPromise> promise(new OperationResultPromise{});
356 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700357 auto binder_result = keystore_->update(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600358 promise, active_operations_[handle],
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700359 android::security::keymaster::KeymasterArguments(input_parameters.hidl_data()),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600360 hidlInputData, &error_code);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700361 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600362 KeyStoreNativeReturnCode rc(error_code);
363 if (!rc.isOk()) return rc;
364
365 OperationResult result = future.get();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100366
367 if (result.resultCode.isOk()) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700368 *num_input_bytes_consumed = result.inputConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100369 if (result.outParams.size()) {
370 *output_parameters = result.outParams;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700371 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100372 // TODO verify that append should not be assign
373 output_data->append(hidlVec2String(result.data));
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700374 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100375 return result.resultCode;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700376}
377
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700378KeyStoreNativeReturnCode
379KeystoreClientImpl::finishOperation(uint64_t handle, const AuthorizationSet& input_parameters,
Rob Barnes3af223f2019-11-14 14:50:30 -0700380 const std::string& input_data,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700381 const std::string& signature_to_verify,
382 AuthorizationSet* output_parameters, std::string* output_data) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700383 if (active_operations_.count(handle) == 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100384 return ErrorCode::INVALID_OPERATION_HANDLE;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700385 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600386 int32_t error_code;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100387 auto hidlSignature = blob2hidlVec(signature_to_verify);
Rob Barnes3af223f2019-11-14 14:50:30 -0700388 auto hidlInput = blob2hidlVec(input_data);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600389 android::sp<OperationResultPromise> promise(new OperationResultPromise{});
390 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700391 auto binder_result = keystore_->finish(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600392 promise, active_operations_[handle],
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700393 android::security::keymaster::KeymasterArguments(input_parameters.hidl_data()),
Rob Barnes3af223f2019-11-14 14:50:30 -0700394 (std::vector<uint8_t>)hidlInput, (std::vector<uint8_t>)hidlSignature, hidl_vec<uint8_t>(),
395 &error_code);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700396 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600397 KeyStoreNativeReturnCode rc(error_code);
398 if (!rc.isOk()) return rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100399
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600400 OperationResult result = future.get();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100401 if (result.resultCode.isOk()) {
402 if (result.outParams.size()) {
403 *output_parameters = result.outParams;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700404 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100405 // TODO verify that append should not be assign
406 output_data->append(hidlVec2String(result.data));
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700407 active_operations_.erase(handle);
408 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100409 return result.resultCode;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700410}
411
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100412KeyStoreNativeReturnCode KeystoreClientImpl::abortOperation(uint64_t handle) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700413 if (active_operations_.count(handle) == 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100414 return ErrorCode::INVALID_OPERATION_HANDLE;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700415 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700416 int32_t result;
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600417 android::sp<KeystoreResponsePromise> promise(new KeystoreResponsePromise{});
418 auto future = promise->get_future();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700419 // Current implementation does not return exceptions in android::binder::Status
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600420 auto binder_result = keystore_->abort(promise, active_operations_[handle], &result);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700421 if (!binder_result.isOk()) return ResponseCode::SYSTEM_ERROR;
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600422 KeyStoreNativeReturnCode rc(result);
423 if (!rc.isOk()) return rc;
424 rc = KeyStoreNativeReturnCode(future.get().response_code());
425 if (rc.isOk()) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700426 active_operations_.erase(handle);
427 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600428 return rc;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700429}
430
431bool KeystoreClientImpl::doesKeyExist(const std::string& key_name) {
432 String16 key_name16(key_name.data(), key_name.size());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700433 int32_t result;
434 auto binder_result = keystore_->exist(key_name16, kDefaultUID, &result);
435 if (!binder_result.isOk()) return false; // binder error
Branden Archer1a87fdc2018-11-21 14:58:01 -0800436 return result == static_cast<int32_t>(ResponseCode::NO_ERROR);
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700437}
438
439bool KeystoreClientImpl::listKeys(const std::string& prefix,
440 std::vector<std::string>* key_name_list) {
Victor Hsieh8b3b6fc2019-09-05 14:27:38 -0700441 return listKeysOfUid(prefix, kDefaultUID, key_name_list);
442}
443
444bool KeystoreClientImpl::listKeysOfUid(const std::string& prefix, int uid,
445 std::vector<std::string>* key_name_list) {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700446 String16 prefix16(prefix.data(), prefix.size());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700447 std::vector<::android::String16> matches;
Victor Hsieh8b3b6fc2019-09-05 14:27:38 -0700448 auto binder_result = keystore_->list(prefix16, uid, &matches);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700449 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()));
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700454 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700455 return true;
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700456}
457
Victor Hsieh8b3b6fc2019-09-05 14:27:38 -0700458std::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
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100466uint64_t KeystoreClientImpl::getNextVirtualHandle() {
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700467 return next_virtual_handle_++;
468}
469
Janis Danisevskisc1460142017-12-18 16:48:46 -0800470bool KeystoreClientImpl::createOrVerifyEncryptionKey(const std::string& key_name, int32_t flags) {
Darren Krahn251cb282015-09-28 08:51:18 -0700471 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) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100478 auto result = deleteKey(key_name);
479 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800480 ALOGE("Failed to delete invalid encryption key: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700481 return false;
482 }
483 key_exists = false;
484 }
485 }
486 if (!key_exists) {
487 AuthorizationSetBuilder key_parameters;
488 key_parameters.AesEncryptionKey(kAESKeySize)
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100489 .Padding(PaddingMode::PKCS7)
490 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
491 .Authorization(TAG_NO_AUTH_REQUIRED);
Darren Krahn251cb282015-09-28 08:51:18 -0700492 AuthorizationSet hardware_enforced_characteristics;
493 AuthorizationSet software_enforced_characteristics;
Janis Danisevskisc1460142017-12-18 16:48:46 -0800494 auto result =
495 generateKey(key_name, key_parameters, flags, &hardware_enforced_characteristics,
496 &software_enforced_characteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100497 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800498 ALOGE("Failed to generate encryption key: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700499 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
Janis Danisevskisc1460142017-12-18 16:48:46 -0800508bool KeystoreClientImpl::createOrVerifyAuthenticationKey(const std::string& key_name,
509 int32_t flags) {
Darren Krahn251cb282015-09-28 08:51:18 -0700510 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) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100517 auto result = deleteKey(key_name);
518 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800519 ALOGE("Failed to delete invalid authentication key: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700520 return false;
521 }
522 key_exists = false;
523 }
524 }
525 if (!key_exists) {
526 AuthorizationSetBuilder key_parameters;
527 key_parameters.HmacKey(kHMACKeySize)
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100528 .Digest(Digest::SHA_2_256)
529 .Authorization(TAG_MIN_MAC_LENGTH, kHMACOutputSize)
530 .Authorization(TAG_NO_AUTH_REQUIRED);
Darren Krahn251cb282015-09-28 08:51:18 -0700531 AuthorizationSet hardware_enforced_characteristics;
532 AuthorizationSet software_enforced_characteristics;
Janis Danisevskisc1460142017-12-18 16:48:46 -0800533 auto result =
534 generateKey(key_name, key_parameters, flags, &hardware_enforced_characteristics,
535 &software_enforced_characteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100536 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800537 ALOGE("Failed to generate authentication key: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700538 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
547bool KeystoreClientImpl::verifyEncryptionKeyAttributes(const std::string& key_name,
548 bool* verified) {
549 AuthorizationSet hardware_enforced_characteristics;
550 AuthorizationSet software_enforced_characteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100551 auto result = getKeyCharacteristics(key_name, &hardware_enforced_characteristics,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700552 &software_enforced_characteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100553 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800554 ALOGE("Failed to query encryption key: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700555 return false;
556 }
557 *verified = true;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100558 auto algorithm = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_ALGORITHM),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700559 software_enforced_characteristics.GetTagValue(TAG_ALGORITHM));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100560 if (!algorithm.isOk() || algorithm.value() != Algorithm::AES) {
Darren Krahn251cb282015-09-28 08:51:18 -0700561 ALOGW("Found encryption key with invalid algorithm.");
562 *verified = false;
563 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100564 auto key_size = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_KEY_SIZE),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700565 software_enforced_characteristics.GetTagValue(TAG_KEY_SIZE));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100566 if (!key_size.isOk() || key_size.value() != kAESKeySize) {
Darren Krahn251cb282015-09-28 08:51:18 -0700567 ALOGW("Found encryption key with invalid size.");
568 *verified = false;
569 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100570 auto block_mode = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_BLOCK_MODE),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700571 software_enforced_characteristics.GetTagValue(TAG_BLOCK_MODE));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100572 if (!block_mode.isOk() || block_mode.value() != BlockMode::CBC) {
Darren Krahn251cb282015-09-28 08:51:18 -0700573 ALOGW("Found encryption key with invalid block mode.");
574 *verified = false;
575 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100576 auto padding_mode = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_PADDING),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700577 software_enforced_characteristics.GetTagValue(TAG_PADDING));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100578 if (!padding_mode.isOk() || padding_mode.value() != PaddingMode::PKCS7) {
Darren Krahn251cb282015-09-28 08:51:18 -0700579 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
588bool KeystoreClientImpl::verifyAuthenticationKeyAttributes(const std::string& key_name,
589 bool* verified) {
590 AuthorizationSet hardware_enforced_characteristics;
591 AuthorizationSet software_enforced_characteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100592 auto result = getKeyCharacteristics(key_name, &hardware_enforced_characteristics,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700593 &software_enforced_characteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100594 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800595 ALOGE("Failed to query authentication key: %d", result.getErrorCode());
Darren Krahn251cb282015-09-28 08:51:18 -0700596 return false;
597 }
598 *verified = true;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100599 auto algorithm = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_ALGORITHM),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700600 software_enforced_characteristics.GetTagValue(TAG_ALGORITHM));
601 if (!algorithm.isOk() || algorithm.value() != Algorithm::HMAC) {
Darren Krahn251cb282015-09-28 08:51:18 -0700602 ALOGW("Found authentication key with invalid algorithm.");
603 *verified = false;
604 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100605 auto key_size = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_KEY_SIZE),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700606 software_enforced_characteristics.GetTagValue(TAG_KEY_SIZE));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100607 if (!key_size.isOk() || key_size.value() != kHMACKeySize) {
Darren Krahn251cb282015-09-28 08:51:18 -0700608 ALOGW("Found authentication key with invalid size.");
609 *verified = false;
610 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100611 auto mac_size = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_MIN_MAC_LENGTH),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700612 software_enforced_characteristics.GetTagValue(TAG_MIN_MAC_LENGTH));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100613 if (!mac_size.isOk() || mac_size.value() != kHMACOutputSize) {
Darren Krahn251cb282015-09-28 08:51:18 -0700614 ALOGW("Found authentication key with invalid minimum mac size.");
615 *verified = false;
616 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100617 auto digest = NullOrOr(hardware_enforced_characteristics.GetTagValue(TAG_DIGEST),
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700618 software_enforced_characteristics.GetTagValue(TAG_DIGEST));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100619 if (!digest.isOk() || digest.value() != Digest::SHA_2_256) {
Darren Krahn251cb282015-09-28 08:51:18 -0700620 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
Darren Krahn69a3dbc2015-09-22 16:21:04 -0700629} // namespace keystore