blob: a9c36872b93db9a669db658abb4870bc30a06ee1 [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";
Rubin Xu1a203e32018-05-08 14:25:21 +010072const int ID_ATTESTATION_REQUEST_GENERIC_INFO = 1 << 0;
73const int ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID = 1 << 1;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070074
75struct BIGNUM_Delete {
76 void operator()(BIGNUM* p) const { BN_free(p); }
77};
Janis Danisevskisccfff102017-05-01 11:02:51 -070078typedef std::unique_ptr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070079
Shawn Willdene2a7b522017-04-11 09:27:40 -060080bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070081 return params.end() !=
82 std::find_if(params.begin(), params.end(),
83 [&](const KeyParameter& param) { return param.tag == tag; });
Shawn Willdend5a24e62017-02-28 13:53:24 -070084}
85
Branden Archer70080742018-11-20 11:04:11 -080086#define AIDL_RETURN(rc) (*_aidl_return = KeyStoreServiceReturnCode(rc).getErrorCode(), Status::ok())
Janis Danisevskisb50236a2019-03-25 10:26:30 -070087#define KEYSTORE_SERVICE_LOCK std::lock_guard<std::mutex> keystore_lock(keystoreServiceMutex_)
Rob Barnesbb6cabd2018-10-04 17:10:37 -060088
Shawn Willdene2a7b522017-04-11 09:27:40 -060089std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
90 struct stat sbuf;
91 if (stat(kTimestampFilePath, &sbuf) == 0) {
Yi Konge353f252018-07-30 01:38:39 -070092 double diff_secs = difftime(time(nullptr), sbuf.st_ctime);
Shawn Willdene2a7b522017-04-11 09:27:40 -060093 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
94 }
95
96 if (errno != ENOENT) {
97 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
98 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
99 }
100
101 int fd = creat(kTimestampFilePath, 0600);
102 if (fd < 0) {
103 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
104 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
105 }
106
107 if (close(fd)) {
108 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
109 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
110 }
111
112 return {ResponseCode::NO_ERROR, true};
113}
114
Eran Messeri03fc4c82018-08-16 18:53:15 +0100115using ::android::security::KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200116
117KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
118 KeyStoreServiceReturnCode responseCode;
119 bool factoryResetSinceIdRotation;
120 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
121
122 if (!responseCode.isOk()) return responseCode;
123 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
124
125 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
126 if (!asn1_attestation_id_result.isOk()) {
127 ALOGE("failed to gather attestation_id");
128 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
129 }
130 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
131
132 /*
Eran Messeri03fc4c82018-08-16 18:53:15 +0100133 * The attestation application ID must not be longer than
134 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, error out if gather_attestation_application_id
135 * returned such an invalid vector.
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200136 */
137 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Eran Messeri03fc4c82018-08-16 18:53:15 +0100138 ALOGE("BUG: Gathered Attestation Application ID is too big (%d)",
139 static_cast<int32_t>(asn1_attestation_id.size()));
140 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200141 }
142
143 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
144
145 return ResponseCode::NO_ERROR;
146}
147
Shawn Willdene2a7b522017-04-11 09:27:40 -0600148} // anonymous namespace
149
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700150Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700151 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700152 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700153 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
154 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700155 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700156 *aidl_return = mKeyStore->getState(userId);
157 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700158}
159
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700160Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700161 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700162 uid_t targetUid = getEffectiveUid(uid);
163 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700164 // see keystore/keystore.h
165 return Status::fromServiceSpecificError(
166 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700167 }
168
169 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700170 ResponseCode rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700171 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700172 Blob charBlob;
173 LockedKeyBlobEntry lockedEntry;
174
175 std::tie(rc, keyBlob, charBlob, lockedEntry) =
176 mKeyStore->getKeyForName(name8, targetUid, TYPE_GENERIC);
177 if (rc != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700178 *item = ::std::vector<uint8_t>();
179 // Return empty array if key is not found
180 // TODO: consider having returned value nullable or parse exception on the client.
181 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700182 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100183 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700184 // The static_cast here is needed to prevent a move, forcing a deep copy.
185 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
186 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700187}
188
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700189Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
190 int targetUid, int32_t flags, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700191 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700192 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700193 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700194 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100195 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800196 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700197 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700198 }
199
200 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700201 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), targetUid);
202
203 if (!lockedEntry) {
204 ALOGE("failed to grab lock on blob entry %u_%s", targetUid, name8.string());
205 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_ALREADY_EXISTS);
206 return Status::ok();
207 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700208
Yi Konge353f252018-07-30 01:38:39 -0700209 Blob keyBlob(&item[0], item.size(), nullptr, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700210 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
211
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700212 *aidl_return = static_cast<int32_t>(mKeyStore->put(lockedEntry, keyBlob, {}));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700213 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700214}
215
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700216Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700217 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700218 targetUid = getEffectiveUid(targetUid);
219 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700220 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
221 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700222 }
223 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000224 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700225 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
226 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700227 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
228 return Status::ok();
229 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700230
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700231 ResponseCode result = mKeyStore->del(lockedEntry);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400232
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700233 *aidl_return = static_cast<int32_t>(result);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700234 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700235}
236
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700237Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700238 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700239 targetUid = getEffectiveUid(targetUid);
240 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700241 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
242 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700243 }
244
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700245 LockedKeyBlobEntry lockedEntry =
246 mKeyStore->getLockedBlobEntryIfExists(String8(name).string(), targetUid);
247 *aidl_return =
248 static_cast<int32_t>(lockedEntry ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700249 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700250}
251
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700252Status KeyStoreService::list(const String16& prefix, int32_t targetUid,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700253 ::std::vector<::android::String16>* matches) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700254 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700255 targetUid = getEffectiveUid(targetUid);
256 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700257 return Status::fromServiceSpecificError(
258 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700259 }
260 const String8 prefix8(prefix);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700261 const std::string stdPrefix(prefix8.string());
262
263 ResponseCode rc;
264 std::list<LockedKeyBlobEntry> internal_matches;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800265 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700266
Janis Danisevskis265435f2018-11-16 14:10:46 -0800267 std::tie(rc, internal_matches) =
268 LockedKeyBlobEntry::list(userDirName, [&](uid_t uid, const std::string& alias) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700269 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end());
270 return uid == static_cast<uid_t>(targetUid) &&
271 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end())
272 .first == stdPrefix.end();
273 });
274
275 if (rc != ResponseCode::NO_ERROR) {
276 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700277 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700278
279 for (LockedKeyBlobEntry& entry : internal_matches) {
280 matches->push_back(String16(entry->alias().substr(prefix8.size()).c_str()));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700281 }
282 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700283}
284
Rob Barneseb7f79b2018-11-08 15:44:10 -0700285/*
286 * This method will return the uids of all auth bound keys for the calling user.
287 * This is intended to be used for alerting the user about which apps will be affected
288 * if the password/pin is removed. Only allowed to be called by system.
289 * The output is bound by the initial size of uidsOut to be compatible with Java.
290 */
Rob Barnes5d59e632018-12-07 16:09:02 -0700291Status KeyStoreService::listUidsOfAuthBoundKeys(std::vector<std::string>* uidsOut,
Rob Barneseb7f79b2018-11-08 15:44:10 -0700292 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700293 KEYSTORE_SERVICE_LOCK;
Rob Barneseb7f79b2018-11-08 15:44:10 -0700294 const int32_t callingUid = IPCThreadState::self()->getCallingUid();
295 const int32_t userId = get_user_id(callingUid);
296 const int32_t appId = get_app_id(callingUid);
297 if (appId != AID_SYSTEM) {
298 ALOGE("Permission listUidsOfAuthBoundKeys denied for aid %d", appId);
299 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
300 return Status::ok();
301 }
302
303 const String8 prefix8("");
304 auto userState = mKeyStore->getUserStateDB().getUserState(userId);
305 const std::string userDirName = userState->getUserDirName();
306 auto encryptionKey = userState->getEncryptionKey();
307 auto state = userState->getState();
308 // unlock the user state
309 userState = {};
310
311 ResponseCode rc;
312 std::list<LockedKeyBlobEntry> internal_matches;
313 std::tie(rc, internal_matches) =
314 LockedKeyBlobEntry::list(userDirName, [&](uid_t, const std::string&) {
315 // Need to filter on auth bound state, so just return true.
316 return true;
317 });
318 if (rc != ResponseCode::NO_ERROR) {
319 ALOGE("Error listing blob entries for user %d", userId);
320 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
321 }
322
Rob Barneseb7f79b2018-11-08 15:44:10 -0700323 for (LockedKeyBlobEntry& entry : internal_matches) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700324 // Need to store uids as a list of strings because integer list output
325 // parameters is not supported in aidl-cpp.
326 std::string entryUid = std::to_string(entry->uid());
327 if (std::find(uidsOut->begin(), uidsOut->end(), entryUid) != uidsOut->end()) {
Rob Barneseb7f79b2018-11-08 15:44:10 -0700328 // uid already in list, skip
329 continue;
330 }
331
332 auto [rc, blob, charBlob] = entry.readBlobs(encryptionKey, state);
333 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::LOCKED) {
334 ALOGE("Error reading blob for key %s", entry->alias().c_str());
335 continue;
336 }
337
338 if (blob && blob.isEncrypted()) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700339 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700340 } else if (charBlob) {
341 auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
342 if (!success) {
343 ALOGE("Error reading blob characteristics for key %s", entry->alias().c_str());
344 continue;
345 }
346 if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
347 swEnforced.Contains(TAG_USER_SECURE_ID)) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700348 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700349 }
350 }
351 }
352 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
353 return Status::ok();
354}
355
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700356Status KeyStoreService::reset(int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700357 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700358 if (!checkBinderPermission(P_RESET)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700359 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
360 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700361 }
362
363 uid_t callingUid = IPCThreadState::self()->getCallingUid();
364 mKeyStore->resetUser(get_user_id(callingUid), false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700365 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
366 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700367}
368
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700369Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
370 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700371 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700372 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700373 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
374 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700375 }
376
377 const String8 password8(password);
378 // Flush the auth token table to prevent stale tokens from sticking
379 // around.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700380 mKeyStore->getAuthTokenTable().Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700381
382 if (password.size() == 0) {
383 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
384 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700385 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
386 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700387 } else {
388 switch (mKeyStore->getState(userId)) {
389 case ::STATE_UNINITIALIZED: {
390 // generate master key, encrypt with password, write to file,
391 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700392 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
393 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700394 }
395 case ::STATE_NO_ERROR: {
396 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700397 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
398 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700399 }
400 case ::STATE_LOCKED: {
401 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
402 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700403 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
404 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700405 }
406 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700407 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
408 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700409 }
410}
411
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700412Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700413 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700414 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700415 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
416 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700417 }
418
419 // Sanity check that the new user has an empty keystore.
420 if (!mKeyStore->isEmpty(userId)) {
421 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
422 }
423 // Unconditionally clear the keystore, just to be safe.
424 mKeyStore->resetUser(userId, false);
425 if (parentId != -1) {
426 // This profile must share the same master key password as the parent profile. Because the
427 // password of the parent profile is not known here, the best we can do is copy the parent's
428 // master key and master key file. This makes this profile use the same master key as the
429 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700430 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
431 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700432 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700433 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
434 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700435 }
436}
437
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700438Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700439 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700440 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700441 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
442 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700443 }
444
445 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700446 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
447 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700448}
449
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700450Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700451 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700452 if (!checkBinderPermission(P_LOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700453 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
454 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700455 }
456
457 State state = mKeyStore->getState(userId);
458 if (state != ::STATE_NO_ERROR) {
459 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700460 *aidl_return = static_cast<int32_t>(ResponseCode(state));
461 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700462 }
463
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700464 mKeyStore->getEnforcementPolicy().set_device_locked(true, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700465 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700466 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
467 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700468}
469
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700470Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700471 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700472 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700473 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
474 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700475 }
476
477 State state = mKeyStore->getState(userId);
478 if (state != ::STATE_LOCKED) {
479 switch (state) {
480 case ::STATE_NO_ERROR:
481 ALOGI("calling unlock when already unlocked, ignoring.");
482 break;
483 case ::STATE_UNINITIALIZED:
484 ALOGE("unlock called on uninitialized keystore.");
485 break;
486 default:
487 ALOGE("unlock called on keystore in unknown state: %d", state);
488 break;
489 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700490 *aidl_return = static_cast<int32_t>(ResponseCode(state));
491 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700492 }
493
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700494 mKeyStore->getEnforcementPolicy().set_device_locked(false, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700495 const String8 password8(pw);
496 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700497 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
498 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700499}
500
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700501Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700502 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700503 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700504 *aidl_return = static_cast<int32_t>(false);
505 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700506 }
507
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700508 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
509 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700510}
511
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700512Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
513 ::android::String16* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700514 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700515 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700516 auto result =
517 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100518 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700519 *aidl_return = String16();
520 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700521 }
522
523 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700524 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
525 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700526 *aidl_return = String16();
527 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700528 }
529
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700530 *aidl_return = String16(mKeyStore->addGrant(lockedEntry, granteeUid).c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700531 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700532}
533
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700534Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700535 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700536 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700537 KeyStoreServiceReturnCode result =
538 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100539 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800540 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700541 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700542 }
543
544 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700545
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700546 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
547 if (!lockedEntry) {
548 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700549 }
550
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700551 *aidl_return = mKeyStore->removeGrant(lockedEntry, granteeUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700552 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700553}
554
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700555Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700556 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700557 uid_t targetUid = getEffectiveUid(uid);
558 if (!checkBinderPermission(P_GET, targetUid)) {
559 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700560 *time = -1L;
561 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700562 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700563 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700564
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700565 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
566 if (!lockedEntry) {
567 ALOGW("could not access key with alias %s for getmtime", name8.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700568 *time = -1L;
569 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700570 }
571
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700572 std::string filename = lockedEntry->getKeyBlobPath();
573
574 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700575 if (fd < 0) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700576 ALOGW("could not open %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700577 *time = -1L;
578 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700579 }
580
581 struct stat s;
582 int ret = fstat(fd, &s);
583 close(fd);
584 if (ret == -1) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700585 ALOGW("could not stat %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700586 *time = -1L;
587 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700588 }
589
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700590 *time = static_cast<int64_t>(s.st_mtime);
591 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700592}
593
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700594Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700595 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700596 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
597 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700598}
599
Janis Danisevskis265435f2018-11-16 14:10:46 -0800600Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700601 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700602 uid_t targetUid = getEffectiveUid(targetUid64);
603 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800604 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700605 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000606 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700607
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700608 mKeyStore->removeAllGrantsToUid(targetUid);
609
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700610 ResponseCode rc;
611 std::list<LockedKeyBlobEntry> entries;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800612 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700613
614 // list has a fence making sure no workers are modifying blob files before iterating the
615 // data base. All returned entries are locked.
616 std::tie(rc, entries) = LockedKeyBlobEntry::list(
Janis Danisevskis265435f2018-11-16 14:10:46 -0800617 userDirName, [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700618
619 if (rc != ResponseCode::NO_ERROR) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800620 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700621 }
622
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700623 for (LockedKeyBlobEntry& lockedEntry : entries) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100624 if (get_app_id(targetUid) == AID_SYSTEM) {
625 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700626 Blob charBlob;
627 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
628 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100629 // Do not clear keys critical to device encryption under system uid.
630 continue;
631 }
632 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700633 mKeyStore->del(lockedEntry);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700634 }
Janis Danisevskis265435f2018-11-16 14:10:46 -0800635 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700636}
637
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600638Status KeyStoreService::addRngEntropy(
639 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
640 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700641 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisc1460142017-12-18 16:48:46 -0800642 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
643 if (!device) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600644 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800645 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700646
Janis Danisevskis37896102019-03-14 17:15:06 -0700647 device->addRngEntropy(entropy, [device, cb](Return<ErrorCode> rc) {
648 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device, rc)));
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600649 });
650
651 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700652}
653
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600654Status KeyStoreService::generateKey(
655 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
656 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
657 int uid, int flags, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700658 KEYSTORE_SERVICE_LOCK;
Max Biresef4f0672017-11-29 14:38:48 -0800659 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
660 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700661 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000662 auto logOnScopeExit = android::base::make_scope_guard([&] {
663 if (__android_log_security()) {
664 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600665 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000666 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
667 }
668 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100669 KeyStoreServiceReturnCode rc =
670 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
671 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600672 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700673 }
Rubin Xu67899de2017-04-21 19:15:13 +0100674 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
675 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600676 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100677 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700678
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700679 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700680 // TODO(jbires): remove uid checking upon implementation of b/25646100
Max Bires670467d2017-12-12 11:16:43 -0800681 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Biresef4f0672017-11-29 14:38:48 -0800682 originalUid != IPCThreadState::self()->getCallingUid()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600683 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700684 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600685 }
686
Janis Danisevskisc1460142017-12-18 16:48:46 -0800687 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
688 auto dev = mKeyStore->getDevice(securityLevel);
689 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600690 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800691 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400692
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100693 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700694 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
695 if (!lockedEntry) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600696 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100697 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400698
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700699 logOnScopeExit.Disable();
700
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600701 dev->generateKey(
702 std::move(lockedEntry), params.getParameters(), entropy, flags,
703 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
704 if (__android_log_security()) {
705 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
706 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
707 }
708 cb->onFinished(rc,
709 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
710 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700711
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600712 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700713}
714
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700715Status KeyStoreService::getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600716 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700717 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
Janis Danisevskis64ec1fe2018-02-26 16:47:21 -0800718 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600719 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700720 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700721
722 uid_t targetUid = getEffectiveUid(uid);
723 uid_t callingUid = IPCThreadState::self()->getCallingUid();
724 if (!is_granted_to(callingUid, targetUid)) {
725 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
726 targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600727 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700728 }
729
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700730 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700731
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700732 ResponseCode rc;
733 Blob keyBlob;
734 Blob charBlob;
735 LockedKeyBlobEntry lockedEntry;
Janis Danisevskisd714a672017-09-01 14:31:36 -0700736
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700737 std::tie(rc, keyBlob, charBlob, lockedEntry) =
738 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
739
740 if (rc != ResponseCode::NO_ERROR) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600741 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700742 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100743
Janis Danisevskisc1460142017-12-18 16:48:46 -0800744 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700745 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600746 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100747 }
748
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700749 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
750 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
751 // from keymaster. It may also upgrade the key blob.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700752 dev->getKeyCharacteristics(
753 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
754 std::move(charBlob),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600755 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
756 cb->onFinished(rc,
757 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700758 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100759
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600760 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700761}
762
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600763Status KeyStoreService::importKey(
764 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
765 const String16& name, const KeymasterArguments& params, int32_t format,
766 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700767 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700768 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000769 auto logOnScopeExit = android::base::make_scope_guard([&] {
770 if (__android_log_security()) {
771 android_log_event_list(SEC_TAG_KEY_IMPORTED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600772 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000773 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
774 }
775 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100776 KeyStoreServiceReturnCode rc =
777 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
778 if (!rc.isOk()) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700779 LOG(ERROR) << "permissission denied";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600780 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700781 }
Rubin Xu67899de2017-04-21 19:15:13 +0100782 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
783 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600784 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100785 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700786
Janis Danisevskisc1460142017-12-18 16:48:46 -0800787 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
788 auto dev = mKeyStore->getDevice(securityLevel);
789 if (!dev) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700790 LOG(ERROR) << "importKey - cound not get keymaster device";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600791 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800792 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700793
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700794 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700795 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
796 if (!lockedEntry) {
797 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
798 << " already exists.";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600799 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400800 }
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700801
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700802 logOnScopeExit.Disable();
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700803
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600804 dev->importKey(
805 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
806 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
807 if (__android_log_security()) {
808 android_log_event_list(SEC_TAG_KEY_IMPORTED)
809 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
810 }
811 cb->onFinished(rc,
812 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
813 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400814
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600815 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700816}
817
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600818Status KeyStoreService::exportKey(
819 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
820 const String16& name, int32_t format,
821 const ::android::security::keymaster::KeymasterBlob& clientId,
822 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
823 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700824 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700825
826 uid_t targetUid = getEffectiveUid(uid);
827 uid_t callingUid = IPCThreadState::self()->getCallingUid();
828 if (!is_granted_to(callingUid, targetUid)) {
829 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600830 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700831 }
832
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700833 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700834
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700835 KeyStoreServiceReturnCode rc;
836 Blob keyBlob;
837 Blob charBlob;
838 LockedKeyBlobEntry lockedEntry;
839
840 std::tie(rc, keyBlob, charBlob, lockedEntry) =
841 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskis3cf85322018-11-19 13:37:49 -0800842 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600843 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700844 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100845
Janis Danisevskisc1460142017-12-18 16:48:46 -0800846 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100847
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700848 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600849 std::move(keyBlob), std::move(charBlob),
850 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
Ji Wang2c142312016-10-14 17:21:10 +0800851
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600852 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700853}
854
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600855Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
856 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700857 bool pruneable, const KeymasterArguments& params,
858 const ::std::vector<uint8_t>& entropy, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600859 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700860 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700861 uid_t callingUid = IPCThreadState::self()->getCallingUid();
862 uid_t targetUid = getEffectiveUid(uid);
863 if (!is_granted_to(callingUid, targetUid)) {
864 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600865 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700866 }
867 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
868 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600869 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700870 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700871 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600872 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700873 }
Shawn Willden0329a822017-12-04 13:55:14 -0700874
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700875 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700876 Blob keyBlob;
877 Blob charBlob;
878 LockedKeyBlobEntry lockedEntry;
879 ResponseCode rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100880
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700881 std::tie(rc, keyBlob, charBlob, lockedEntry) =
882 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
883
884 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600885 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700886 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600887 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700888
Janis Danisevskisc1460142017-12-18 16:48:46 -0800889 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700890 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100891
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700892 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
893 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600894 [this, cb, dev](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700895 if (result_.resultCode.isOk() ||
896 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
897 addOperationDevice(result_.token, dev);
898 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600899 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700900 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400901
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600902 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700903}
904
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600905Status KeyStoreService::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
906 const ::android::sp<::android::IBinder>& token,
907 const ::android::security::keymaster::KeymasterArguments& params,
908 const ::std::vector<uint8_t>& input, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700909 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700910 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600911 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700912 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700913
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700914 auto dev = getOperationDevice(token);
915 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600916 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700917 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700918
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600919 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700920 if (!result_.resultCode.isOk()) {
921 removeOperationDevice(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100922 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600923 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700924 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100925
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600926 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700927}
928
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600929Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
930 const ::android::sp<::android::IBinder>& token,
931 const ::android::security::keymaster::KeymasterArguments& params,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700932 const ::std::vector<uint8_t>& signature,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600933 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700934 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700935 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600936 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700937 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700938
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700939 auto dev = getOperationDevice(token);
940 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600941 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700942 }
943
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700944 dev->finish(token, params.getParameters(), {}, signature, entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600945 [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700946 if (!result_.resultCode.isOk()) {
947 removeOperationDevice(token);
948 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600949 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700950 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700951
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600952 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700953}
954
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600955Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
956 const ::android::sp<::android::IBinder>& token,
957 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700958 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700959 auto dev = getOperationDevice(token);
960 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600961 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700962 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100963
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600964 dev->abort(token, [cb](KeyStoreServiceReturnCode rc) { cb->onFinished(rc); });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700965
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600966 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700967}
968
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700969Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000970 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700971 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700972
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000973 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
974 // receive a HardwareAuthToken, rather than an opaque byte array.
975
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700976 if (!checkBinderPermission(P_ADD_AUTH)) {
977 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700978 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
979 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700980 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700981 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
Branden Archer70080742018-11-20 11:04:11 -0800982 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700983 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000984 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100985
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000986 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700987 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000988 if (authToken.version != 0) {
Branden Archer70080742018-11-20 11:04:11 -0800989 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700990 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000991 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100992
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700993 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
994 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700995 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
996 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700997}
998
Rubin Xu1a203e32018-05-08 14:25:21 +0100999int isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -07001000 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Rubin Xu1a203e32018-05-08 14:25:21 +01001001 int result = 0;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001002 for (size_t i = 0; i < paramsVec.size(); ++i) {
1003 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -06001004 case Tag::ATTESTATION_ID_BRAND:
1005 case Tag::ATTESTATION_ID_DEVICE:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001006 case Tag::ATTESTATION_ID_MANUFACTURER:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001007 case Tag::ATTESTATION_ID_MODEL:
1008 case Tag::ATTESTATION_ID_PRODUCT:
Rubin Xu1a203e32018-05-08 14:25:21 +01001009 result |= ID_ATTESTATION_REQUEST_GENERIC_INFO;
Shawn Willdene2a7b522017-04-11 09:27:40 -06001010 break;
Rubin Xu1a203e32018-05-08 14:25:21 +01001011 case Tag::ATTESTATION_ID_IMEI:
1012 case Tag::ATTESTATION_ID_MEID:
1013 case Tag::ATTESTATION_ID_SERIAL:
1014 result |= ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID;
1015 break;
1016 default:
1017 continue;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001018 }
1019 }
Rubin Xu1a203e32018-05-08 14:25:21 +01001020 return result;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001021}
1022
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001023Status KeyStoreService::attestKey(
1024 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1025 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001026 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001027 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1028 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001029 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001030 }
1031
Eran Messerie2c34152017-12-21 21:01:22 +00001032 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1033
Rubin Xu1a203e32018-05-08 14:25:21 +01001034 int needsIdAttestation = isDeviceIdAttestationRequested(params);
1035 bool needsUniqueIdAttestation = needsIdAttestation & ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID;
1036 bool isPrimaryUserSystemUid = (callingUid == AID_SYSTEM);
1037 bool isSomeUserSystemUid = (get_app_id(callingUid) == AID_SYSTEM);
1038 // Allow system context from any user to request attestation with basic device information,
1039 // while only allow system context from user 0 (device owner) to request attestation with
1040 // unique device ID.
1041 if ((needsIdAttestation && !isSomeUserSystemUid) ||
1042 (needsUniqueIdAttestation && !isPrimaryUserSystemUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001043 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001044 }
1045
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001046 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001047 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1048 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001049 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001050 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001051
Shawn Willden50eb1b22016-01-21 12:41:23 -07001052 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001053 Blob keyBlob;
1054 Blob charBlob;
1055 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001056
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001057 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1058 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1059
Janis Danisevskis9dff56c2019-07-10 14:08:06 -07001060 if (!rc.isOk()) {
1061 return AIDL_RETURN(rc);
1062 }
1063
Janis Danisevskisc1460142017-12-18 16:48:46 -08001064 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001065 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001066 dev->attestKey(
1067 std::move(hidlKey), mutableParams.hidl_data(),
Janis Danisevskis37896102019-03-14 17:15:06 -07001068 [dev, cb](Return<void> rc,
1069 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001070 auto& [ret, certChain] = hidlResult;
1071 if (!rc.isOk()) {
1072 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1073 } else if (ret != ErrorCode::OK) {
Janis Danisevskis37896102019-03-14 17:15:06 -07001074 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001075 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1076 } else {
1077 cb->onFinished(KeyStoreServiceReturnCode(ret),
1078 KeymasterCertificateChain(std::move(certChain)));
1079 }
1080 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001081
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001082 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001083}
1084
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001085// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1086// It should never be redefined by a build system though.
1087#ifndef CAPTURE_MOVE
1088#define CAPTURE_MOVE(x) x = std::move(x)
1089#endif
1090
1091Status KeyStoreService::attestDeviceIds(
1092 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1093 const KeymasterArguments& params, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001094 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001095 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001096
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001097 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001098 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001099 }
1100
1101 if (!isDeviceIdAttestationRequested(params)) {
1102 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001103 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001104 }
1105
1106 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1107 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
Yi Konge353f252018-07-30 01:38:39 -07001108 if (binder == nullptr) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001109 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001110 }
1111 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1112 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1113 IPCThreadState::self()->getCallingPid(), callingUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001114 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001115 }
1116
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001117 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001118 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1119 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001120 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001121 }
1122
1123 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001124 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001125
Shawn Willden70c1a782018-07-11 15:13:20 -06001126 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001127 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001128 }
1129
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001130
1131 AuthorizationSet keyCharacteristics;
1132 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1133 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1134 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1135 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1136 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001137
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001138 std::promise<KeyStoreServiceReturnCode> resultPromise;
1139 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001140
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001141 dev->generateKey(
1142 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001143 [cb, dev, CAPTURE_MOVE(mutableParams)](
1144 Return<void> rc,
1145 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001146 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1147 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1148 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001149 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001150 return;
1151 }
1152 if (ret != ErrorCode::OK) {
Janis Danisevskis37896102019-03-14 17:15:06 -07001153 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001154 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001155 return;
1156 }
1157 dev->attestKey(
1158 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001159 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001160 hidlKeyBlob](Return<void> rc,
1161 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1162 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001163 // schedule temp key for deletion
Janis Danisevskis37896102019-03-14 17:15:06 -07001164 dev->deleteKey(std::move(hidlKeyBlob), [dev](Return<ErrorCode> rc) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001165 // log error but don't return an error
Janis Danisevskis37896102019-03-14 17:15:06 -07001166 KS_HANDLE_HIDL_ERROR(dev, rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001167 });
1168 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001169 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001170 return;
1171 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001172 if (ret == ErrorCode::OK) {
1173 cb->onFinished(
1174 KeyStoreServiceReturnCode(ret),
1175 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1176 } else {
Janis Danisevskis37896102019-03-14 17:15:06 -07001177 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001178 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001179 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001180 });
1181 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001182
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001183 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001184}
1185
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001186Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001187 KEYSTORE_SERVICE_LOCK;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001188 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001189 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001190 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1191 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001192}
1193
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001194Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001195 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001196 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1197 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1198 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001199 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001200 KEYSTORE_SERVICE_LOCK;
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001201
1202 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1203
1204 if (!checkBinderPermission(P_INSERT, callingUid)) {
1205 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1206 }
1207
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001208 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001209
1210 KeyStoreServiceReturnCode rc;
1211 Blob wrappingKeyBlob;
1212 Blob wrappingCharBlob;
1213 LockedKeyBlobEntry wrappingLockedEntry;
1214
1215 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1216 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
Branden Archerd166a882018-11-20 10:56:48 -08001217 if (!rc.isOk()) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001218 return AIDL_RETURN(rc);
1219 }
1220
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001221 String8 wrappedKeyName8(wrappedKeyAlias);
1222 auto wrappedLockedEntry =
1223 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1224 if (!wrappedLockedEntry) {
1225 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1226 }
1227
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001228 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1229 auto dev = mKeyStore->getDevice(securityLevel);
1230 if (!dev) {
1231 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1232 }
1233
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001234 dev->importWrappedKey(
1235 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1236 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001237 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1238 cb->onFinished(rc,
1239 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001240 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001241
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001242 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001243}
1244
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001245Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1246 const String16& promptText,
1247 const ::std::vector<uint8_t>& extraData,
1248 const String16& locale, int32_t uiOptionsAsFlags,
1249 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001250 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001251 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1252 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001253}
1254
1255Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1256 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001257 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001258 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001259}
1260
David Zeuthen1a492312018-02-26 11:00:30 -05001261Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001262 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001263 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001264}
1265
1266/**
1267 * Get the effective target uid for a binder operation that takes an
1268 * optional uid as the target.
1269 */
1270uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1271 if (targetUid == UID_SELF) {
1272 return IPCThreadState::self()->getCallingUid();
1273 }
1274 return static_cast<uid_t>(targetUid);
1275}
1276
1277/**
1278 * Check if the caller of the current binder method has the required
1279 * permission and if acting on other uids the grants to do so.
1280 */
1281bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1282 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1283 pid_t spid = IPCThreadState::self()->getCallingPid();
1284 if (!has_permission(callingUid, permission, spid)) {
1285 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1286 return false;
1287 }
1288 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1289 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1290 return false;
1291 }
1292 return true;
1293}
1294
1295/**
1296 * Check if the caller of the current binder method has the required
1297 * permission and the target uid is the caller or the caller is system.
1298 */
1299bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1300 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1301 pid_t spid = IPCThreadState::self()->getCallingPid();
1302 if (!has_permission(callingUid, permission, spid)) {
1303 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1304 return false;
1305 }
1306 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1307}
1308
1309/**
1310 * Check if the caller of the current binder method has the required
1311 * permission or the target of the operation is the caller's uid. This is
1312 * for operation where the permission is only for cross-uid activity and all
1313 * uids are allowed to act on their own (ie: clearing all entries for a
1314 * given uid).
1315 */
1316bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1317 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1318 if (getEffectiveUid(targetUid) == callingUid) {
1319 return true;
1320 } else {
1321 return checkBinderPermission(permission, targetUid);
1322 }
1323}
1324
1325/**
1326 * Helper method to check that the caller has the required permission as
1327 * well as the keystore is in the unlocked state if checkUnlocked is true.
1328 *
1329 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1330 * otherwise the state of keystore when not unlocked and checkUnlocked is
1331 * true.
1332 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001333KeyStoreServiceReturnCode
1334KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1335 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001336 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001337 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001338 }
1339 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1340 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001341 // All State values coincide with ResponseCodes
1342 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001343 }
1344
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001345 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001346}
1347
1348bool KeyStoreService::isKeystoreUnlocked(State state) {
1349 switch (state) {
1350 case ::STATE_NO_ERROR:
1351 return true;
1352 case ::STATE_UNINITIALIZED:
1353 case ::STATE_LOCKED:
1354 return false;
1355 }
1356 return false;
1357}
1358
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001359/**
Shawn Willden0329a822017-12-04 13:55:14 -07001360 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1361 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001362 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001363bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1364 for (size_t i = 0; i < params.size(); ++i) {
1365 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001366 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001367 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001368 return false;
1369 default:
1370 break;
1371 }
1372 }
1373 return true;
1374}
1375
Brian Young9a947d52018-02-23 18:03:14 +00001376Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
1377 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001378 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001379 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Brian Young9a947d52018-02-23 18:03:14 +00001380 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001381
1382 return Status::ok();
1383}
1384
Shawn Willdene2a7b522017-04-11 09:27:40 -06001385} // namespace keystore