blob: 2336e570335085993b61b2a29856092531d77d24 [file] [log] [blame]
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Janis Danisevskis011675d2016-09-01 11:41:29 +010017#define LOG_TAG "keystore"
18
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070019#include "key_store_service.h"
20
21#include <fcntl.h>
22#include <sys/stat.h>
23
Janis Danisevskis7612fd42016-09-01 11:50:02 +010024#include <algorithm>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070025#include <atomic>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070026#include <sstream>
27
Pavel Grafovff311b42018-01-24 20:34:37 +000028#include <android-base/scopeguard.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010029#include <binder/IInterface.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070030#include <binder/IPCThreadState.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010031#include <binder/IPermissionController.h>
32#include <binder/IServiceManager.h>
Brian Claire Young3133c452018-08-31 13:56:49 -070033#include <cutils/multiuser.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000034#include <log/log_event_list.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070035
36#include <private/android_filesystem_config.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000037#include <private/android_logger.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070038
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070039#include <android/hardware/confirmationui/1.0/IConfirmationUI.h>
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010040#include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070041
42#include "defaults.h"
Max Bires33aac2d2018-02-23 10:53:10 -080043#include "key_proto_handler.h"
Janis Danisevskis18f27ad2016-06-01 13:57:40 -070044#include "keystore_attestation_id.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010045#include "keystore_keymaster_enforcement.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070046#include "keystore_utils.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010047#include <keystore/keystore_hidl_support.h>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070048#include <keystore/keystore_return_types.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070049
Janis Danisevskis8f737ad2017-11-21 12:30:15 -080050#include <hardware/hw_auth_token.h>
51
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010052namespace keystore {
Shawn Willdend5a24e62017-02-28 13:53:24 -070053
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010054using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070055
Shawn Willdene2a7b522017-04-11 09:27:40 -060056namespace {
57
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070058using ::android::binder::Status;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070059using android::security::keymaster::ExportResult;
60using android::security::keymaster::KeymasterArguments;
61using android::security::keymaster::KeymasterBlob;
62using android::security::keymaster::KeymasterCertificateChain;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070063using android::security::keymaster::operationFailed;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070064using android::security::keymaster::OperationResult;
David Zeuthenc6eb7cd2017-11-27 11:33:55 -050065using ConfirmationResponseCode = android::hardware::confirmationui::V1_0::ResponseCode;
Rob Barnesbb6cabd2018-10-04 17:10:37 -060066using ::android::security::keystore::IKeystoreOperationResultCallback;
67using ::android::security::keystore::IKeystoreResponseCallback;
68using ::android::security::keystore::KeystoreResponse;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070069
Shawn Willdene2a7b522017-04-11 09:27:40 -060070constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
71const char* kTimestampFilePath = "timestamp";
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070072
73struct BIGNUM_Delete {
74 void operator()(BIGNUM* p) const { BN_free(p); }
75};
Janis Danisevskisccfff102017-05-01 11:02:51 -070076typedef std::unique_ptr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070077
Shawn Willdene2a7b522017-04-11 09:27:40 -060078bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070079 return params.end() !=
80 std::find_if(params.begin(), params.end(),
81 [&](const KeyParameter& param) { return param.tag == tag; });
Shawn Willdend5a24e62017-02-28 13:53:24 -070082}
83
Branden Archer70080742018-11-20 11:04:11 -080084#define AIDL_RETURN(rc) (*_aidl_return = KeyStoreServiceReturnCode(rc).getErrorCode(), Status::ok())
Janis Danisevskisb50236a2019-03-25 10:26:30 -070085#define KEYSTORE_SERVICE_LOCK std::lock_guard<std::mutex> keystore_lock(keystoreServiceMutex_)
Rob Barnesbb6cabd2018-10-04 17:10:37 -060086
Shawn Willdene2a7b522017-04-11 09:27:40 -060087std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
88 struct stat sbuf;
89 if (stat(kTimestampFilePath, &sbuf) == 0) {
Yi Konge353f252018-07-30 01:38:39 -070090 double diff_secs = difftime(time(nullptr), sbuf.st_ctime);
Shawn Willdene2a7b522017-04-11 09:27:40 -060091 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
92 }
93
94 if (errno != ENOENT) {
95 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
96 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
97 }
98
99 int fd = creat(kTimestampFilePath, 0600);
100 if (fd < 0) {
101 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
102 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
103 }
104
105 if (close(fd)) {
106 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
107 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
108 }
109
110 return {ResponseCode::NO_ERROR, true};
111}
112
Eran Messeri03fc4c82018-08-16 18:53:15 +0100113using ::android::security::KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200114
115KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
116 KeyStoreServiceReturnCode responseCode;
117 bool factoryResetSinceIdRotation;
118 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
119
120 if (!responseCode.isOk()) return responseCode;
121 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
122
123 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
124 if (!asn1_attestation_id_result.isOk()) {
125 ALOGE("failed to gather attestation_id");
126 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
127 }
128 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
129
130 /*
Eran Messeri03fc4c82018-08-16 18:53:15 +0100131 * The attestation application ID must not be longer than
132 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, error out if gather_attestation_application_id
133 * returned such an invalid vector.
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200134 */
135 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Eran Messeri03fc4c82018-08-16 18:53:15 +0100136 ALOGE("BUG: Gathered Attestation Application ID is too big (%d)",
137 static_cast<int32_t>(asn1_attestation_id.size()));
138 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200139 }
140
141 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
142
143 return ResponseCode::NO_ERROR;
144}
145
Shawn Willdene2a7b522017-04-11 09:27:40 -0600146} // anonymous namespace
147
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700148Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700149 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700150 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700151 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
152 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700153 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700154 *aidl_return = mKeyStore->getState(userId);
155 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700156}
157
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700158Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700159 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700160 uid_t targetUid = getEffectiveUid(uid);
161 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700162 // see keystore/keystore.h
163 return Status::fromServiceSpecificError(
164 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700165 }
166
167 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700168 ResponseCode rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700169 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700170 Blob charBlob;
171 LockedKeyBlobEntry lockedEntry;
172
173 std::tie(rc, keyBlob, charBlob, lockedEntry) =
174 mKeyStore->getKeyForName(name8, targetUid, TYPE_GENERIC);
175 if (rc != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700176 *item = ::std::vector<uint8_t>();
177 // Return empty array if key is not found
178 // TODO: consider having returned value nullable or parse exception on the client.
179 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700180 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100181 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700182 // The static_cast here is needed to prevent a move, forcing a deep copy.
183 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
184 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700185}
186
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700187Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
188 int targetUid, int32_t flags, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700189 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700190 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700191 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700192 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100193 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800194 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700195 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700196 }
197
198 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700199 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), targetUid);
200
201 if (!lockedEntry) {
202 ALOGE("failed to grab lock on blob entry %u_%s", targetUid, name8.string());
203 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_ALREADY_EXISTS);
204 return Status::ok();
205 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700206
Yi Konge353f252018-07-30 01:38:39 -0700207 Blob keyBlob(&item[0], item.size(), nullptr, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700208 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
209
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700210 *aidl_return = static_cast<int32_t>(mKeyStore->put(lockedEntry, keyBlob, {}));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700211 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700212}
213
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700214Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700215 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700216 targetUid = getEffectiveUid(targetUid);
217 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700218 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
219 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700220 }
221 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000222 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700223 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
224 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700225 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
226 return Status::ok();
227 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700228
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700229 ResponseCode result = mKeyStore->del(lockedEntry);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400230
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700231 *aidl_return = static_cast<int32_t>(result);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700232 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700233}
234
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700235Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700236 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700237 targetUid = getEffectiveUid(targetUid);
238 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700239 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
240 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700241 }
242
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700243 LockedKeyBlobEntry lockedEntry =
244 mKeyStore->getLockedBlobEntryIfExists(String8(name).string(), targetUid);
245 *aidl_return =
246 static_cast<int32_t>(lockedEntry ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700247 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700248}
249
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700250Status KeyStoreService::list(const String16& prefix, int32_t targetUid,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700251 ::std::vector<::android::String16>* matches) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700252 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700253 targetUid = getEffectiveUid(targetUid);
254 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700255 return Status::fromServiceSpecificError(
256 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700257 }
258 const String8 prefix8(prefix);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700259 const std::string stdPrefix(prefix8.string());
260
261 ResponseCode rc;
262 std::list<LockedKeyBlobEntry> internal_matches;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800263 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700264
Janis Danisevskis265435f2018-11-16 14:10:46 -0800265 std::tie(rc, internal_matches) =
266 LockedKeyBlobEntry::list(userDirName, [&](uid_t uid, const std::string& alias) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700267 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end());
268 return uid == static_cast<uid_t>(targetUid) &&
269 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end())
270 .first == stdPrefix.end();
271 });
272
273 if (rc != ResponseCode::NO_ERROR) {
274 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700275 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700276
277 for (LockedKeyBlobEntry& entry : internal_matches) {
278 matches->push_back(String16(entry->alias().substr(prefix8.size()).c_str()));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700279 }
280 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700281}
282
Rob Barneseb7f79b2018-11-08 15:44:10 -0700283/*
284 * This method will return the uids of all auth bound keys for the calling user.
285 * This is intended to be used for alerting the user about which apps will be affected
286 * if the password/pin is removed. Only allowed to be called by system.
287 * The output is bound by the initial size of uidsOut to be compatible with Java.
288 */
Rob Barnes5d59e632018-12-07 16:09:02 -0700289Status KeyStoreService::listUidsOfAuthBoundKeys(std::vector<std::string>* uidsOut,
Rob Barneseb7f79b2018-11-08 15:44:10 -0700290 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700291 KEYSTORE_SERVICE_LOCK;
Rob Barneseb7f79b2018-11-08 15:44:10 -0700292 const int32_t callingUid = IPCThreadState::self()->getCallingUid();
293 const int32_t userId = get_user_id(callingUid);
294 const int32_t appId = get_app_id(callingUid);
295 if (appId != AID_SYSTEM) {
296 ALOGE("Permission listUidsOfAuthBoundKeys denied for aid %d", appId);
297 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
298 return Status::ok();
299 }
300
301 const String8 prefix8("");
302 auto userState = mKeyStore->getUserStateDB().getUserState(userId);
303 const std::string userDirName = userState->getUserDirName();
304 auto encryptionKey = userState->getEncryptionKey();
305 auto state = userState->getState();
306 // unlock the user state
307 userState = {};
308
309 ResponseCode rc;
310 std::list<LockedKeyBlobEntry> internal_matches;
311 std::tie(rc, internal_matches) =
312 LockedKeyBlobEntry::list(userDirName, [&](uid_t, const std::string&) {
313 // Need to filter on auth bound state, so just return true.
314 return true;
315 });
316 if (rc != ResponseCode::NO_ERROR) {
317 ALOGE("Error listing blob entries for user %d", userId);
318 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
319 }
320
Rob Barneseb7f79b2018-11-08 15:44:10 -0700321 for (LockedKeyBlobEntry& entry : internal_matches) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700322 // Need to store uids as a list of strings because integer list output
323 // parameters is not supported in aidl-cpp.
324 std::string entryUid = std::to_string(entry->uid());
325 if (std::find(uidsOut->begin(), uidsOut->end(), entryUid) != uidsOut->end()) {
Rob Barneseb7f79b2018-11-08 15:44:10 -0700326 // uid already in list, skip
327 continue;
328 }
329
330 auto [rc, blob, charBlob] = entry.readBlobs(encryptionKey, state);
331 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::LOCKED) {
332 ALOGE("Error reading blob for key %s", entry->alias().c_str());
333 continue;
334 }
335
336 if (blob && blob.isEncrypted()) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700337 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700338 } else if (charBlob) {
339 auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
340 if (!success) {
341 ALOGE("Error reading blob characteristics for key %s", entry->alias().c_str());
342 continue;
343 }
344 if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
345 swEnforced.Contains(TAG_USER_SECURE_ID)) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700346 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700347 }
348 }
349 }
350 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
351 return Status::ok();
352}
353
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700354Status KeyStoreService::reset(int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700355 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700356 if (!checkBinderPermission(P_RESET)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700357 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
358 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700359 }
360
361 uid_t callingUid = IPCThreadState::self()->getCallingUid();
362 mKeyStore->resetUser(get_user_id(callingUid), false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700363 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
364 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700365}
366
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700367Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
368 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700369 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700370 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700371 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
372 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700373 }
374
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700375 if (password.size() == 0) {
376 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
377 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700378 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
379 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700380 } else {
Pavel Grafovf9b53eb2019-02-06 17:16:21 +0000381 const String8 password8(password);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700382 switch (mKeyStore->getState(userId)) {
383 case ::STATE_UNINITIALIZED: {
384 // generate master key, encrypt with password, write to file,
385 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700386 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
387 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700388 }
389 case ::STATE_NO_ERROR: {
390 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700391 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
392 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700393 }
394 case ::STATE_LOCKED: {
395 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
396 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700397 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
398 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700399 }
400 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700401 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
402 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700403 }
404}
405
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700406Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700407 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700408 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700409 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
410 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700411 }
412
413 // Sanity check that the new user has an empty keystore.
414 if (!mKeyStore->isEmpty(userId)) {
415 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
416 }
417 // Unconditionally clear the keystore, just to be safe.
418 mKeyStore->resetUser(userId, false);
419 if (parentId != -1) {
420 // This profile must share the same master key password as the parent profile. Because the
421 // password of the parent profile is not known here, the best we can do is copy the parent's
422 // master key and master key file. This makes this profile use the same master key as the
423 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700424 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
425 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700426 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700427 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
428 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700429 }
430}
431
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700432Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700433 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700434 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700435 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
436 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700437 }
438
439 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700440 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
441 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700442}
443
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700444Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700445 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700446 if (!checkBinderPermission(P_LOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700447 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
448 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700449 }
450
451 State state = mKeyStore->getState(userId);
452 if (state != ::STATE_NO_ERROR) {
453 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700454 *aidl_return = static_cast<int32_t>(ResponseCode(state));
455 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700456 }
457
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700458 mKeyStore->getEnforcementPolicy().set_device_locked(true, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700459 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700460 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
461 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700462}
463
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700464Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700465 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700466 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700467 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
468 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700469 }
470
471 State state = mKeyStore->getState(userId);
472 if (state != ::STATE_LOCKED) {
473 switch (state) {
474 case ::STATE_NO_ERROR:
475 ALOGI("calling unlock when already unlocked, ignoring.");
476 break;
477 case ::STATE_UNINITIALIZED:
478 ALOGE("unlock called on uninitialized keystore.");
479 break;
480 default:
481 ALOGE("unlock called on keystore in unknown state: %d", state);
482 break;
483 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700484 *aidl_return = static_cast<int32_t>(ResponseCode(state));
485 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700486 }
487
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700488 mKeyStore->getEnforcementPolicy().set_device_locked(false, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700489 const String8 password8(pw);
490 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700491 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
492 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700493}
494
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700495Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700496 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700497 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700498 *aidl_return = static_cast<int32_t>(false);
499 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700500 }
501
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700502 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
503 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700504}
505
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700506Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
507 ::android::String16* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700508 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700509 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700510 auto result =
511 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100512 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700513 *aidl_return = String16();
514 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700515 }
516
517 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700518 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
519 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700520 *aidl_return = String16();
521 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700522 }
523
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700524 *aidl_return = String16(mKeyStore->addGrant(lockedEntry, granteeUid).c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700525 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700526}
527
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700528Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700529 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700530 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700531 KeyStoreServiceReturnCode result =
532 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100533 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800534 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700535 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700536 }
537
538 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700539
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700540 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
541 if (!lockedEntry) {
542 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700543 }
544
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700545 *aidl_return = mKeyStore->removeGrant(lockedEntry, granteeUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700546 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700547}
548
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700549Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700550 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700551 uid_t targetUid = getEffectiveUid(uid);
552 if (!checkBinderPermission(P_GET, targetUid)) {
553 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700554 *time = -1L;
555 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700556 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700557 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700558
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700559 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
560 if (!lockedEntry) {
561 ALOGW("could not access key with alias %s for getmtime", name8.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700562 *time = -1L;
563 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700564 }
565
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700566 std::string filename = lockedEntry->getKeyBlobPath();
567
568 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700569 if (fd < 0) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700570 ALOGW("could not open %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700571 *time = -1L;
572 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700573 }
574
575 struct stat s;
576 int ret = fstat(fd, &s);
577 close(fd);
578 if (ret == -1) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700579 ALOGW("could not stat %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700580 *time = -1L;
581 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700582 }
583
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700584 *time = static_cast<int64_t>(s.st_mtime);
585 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700586}
587
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700588Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700589 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700590 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
591 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700592}
593
Janis Danisevskis265435f2018-11-16 14:10:46 -0800594Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700595 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700596 uid_t targetUid = getEffectiveUid(targetUid64);
597 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800598 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700599 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000600 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700601
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700602 mKeyStore->removeAllGrantsToUid(targetUid);
603
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700604 ResponseCode rc;
605 std::list<LockedKeyBlobEntry> entries;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800606 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700607
608 // list has a fence making sure no workers are modifying blob files before iterating the
609 // data base. All returned entries are locked.
610 std::tie(rc, entries) = LockedKeyBlobEntry::list(
Janis Danisevskis265435f2018-11-16 14:10:46 -0800611 userDirName, [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700612
613 if (rc != ResponseCode::NO_ERROR) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800614 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700615 }
616
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700617 for (LockedKeyBlobEntry& lockedEntry : entries) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100618 if (get_app_id(targetUid) == AID_SYSTEM) {
619 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700620 Blob charBlob;
621 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
622 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100623 // Do not clear keys critical to device encryption under system uid.
624 continue;
625 }
626 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700627 mKeyStore->del(lockedEntry);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700628 }
Janis Danisevskis265435f2018-11-16 14:10:46 -0800629 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700630}
631
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600632Status KeyStoreService::addRngEntropy(
633 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
634 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700635 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisc1460142017-12-18 16:48:46 -0800636 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
637 if (!device) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600638 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800639 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700640
Janis Danisevskisa359c672019-03-14 17:15:06 -0700641 device->addRngEntropy(entropy, [device, cb](Return<ErrorCode> rc) {
642 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device, rc)));
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600643 });
644
645 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700646}
647
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600648Status KeyStoreService::generateKey(
649 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
650 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
651 int uid, int flags, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700652 KEYSTORE_SERVICE_LOCK;
Max Biresef4f0672017-11-29 14:38:48 -0800653 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
654 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700655 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000656 auto logOnScopeExit = android::base::make_scope_guard([&] {
657 if (__android_log_security()) {
658 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600659 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000660 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
661 }
662 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100663 KeyStoreServiceReturnCode rc =
664 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
665 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600666 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700667 }
Rubin Xu67899de2017-04-21 19:15:13 +0100668 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
669 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600670 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100671 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700672
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700673 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700674 // TODO(jbires): remove uid checking upon implementation of b/25646100
Max Bires670467d2017-12-12 11:16:43 -0800675 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Biresef4f0672017-11-29 14:38:48 -0800676 originalUid != IPCThreadState::self()->getCallingUid()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600677 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700678 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600679 }
680
Janis Danisevskisc1460142017-12-18 16:48:46 -0800681 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
682 auto dev = mKeyStore->getDevice(securityLevel);
683 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600684 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800685 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400686
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100687 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700688 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
689 if (!lockedEntry) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600690 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100691 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400692
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700693 logOnScopeExit.Disable();
694
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600695 dev->generateKey(
696 std::move(lockedEntry), params.getParameters(), entropy, flags,
697 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
698 if (__android_log_security()) {
699 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
700 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
701 }
702 cb->onFinished(rc,
703 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
704 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700705
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600706 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700707}
708
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700709Status KeyStoreService::getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600710 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700711 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
Janis Danisevskis64ec1fe2018-02-26 16:47:21 -0800712 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600713 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700714 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700715
716 uid_t targetUid = getEffectiveUid(uid);
717 uid_t callingUid = IPCThreadState::self()->getCallingUid();
718 if (!is_granted_to(callingUid, targetUid)) {
719 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
720 targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600721 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700722 }
723
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700724 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700725
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700726 ResponseCode rc;
727 Blob keyBlob;
728 Blob charBlob;
729 LockedKeyBlobEntry lockedEntry;
Janis Danisevskisd714a672017-09-01 14:31:36 -0700730
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700731 std::tie(rc, keyBlob, charBlob, lockedEntry) =
732 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
733
734 if (rc != ResponseCode::NO_ERROR) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600735 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700736 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100737
Janis Danisevskisc1460142017-12-18 16:48:46 -0800738 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700739 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600740 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100741 }
742
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700743 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
744 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
745 // from keymaster. It may also upgrade the key blob.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700746 dev->getKeyCharacteristics(
747 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
748 std::move(charBlob),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600749 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
750 cb->onFinished(rc,
751 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700752 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100753
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600754 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700755}
756
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600757Status KeyStoreService::importKey(
758 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
759 const String16& name, const KeymasterArguments& params, int32_t format,
760 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700761 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700762 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000763 auto logOnScopeExit = android::base::make_scope_guard([&] {
764 if (__android_log_security()) {
765 android_log_event_list(SEC_TAG_KEY_IMPORTED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600766 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000767 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
768 }
769 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100770 KeyStoreServiceReturnCode rc =
771 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
772 if (!rc.isOk()) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700773 LOG(ERROR) << "permissission denied";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600774 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700775 }
Rubin Xu67899de2017-04-21 19:15:13 +0100776 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
777 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600778 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100779 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700780
Janis Danisevskisc1460142017-12-18 16:48:46 -0800781 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
782 auto dev = mKeyStore->getDevice(securityLevel);
783 if (!dev) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700784 LOG(ERROR) << "importKey - cound not get keymaster device";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600785 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800786 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700787
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700788 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700789 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
790 if (!lockedEntry) {
791 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
792 << " already exists.";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600793 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400794 }
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700795
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700796 logOnScopeExit.Disable();
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700797
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600798 dev->importKey(
799 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
800 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
801 if (__android_log_security()) {
802 android_log_event_list(SEC_TAG_KEY_IMPORTED)
803 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
804 }
805 cb->onFinished(rc,
806 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
807 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400808
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600809 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700810}
811
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600812Status KeyStoreService::exportKey(
813 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
814 const String16& name, int32_t format,
815 const ::android::security::keymaster::KeymasterBlob& clientId,
816 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
817 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700818 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700819
820 uid_t targetUid = getEffectiveUid(uid);
821 uid_t callingUid = IPCThreadState::self()->getCallingUid();
822 if (!is_granted_to(callingUid, targetUid)) {
823 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600824 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700825 }
826
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700827 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700828
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700829 KeyStoreServiceReturnCode rc;
830 Blob keyBlob;
831 Blob charBlob;
832 LockedKeyBlobEntry lockedEntry;
833
834 std::tie(rc, keyBlob, charBlob, lockedEntry) =
835 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskis3cf85322018-11-19 13:37:49 -0800836 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600837 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700838 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100839
Janis Danisevskisc1460142017-12-18 16:48:46 -0800840 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100841
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700842 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600843 std::move(keyBlob), std::move(charBlob),
844 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
Ji Wang2c142312016-10-14 17:21:10 +0800845
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600846 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700847}
848
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600849Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
850 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700851 bool pruneable, const KeymasterArguments& params,
852 const ::std::vector<uint8_t>& entropy, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600853 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700854 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700855 uid_t callingUid = IPCThreadState::self()->getCallingUid();
856 uid_t targetUid = getEffectiveUid(uid);
857 if (!is_granted_to(callingUid, targetUid)) {
858 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600859 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700860 }
861 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
862 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600863 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700864 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700865 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600866 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700867 }
Shawn Willden0329a822017-12-04 13:55:14 -0700868
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700869 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700870 Blob keyBlob;
871 Blob charBlob;
872 LockedKeyBlobEntry lockedEntry;
873 ResponseCode rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100874
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700875 std::tie(rc, keyBlob, charBlob, lockedEntry) =
876 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
877
878 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600879 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700880 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600881 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700882
Janis Danisevskisc1460142017-12-18 16:48:46 -0800883 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700884 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100885
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700886 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
887 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600888 [this, cb, dev](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700889 if (result_.resultCode.isOk() ||
890 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
Janis Danisevskis85735d82019-08-14 13:42:19 -0700891 mKeyStore->addOperationDevice(result_.token, dev);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700892 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600893 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700894 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400895
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600896 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700897}
898
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600899Status KeyStoreService::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
900 const ::android::sp<::android::IBinder>& token,
901 const ::android::security::keymaster::KeymasterArguments& params,
902 const ::std::vector<uint8_t>& input, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700903 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700904 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600905 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700906 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700907
Janis Danisevskis85735d82019-08-14 13:42:19 -0700908 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700909 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600910 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700911 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700912
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600913 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700914 if (!result_.resultCode.isOk()) {
Janis Danisevskis85735d82019-08-14 13:42:19 -0700915 mKeyStore->removeOperationDevice(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100916 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600917 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700918 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100919
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600920 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700921}
922
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600923Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
924 const ::android::sp<::android::IBinder>& token,
925 const ::android::security::keymaster::KeymasterArguments& params,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700926 const ::std::vector<uint8_t>& signature,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600927 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700928 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700929 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600930 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700931 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700932
Janis Danisevskis85735d82019-08-14 13:42:19 -0700933 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700934 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600935 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700936 }
937
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700938 dev->finish(token, params.getParameters(), {}, signature, entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600939 [this, cb, token](OperationResult result_) {
Janis Danisevskis0a623612019-10-04 11:01:54 -0700940 mKeyStore->removeOperationDevice(token);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600941 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700942 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700943
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600944 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700945}
946
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600947Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
948 const ::android::sp<::android::IBinder>& token,
949 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700950 KEYSTORE_SERVICE_LOCK;
Janis Danisevskis85735d82019-08-14 13:42:19 -0700951 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700952 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600953 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700954 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100955
Janis Danisevskis85735d82019-08-14 13:42:19 -0700956 dev->abort(token, [this, cb, token](KeyStoreServiceReturnCode rc) {
957 mKeyStore->removeOperationDevice(token);
958 cb->onFinished(rc);
959 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700960
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600961 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700962}
963
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700964Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000965 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700966 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700967
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000968 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
969 // receive a HardwareAuthToken, rather than an opaque byte array.
970
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700971 if (!checkBinderPermission(P_ADD_AUTH)) {
972 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700973 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
974 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700975 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700976 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
Branden Archer70080742018-11-20 11:04:11 -0800977 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700978 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000979 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100980
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000981 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700982 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000983 if (authToken.version != 0) {
Branden Archer70080742018-11-20 11:04:11 -0800984 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700985 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000986 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100987
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700988 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
989 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700990 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
991 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700992}
993
Eran Messerid9f8ae52018-10-24 13:54:00 +0100994bool isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -0700995 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700996 for (size_t i = 0; i < paramsVec.size(); ++i) {
997 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -0600998 case Tag::ATTESTATION_ID_BRAND:
999 case Tag::ATTESTATION_ID_DEVICE:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001000 case Tag::ATTESTATION_ID_MANUFACTURER:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001001 case Tag::ATTESTATION_ID_MODEL:
1002 case Tag::ATTESTATION_ID_PRODUCT:
Rubin Xu1a203e32018-05-08 14:25:21 +01001003 case Tag::ATTESTATION_ID_IMEI:
1004 case Tag::ATTESTATION_ID_MEID:
1005 case Tag::ATTESTATION_ID_SERIAL:
Eran Messerid9f8ae52018-10-24 13:54:00 +01001006 return true;
Rubin Xu1a203e32018-05-08 14:25:21 +01001007 default:
1008 continue;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001009 }
1010 }
Eran Messerid9f8ae52018-10-24 13:54:00 +01001011 return false;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001012}
1013
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001014Status KeyStoreService::attestKey(
1015 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1016 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001017 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001018 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1019 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001020 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001021 }
1022
Eran Messerie2c34152017-12-21 21:01:22 +00001023 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1024
Eran Messerid9f8ae52018-10-24 13:54:00 +01001025 if (isDeviceIdAttestationRequested(params) && (get_app_id(callingUid) != AID_SYSTEM)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001026 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001027 }
1028
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001029 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001030 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1031 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001032 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001033 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001034
Shawn Willden50eb1b22016-01-21 12:41:23 -07001035 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001036 Blob keyBlob;
1037 Blob charBlob;
1038 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001039
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001040 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1041 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1042
Janis Danisevskis83aa2722019-07-10 14:08:06 -07001043 if (!rc.isOk()) {
1044 return AIDL_RETURN(rc);
1045 }
1046
Janis Danisevskisc1460142017-12-18 16:48:46 -08001047 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001048 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001049 dev->attestKey(
1050 std::move(hidlKey), mutableParams.hidl_data(),
Janis Danisevskisa359c672019-03-14 17:15:06 -07001051 [dev, cb](Return<void> rc,
1052 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001053 auto& [ret, certChain] = hidlResult;
1054 if (!rc.isOk()) {
1055 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1056 } else if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001057 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001058 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1059 } else {
1060 cb->onFinished(KeyStoreServiceReturnCode(ret),
1061 KeymasterCertificateChain(std::move(certChain)));
1062 }
1063 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001064
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001065 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001066}
1067
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001068// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1069// It should never be redefined by a build system though.
1070#ifndef CAPTURE_MOVE
1071#define CAPTURE_MOVE(x) x = std::move(x)
1072#endif
1073
1074Status KeyStoreService::attestDeviceIds(
1075 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1076 const KeymasterArguments& params, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001077 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001078 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001079
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001080 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001081 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001082 }
1083
1084 if (!isDeviceIdAttestationRequested(params)) {
1085 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001086 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001087 }
1088
1089 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1090 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
Yi Konge353f252018-07-30 01:38:39 -07001091 if (binder == nullptr) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001092 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001093 }
1094 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1095 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1096 IPCThreadState::self()->getCallingPid(), callingUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001097 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001098 }
1099
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001100 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001101 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1102 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001103 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001104 }
1105
1106 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001107 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001108
Shawn Willden70c1a782018-07-11 15:13:20 -06001109 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001110 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001111 }
1112
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001113
1114 AuthorizationSet keyCharacteristics;
1115 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1116 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1117 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1118 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1119 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001120
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001121 std::promise<KeyStoreServiceReturnCode> resultPromise;
1122 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001123
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001124 dev->generateKey(
1125 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001126 [cb, dev, CAPTURE_MOVE(mutableParams)](
1127 Return<void> rc,
1128 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001129 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1130 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1131 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001132 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001133 return;
1134 }
1135 if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001136 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001137 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001138 return;
1139 }
1140 dev->attestKey(
1141 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001142 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001143 hidlKeyBlob](Return<void> rc,
1144 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1145 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001146 // schedule temp key for deletion
Janis Danisevskisa359c672019-03-14 17:15:06 -07001147 dev->deleteKey(std::move(hidlKeyBlob), [dev](Return<ErrorCode> rc) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001148 // log error but don't return an error
Janis Danisevskisa359c672019-03-14 17:15:06 -07001149 KS_HANDLE_HIDL_ERROR(dev, rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001150 });
1151 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001152 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001153 return;
1154 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001155 if (ret == ErrorCode::OK) {
1156 cb->onFinished(
1157 KeyStoreServiceReturnCode(ret),
1158 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1159 } else {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001160 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001161 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001162 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001163 });
1164 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001165
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001166 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001167}
1168
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001169Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001170 KEYSTORE_SERVICE_LOCK;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001171 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001172 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001173 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1174 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001175}
1176
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001177Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001178 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001179 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1180 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1181 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001182 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001183 KEYSTORE_SERVICE_LOCK;
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001184
1185 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1186
1187 if (!checkBinderPermission(P_INSERT, callingUid)) {
1188 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1189 }
1190
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001191 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001192
1193 KeyStoreServiceReturnCode rc;
1194 Blob wrappingKeyBlob;
1195 Blob wrappingCharBlob;
1196 LockedKeyBlobEntry wrappingLockedEntry;
1197
1198 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1199 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
Branden Archerd166a882018-11-20 10:56:48 -08001200 if (!rc.isOk()) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001201 return AIDL_RETURN(rc);
1202 }
1203
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001204 String8 wrappedKeyName8(wrappedKeyAlias);
1205 auto wrappedLockedEntry =
1206 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1207 if (!wrappedLockedEntry) {
1208 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1209 }
1210
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001211 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1212 auto dev = mKeyStore->getDevice(securityLevel);
1213 if (!dev) {
1214 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1215 }
1216
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001217 dev->importWrappedKey(
1218 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1219 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001220 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1221 cb->onFinished(rc,
1222 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001223 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001224
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001225 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001226}
1227
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001228Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1229 const String16& promptText,
1230 const ::std::vector<uint8_t>& extraData,
1231 const String16& locale, int32_t uiOptionsAsFlags,
1232 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001233 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001234 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1235 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001236}
1237
1238Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1239 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001240 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001241 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001242}
1243
David Zeuthen1a492312018-02-26 11:00:30 -05001244Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001245 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001246 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001247}
1248
1249/**
1250 * Get the effective target uid for a binder operation that takes an
1251 * optional uid as the target.
1252 */
1253uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1254 if (targetUid == UID_SELF) {
1255 return IPCThreadState::self()->getCallingUid();
1256 }
1257 return static_cast<uid_t>(targetUid);
1258}
1259
1260/**
1261 * Check if the caller of the current binder method has the required
1262 * permission and if acting on other uids the grants to do so.
1263 */
1264bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1265 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1266 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001267 const char* ssid = IPCThreadState::self()->getCallingSid();
1268 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001269 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1270 return false;
1271 }
1272 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1273 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1274 return false;
1275 }
1276 return true;
1277}
1278
1279/**
1280 * Check if the caller of the current binder method has the required
1281 * permission and the target uid is the caller or the caller is system.
1282 */
1283bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1284 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1285 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001286 const char* ssid = IPCThreadState::self()->getCallingSid();
1287 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001288 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1289 return false;
1290 }
1291 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1292}
1293
1294/**
1295 * Check if the caller of the current binder method has the required
1296 * permission or the target of the operation is the caller's uid. This is
1297 * for operation where the permission is only for cross-uid activity and all
1298 * uids are allowed to act on their own (ie: clearing all entries for a
1299 * given uid).
1300 */
1301bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1302 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1303 if (getEffectiveUid(targetUid) == callingUid) {
1304 return true;
1305 } else {
1306 return checkBinderPermission(permission, targetUid);
1307 }
1308}
1309
1310/**
1311 * Helper method to check that the caller has the required permission as
1312 * well as the keystore is in the unlocked state if checkUnlocked is true.
1313 *
1314 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1315 * otherwise the state of keystore when not unlocked and checkUnlocked is
1316 * true.
1317 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001318KeyStoreServiceReturnCode
1319KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1320 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001321 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001322 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001323 }
1324 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1325 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001326 // All State values coincide with ResponseCodes
1327 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001328 }
1329
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001330 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001331}
1332
1333bool KeyStoreService::isKeystoreUnlocked(State state) {
1334 switch (state) {
1335 case ::STATE_NO_ERROR:
1336 return true;
1337 case ::STATE_UNINITIALIZED:
1338 case ::STATE_LOCKED:
1339 return false;
1340 }
1341 return false;
1342}
1343
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001344/**
Shawn Willden0329a822017-12-04 13:55:14 -07001345 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1346 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001347 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001348bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1349 for (size_t i = 0; i < params.size(); ++i) {
1350 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001351 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001352 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001353 return false;
1354 default:
1355 break;
1356 }
1357 }
1358 return true;
1359}
1360
Brian Young9a947d52018-02-23 18:03:14 +00001361Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
1362 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001363 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001364 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Brian Young9a947d52018-02-23 18:03:14 +00001365 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001366
1367 return Status::ok();
1368}
1369
Shawn Willdene2a7b522017-04-11 09:27:40 -06001370} // namespace keystore