blob: 5e7efab0d404f92a80c9e5ebec7a57c7acbf4482 [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) {
891 addOperationDevice(result_.token, dev);
892 }
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 Danisevskisff3d7f42018-10-08 07:15:09 -0700908 auto dev = getOperationDevice(token);
909 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()) {
915 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 Danisevskisff3d7f42018-10-08 07:15:09 -0700933 auto dev = getOperationDevice(token);
934 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 Danisevskisff3d7f42018-10-08 07:15:09 -0700940 if (!result_.resultCode.isOk()) {
941 removeOperationDevice(token);
942 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600943 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700944 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700945
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600946 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700947}
948
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600949Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
950 const ::android::sp<::android::IBinder>& token,
951 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700952 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700953 auto dev = getOperationDevice(token);
954 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600955 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700956 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100957
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600958 dev->abort(token, [cb](KeyStoreServiceReturnCode rc) { cb->onFinished(rc); });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700959
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600960 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700961}
962
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700963Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000964 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700965 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700966
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000967 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
968 // receive a HardwareAuthToken, rather than an opaque byte array.
969
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700970 if (!checkBinderPermission(P_ADD_AUTH)) {
971 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700972 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
973 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700974 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700975 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
Branden Archer70080742018-11-20 11:04:11 -0800976 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700977 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000978 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100979
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000980 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700981 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000982 if (authToken.version != 0) {
Branden Archer70080742018-11-20 11:04:11 -0800983 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700984 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000985 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100986
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700987 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
988 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700989 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
990 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700991}
992
Eran Messerid9f8ae52018-10-24 13:54:00 +0100993bool isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -0700994 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700995 for (size_t i = 0; i < paramsVec.size(); ++i) {
996 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -0600997 case Tag::ATTESTATION_ID_BRAND:
998 case Tag::ATTESTATION_ID_DEVICE:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600999 case Tag::ATTESTATION_ID_MANUFACTURER:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001000 case Tag::ATTESTATION_ID_MODEL:
1001 case Tag::ATTESTATION_ID_PRODUCT:
Rubin Xu1a203e32018-05-08 14:25:21 +01001002 case Tag::ATTESTATION_ID_IMEI:
1003 case Tag::ATTESTATION_ID_MEID:
1004 case Tag::ATTESTATION_ID_SERIAL:
Eran Messerid9f8ae52018-10-24 13:54:00 +01001005 return true;
Rubin Xu1a203e32018-05-08 14:25:21 +01001006 default:
1007 continue;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001008 }
1009 }
Eran Messerid9f8ae52018-10-24 13:54:00 +01001010 return false;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001011}
1012
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001013Status KeyStoreService::attestKey(
1014 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1015 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001016 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001017 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1018 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001019 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001020 }
1021
Eran Messerie2c34152017-12-21 21:01:22 +00001022 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1023
Eran Messerid9f8ae52018-10-24 13:54:00 +01001024 if (isDeviceIdAttestationRequested(params) && (get_app_id(callingUid) != AID_SYSTEM)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001025 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001026 }
1027
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001028 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001029 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1030 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001031 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001032 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001033
Shawn Willden50eb1b22016-01-21 12:41:23 -07001034 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001035 Blob keyBlob;
1036 Blob charBlob;
1037 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001038
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001039 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1040 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1041
Janis Danisevskisc1460142017-12-18 16:48:46 -08001042 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001043 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001044 dev->attestKey(
1045 std::move(hidlKey), mutableParams.hidl_data(),
Janis Danisevskisa359c672019-03-14 17:15:06 -07001046 [dev, cb](Return<void> rc,
1047 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001048 auto& [ret, certChain] = hidlResult;
1049 if (!rc.isOk()) {
1050 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1051 } else if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001052 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001053 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1054 } else {
1055 cb->onFinished(KeyStoreServiceReturnCode(ret),
1056 KeymasterCertificateChain(std::move(certChain)));
1057 }
1058 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001059
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001060 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001061}
1062
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001063// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1064// It should never be redefined by a build system though.
1065#ifndef CAPTURE_MOVE
1066#define CAPTURE_MOVE(x) x = std::move(x)
1067#endif
1068
1069Status KeyStoreService::attestDeviceIds(
1070 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1071 const KeymasterArguments& params, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001072 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001073 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001074
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001075 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001076 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001077 }
1078
1079 if (!isDeviceIdAttestationRequested(params)) {
1080 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001081 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001082 }
1083
1084 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1085 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
Yi Konge353f252018-07-30 01:38:39 -07001086 if (binder == nullptr) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001087 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001088 }
1089 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1090 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1091 IPCThreadState::self()->getCallingPid(), callingUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001092 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001093 }
1094
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001095 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001096 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1097 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001098 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001099 }
1100
1101 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001102 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001103
Shawn Willden70c1a782018-07-11 15:13:20 -06001104 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001105 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001106 }
1107
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001108
1109 AuthorizationSet keyCharacteristics;
1110 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1111 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1112 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1113 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1114 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001115
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001116 std::promise<KeyStoreServiceReturnCode> resultPromise;
1117 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001118
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001119 dev->generateKey(
1120 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001121 [cb, dev, CAPTURE_MOVE(mutableParams)](
1122 Return<void> rc,
1123 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001124 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1125 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1126 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001127 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001128 return;
1129 }
1130 if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001131 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001132 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001133 return;
1134 }
1135 dev->attestKey(
1136 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001137 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001138 hidlKeyBlob](Return<void> rc,
1139 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1140 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001141 // schedule temp key for deletion
Janis Danisevskisa359c672019-03-14 17:15:06 -07001142 dev->deleteKey(std::move(hidlKeyBlob), [dev](Return<ErrorCode> rc) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001143 // log error but don't return an error
Janis Danisevskisa359c672019-03-14 17:15:06 -07001144 KS_HANDLE_HIDL_ERROR(dev, rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001145 });
1146 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001147 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001148 return;
1149 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001150 if (ret == ErrorCode::OK) {
1151 cb->onFinished(
1152 KeyStoreServiceReturnCode(ret),
1153 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1154 } else {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001155 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001156 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001157 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001158 });
1159 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001160
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001161 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001162}
1163
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001164Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001165 KEYSTORE_SERVICE_LOCK;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001166 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001167 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001168 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1169 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001170}
1171
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001172Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001173 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001174 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1175 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1176 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001177 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001178 KEYSTORE_SERVICE_LOCK;
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001179
1180 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1181
1182 if (!checkBinderPermission(P_INSERT, callingUid)) {
1183 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1184 }
1185
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001186 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001187
1188 KeyStoreServiceReturnCode rc;
1189 Blob wrappingKeyBlob;
1190 Blob wrappingCharBlob;
1191 LockedKeyBlobEntry wrappingLockedEntry;
1192
1193 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1194 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
Branden Archerd166a882018-11-20 10:56:48 -08001195 if (!rc.isOk()) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001196 return AIDL_RETURN(rc);
1197 }
1198
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001199 String8 wrappedKeyName8(wrappedKeyAlias);
1200 auto wrappedLockedEntry =
1201 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1202 if (!wrappedLockedEntry) {
1203 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1204 }
1205
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001206 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1207 auto dev = mKeyStore->getDevice(securityLevel);
1208 if (!dev) {
1209 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1210 }
1211
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001212 dev->importWrappedKey(
1213 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1214 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001215 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1216 cb->onFinished(rc,
1217 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001218 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001219
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001220 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001221}
1222
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001223Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1224 const String16& promptText,
1225 const ::std::vector<uint8_t>& extraData,
1226 const String16& locale, int32_t uiOptionsAsFlags,
1227 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001228 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001229 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1230 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001231}
1232
1233Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1234 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001235 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001236 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001237}
1238
David Zeuthen1a492312018-02-26 11:00:30 -05001239Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001240 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001241 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001242}
1243
1244/**
1245 * Get the effective target uid for a binder operation that takes an
1246 * optional uid as the target.
1247 */
1248uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1249 if (targetUid == UID_SELF) {
1250 return IPCThreadState::self()->getCallingUid();
1251 }
1252 return static_cast<uid_t>(targetUid);
1253}
1254
1255/**
1256 * Check if the caller of the current binder method has the required
1257 * permission and if acting on other uids the grants to do so.
1258 */
1259bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1260 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1261 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001262 const char* ssid = IPCThreadState::self()->getCallingSid();
1263 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001264 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1265 return false;
1266 }
1267 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1268 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1269 return false;
1270 }
1271 return true;
1272}
1273
1274/**
1275 * Check if the caller of the current binder method has the required
1276 * permission and the target uid is the caller or the caller is system.
1277 */
1278bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1279 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1280 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001281 const char* ssid = IPCThreadState::self()->getCallingSid();
1282 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001283 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1284 return false;
1285 }
1286 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1287}
1288
1289/**
1290 * Check if the caller of the current binder method has the required
1291 * permission or the target of the operation is the caller's uid. This is
1292 * for operation where the permission is only for cross-uid activity and all
1293 * uids are allowed to act on their own (ie: clearing all entries for a
1294 * given uid).
1295 */
1296bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1297 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1298 if (getEffectiveUid(targetUid) == callingUid) {
1299 return true;
1300 } else {
1301 return checkBinderPermission(permission, targetUid);
1302 }
1303}
1304
1305/**
1306 * Helper method to check that the caller has the required permission as
1307 * well as the keystore is in the unlocked state if checkUnlocked is true.
1308 *
1309 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1310 * otherwise the state of keystore when not unlocked and checkUnlocked is
1311 * true.
1312 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001313KeyStoreServiceReturnCode
1314KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1315 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001316 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001317 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001318 }
1319 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1320 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001321 // All State values coincide with ResponseCodes
1322 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001323 }
1324
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001325 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001326}
1327
1328bool KeyStoreService::isKeystoreUnlocked(State state) {
1329 switch (state) {
1330 case ::STATE_NO_ERROR:
1331 return true;
1332 case ::STATE_UNINITIALIZED:
1333 case ::STATE_LOCKED:
1334 return false;
1335 }
1336 return false;
1337}
1338
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001339/**
Shawn Willden0329a822017-12-04 13:55:14 -07001340 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1341 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001342 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001343bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1344 for (size_t i = 0; i < params.size(); ++i) {
1345 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001346 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001347 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001348 return false;
1349 default:
1350 break;
1351 }
1352 }
1353 return true;
1354}
1355
Brian Young9a947d52018-02-23 18:03:14 +00001356Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
1357 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001358 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001359 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Brian Young9a947d52018-02-23 18:03:14 +00001360 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001361
1362 return Status::ok();
1363}
1364
Shawn Willdene2a7b522017-04-11 09:27:40 -06001365} // namespace keystore