blob: c57012ec4de0ed3270a2ed004ecafc7c1cb85994 [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
Shawn Willdene2a7b522017-04-11 09:27:40 -060073bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070074 return params.end() !=
75 std::find_if(params.begin(), params.end(),
76 [&](const KeyParameter& param) { return param.tag == tag; });
Shawn Willdend5a24e62017-02-28 13:53:24 -070077}
78
Branden Archer70080742018-11-20 11:04:11 -080079#define AIDL_RETURN(rc) (*_aidl_return = KeyStoreServiceReturnCode(rc).getErrorCode(), Status::ok())
Janis Danisevskisb50236a2019-03-25 10:26:30 -070080#define KEYSTORE_SERVICE_LOCK std::lock_guard<std::mutex> keystore_lock(keystoreServiceMutex_)
Rob Barnesbb6cabd2018-10-04 17:10:37 -060081
Shawn Willdene2a7b522017-04-11 09:27:40 -060082std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
83 struct stat sbuf;
84 if (stat(kTimestampFilePath, &sbuf) == 0) {
Yi Konge353f252018-07-30 01:38:39 -070085 double diff_secs = difftime(time(nullptr), sbuf.st_ctime);
Shawn Willdene2a7b522017-04-11 09:27:40 -060086 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
87 }
88
89 if (errno != ENOENT) {
90 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
91 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
92 }
93
94 int fd = creat(kTimestampFilePath, 0600);
95 if (fd < 0) {
96 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
97 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
98 }
99
100 if (close(fd)) {
101 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
102 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
103 }
104
105 return {ResponseCode::NO_ERROR, true};
106}
107
Eran Messeri03fc4c82018-08-16 18:53:15 +0100108using ::android::security::KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200109
110KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
111 KeyStoreServiceReturnCode responseCode;
112 bool factoryResetSinceIdRotation;
113 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
114
115 if (!responseCode.isOk()) return responseCode;
116 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
117
118 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
119 if (!asn1_attestation_id_result.isOk()) {
120 ALOGE("failed to gather attestation_id");
Shawn Willden6f7d27c2019-09-11 22:51:46 -0600121 // Couldn't get attestation ID; just use an empty one rather than failing.
122 asn1_attestation_id_result = std::vector<uint8_t>();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200123 }
124 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
125
126 /*
Eran Messeri03fc4c82018-08-16 18:53:15 +0100127 * The attestation application ID must not be longer than
128 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, error out if gather_attestation_application_id
129 * returned such an invalid vector.
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200130 */
131 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Eran Messeri03fc4c82018-08-16 18:53:15 +0100132 ALOGE("BUG: Gathered Attestation Application ID is too big (%d)",
133 static_cast<int32_t>(asn1_attestation_id.size()));
134 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200135 }
136
137 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
138
139 return ResponseCode::NO_ERROR;
140}
141
Shawn Willdene2a7b522017-04-11 09:27:40 -0600142} // anonymous namespace
143
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700144Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700145 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700146 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700147 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
148 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700149 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700150 *aidl_return = mKeyStore->getState(userId);
151 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700152}
153
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700154Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700155 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700156 uid_t targetUid = getEffectiveUid(uid);
157 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700158 // see keystore/keystore.h
159 return Status::fromServiceSpecificError(
160 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700161 }
162
163 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700164 ResponseCode rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700165 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700166 Blob charBlob;
167 LockedKeyBlobEntry lockedEntry;
168
169 std::tie(rc, keyBlob, charBlob, lockedEntry) =
170 mKeyStore->getKeyForName(name8, targetUid, TYPE_GENERIC);
171 if (rc != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700172 *item = ::std::vector<uint8_t>();
173 // Return empty array if key is not found
174 // TODO: consider having returned value nullable or parse exception on the client.
175 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700176 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100177 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700178 // The static_cast here is needed to prevent a move, forcing a deep copy.
179 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
180 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700181}
182
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700183Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
184 int targetUid, int32_t flags, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700185 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700186 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700187 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700188 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100189 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800190 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700191 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700192 }
193
194 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700195 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), targetUid);
196
197 if (!lockedEntry) {
198 ALOGE("failed to grab lock on blob entry %u_%s", targetUid, name8.string());
199 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_ALREADY_EXISTS);
200 return Status::ok();
201 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700202
Yi Konge353f252018-07-30 01:38:39 -0700203 Blob keyBlob(&item[0], item.size(), nullptr, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700204 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
205
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700206 *aidl_return = static_cast<int32_t>(mKeyStore->put(lockedEntry, keyBlob, {}));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700207 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700208}
209
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700210Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700211 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700212 targetUid = getEffectiveUid(targetUid);
213 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700214 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
215 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700216 }
217 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000218 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700219 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
220 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700221 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
222 return Status::ok();
223 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700224
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700225 ResponseCode result = mKeyStore->del(lockedEntry);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400226
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700227 *aidl_return = static_cast<int32_t>(result);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700228 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700229}
230
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700231Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700232 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700233 targetUid = getEffectiveUid(targetUid);
234 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700235 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
236 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700237 }
238
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700239 LockedKeyBlobEntry lockedEntry =
240 mKeyStore->getLockedBlobEntryIfExists(String8(name).string(), targetUid);
241 *aidl_return =
242 static_cast<int32_t>(lockedEntry ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700243 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700244}
245
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700246Status KeyStoreService::list(const String16& prefix, int32_t targetUid,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700247 ::std::vector<::android::String16>* matches) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700248 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700249 targetUid = getEffectiveUid(targetUid);
250 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700251 return Status::fromServiceSpecificError(
252 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700253 }
254 const String8 prefix8(prefix);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700255 const std::string stdPrefix(prefix8.string());
256
257 ResponseCode rc;
258 std::list<LockedKeyBlobEntry> internal_matches;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800259 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700260
Janis Danisevskis265435f2018-11-16 14:10:46 -0800261 std::tie(rc, internal_matches) =
262 LockedKeyBlobEntry::list(userDirName, [&](uid_t uid, const std::string& alias) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700263 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end());
264 return uid == static_cast<uid_t>(targetUid) &&
265 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end())
266 .first == stdPrefix.end();
267 });
268
269 if (rc != ResponseCode::NO_ERROR) {
270 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700271 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700272
273 for (LockedKeyBlobEntry& entry : internal_matches) {
274 matches->push_back(String16(entry->alias().substr(prefix8.size()).c_str()));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700275 }
276 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700277}
278
Rob Barneseb7f79b2018-11-08 15:44:10 -0700279/*
280 * This method will return the uids of all auth bound keys for the calling user.
281 * This is intended to be used for alerting the user about which apps will be affected
282 * if the password/pin is removed. Only allowed to be called by system.
283 * The output is bound by the initial size of uidsOut to be compatible with Java.
284 */
Rob Barnes5d59e632018-12-07 16:09:02 -0700285Status KeyStoreService::listUidsOfAuthBoundKeys(std::vector<std::string>* uidsOut,
Rob Barneseb7f79b2018-11-08 15:44:10 -0700286 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700287 KEYSTORE_SERVICE_LOCK;
Rob Barneseb7f79b2018-11-08 15:44:10 -0700288 const int32_t callingUid = IPCThreadState::self()->getCallingUid();
289 const int32_t userId = get_user_id(callingUid);
290 const int32_t appId = get_app_id(callingUid);
291 if (appId != AID_SYSTEM) {
292 ALOGE("Permission listUidsOfAuthBoundKeys denied for aid %d", appId);
293 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
294 return Status::ok();
295 }
296
297 const String8 prefix8("");
298 auto userState = mKeyStore->getUserStateDB().getUserState(userId);
299 const std::string userDirName = userState->getUserDirName();
300 auto encryptionKey = userState->getEncryptionKey();
301 auto state = userState->getState();
302 // unlock the user state
303 userState = {};
304
305 ResponseCode rc;
306 std::list<LockedKeyBlobEntry> internal_matches;
307 std::tie(rc, internal_matches) =
308 LockedKeyBlobEntry::list(userDirName, [&](uid_t, const std::string&) {
309 // Need to filter on auth bound state, so just return true.
310 return true;
311 });
312 if (rc != ResponseCode::NO_ERROR) {
313 ALOGE("Error listing blob entries for user %d", userId);
314 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
315 }
316
Rob Barneseb7f79b2018-11-08 15:44:10 -0700317 for (LockedKeyBlobEntry& entry : internal_matches) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700318 // Need to store uids as a list of strings because integer list output
319 // parameters is not supported in aidl-cpp.
320 std::string entryUid = std::to_string(entry->uid());
321 if (std::find(uidsOut->begin(), uidsOut->end(), entryUid) != uidsOut->end()) {
Rob Barneseb7f79b2018-11-08 15:44:10 -0700322 // uid already in list, skip
323 continue;
324 }
325
326 auto [rc, blob, charBlob] = entry.readBlobs(encryptionKey, state);
327 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::LOCKED) {
328 ALOGE("Error reading blob for key %s", entry->alias().c_str());
329 continue;
330 }
331
332 if (blob && blob.isEncrypted()) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700333 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700334 } else if (charBlob) {
335 auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
336 if (!success) {
337 ALOGE("Error reading blob characteristics for key %s", entry->alias().c_str());
338 continue;
339 }
340 if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
341 swEnforced.Contains(TAG_USER_SECURE_ID)) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700342 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700343 }
344 }
345 }
346 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
347 return Status::ok();
348}
349
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700350Status KeyStoreService::reset(int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700351 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700352 if (!checkBinderPermission(P_RESET)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700353 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
354 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700355 }
356
357 uid_t callingUid = IPCThreadState::self()->getCallingUid();
358 mKeyStore->resetUser(get_user_id(callingUid), false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700359 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
360 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700361}
362
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700363Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
364 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700365 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700366 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700367 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
368 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700369 }
370
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700371 if (password.size() == 0) {
372 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
373 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700374 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
375 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700376 } else {
Pavel Grafovf9b53eb2019-02-06 17:16:21 +0000377 const String8 password8(password);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700378 switch (mKeyStore->getState(userId)) {
379 case ::STATE_UNINITIALIZED: {
380 // generate master key, encrypt with password, write to file,
381 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700382 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
383 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700384 }
385 case ::STATE_NO_ERROR: {
386 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700387 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
388 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700389 }
390 case ::STATE_LOCKED: {
391 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
392 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700393 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
394 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700395 }
396 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700397 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
398 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700399 }
400}
401
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700402Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700403 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700404 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700405 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
406 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700407 }
408
409 // Sanity check that the new user has an empty keystore.
410 if (!mKeyStore->isEmpty(userId)) {
411 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
412 }
413 // Unconditionally clear the keystore, just to be safe.
414 mKeyStore->resetUser(userId, false);
415 if (parentId != -1) {
416 // This profile must share the same master key password as the parent profile. Because the
417 // password of the parent profile is not known here, the best we can do is copy the parent's
418 // master key and master key file. This makes this profile use the same master key as the
419 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700420 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
421 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700422 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700423 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
424 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700425 }
426}
427
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700428Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700429 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700430 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700431 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
432 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700433 }
434
435 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700436 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
437 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700438}
439
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700440Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700441 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700442 if (!checkBinderPermission(P_LOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700443 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
444 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700445 }
446
447 State state = mKeyStore->getState(userId);
448 if (state != ::STATE_NO_ERROR) {
449 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700450 *aidl_return = static_cast<int32_t>(ResponseCode(state));
451 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700452 }
453
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700454 mKeyStore->getEnforcementPolicy().set_device_locked(true, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700455 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700456 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
457 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700458}
459
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700460Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700461 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700462 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700463 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
464 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700465 }
466
467 State state = mKeyStore->getState(userId);
468 if (state != ::STATE_LOCKED) {
469 switch (state) {
470 case ::STATE_NO_ERROR:
471 ALOGI("calling unlock when already unlocked, ignoring.");
472 break;
473 case ::STATE_UNINITIALIZED:
474 ALOGE("unlock called on uninitialized keystore.");
475 break;
476 default:
477 ALOGE("unlock called on keystore in unknown state: %d", state);
478 break;
479 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700480 *aidl_return = static_cast<int32_t>(ResponseCode(state));
481 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700482 }
483
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700484 mKeyStore->getEnforcementPolicy().set_device_locked(false, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700485 const String8 password8(pw);
486 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700487 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
488 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700489}
490
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700491Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700492 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700493 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700494 *aidl_return = static_cast<int32_t>(false);
495 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700496 }
497
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700498 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
499 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700500}
501
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700502Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
503 ::android::String16* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700504 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700505 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700506 auto result =
507 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100508 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700509 *aidl_return = String16();
510 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700511 }
512
513 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700514 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
515 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700516 *aidl_return = String16();
517 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700518 }
519
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700520 *aidl_return = String16(mKeyStore->addGrant(lockedEntry, granteeUid).c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700521 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700522}
523
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700524Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700525 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700526 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700527 KeyStoreServiceReturnCode result =
528 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100529 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800530 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700531 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700532 }
533
534 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700535
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700536 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
537 if (!lockedEntry) {
538 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700539 }
540
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700541 *aidl_return = mKeyStore->removeGrant(lockedEntry, granteeUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700542 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700543}
544
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700545Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700546 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700547 uid_t targetUid = getEffectiveUid(uid);
548 if (!checkBinderPermission(P_GET, targetUid)) {
549 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700550 *time = -1L;
551 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700552 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700553 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700554
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700555 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
556 if (!lockedEntry) {
557 ALOGW("could not access key with alias %s for getmtime", name8.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700558 *time = -1L;
559 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700560 }
561
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700562 std::string filename = lockedEntry->getKeyBlobPath();
563
564 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700565 if (fd < 0) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700566 ALOGW("could not open %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700567 *time = -1L;
568 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700569 }
570
571 struct stat s;
572 int ret = fstat(fd, &s);
573 close(fd);
574 if (ret == -1) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700575 ALOGW("could not stat %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700576 *time = -1L;
577 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700578 }
579
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700580 *time = static_cast<int64_t>(s.st_mtime);
581 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700582}
583
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700584Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700585 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700586 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
587 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700588}
589
Janis Danisevskis265435f2018-11-16 14:10:46 -0800590Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700591 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700592 uid_t targetUid = getEffectiveUid(targetUid64);
593 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800594 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700595 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000596 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700597
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700598 mKeyStore->removeAllGrantsToUid(targetUid);
599
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700600 ResponseCode rc;
601 std::list<LockedKeyBlobEntry> entries;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800602 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700603
604 // list has a fence making sure no workers are modifying blob files before iterating the
605 // data base. All returned entries are locked.
606 std::tie(rc, entries) = LockedKeyBlobEntry::list(
Janis Danisevskis265435f2018-11-16 14:10:46 -0800607 userDirName, [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700608
609 if (rc != ResponseCode::NO_ERROR) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800610 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700611 }
612
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700613 for (LockedKeyBlobEntry& lockedEntry : entries) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100614 if (get_app_id(targetUid) == AID_SYSTEM) {
615 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700616 Blob charBlob;
617 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
618 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100619 // Do not clear keys critical to device encryption under system uid.
620 continue;
621 }
622 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700623 mKeyStore->del(lockedEntry);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700624 }
Janis Danisevskis265435f2018-11-16 14:10:46 -0800625 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700626}
627
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600628Status KeyStoreService::addRngEntropy(
629 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
630 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700631 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisc1460142017-12-18 16:48:46 -0800632 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
633 if (!device) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600634 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800635 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700636
Janis Danisevskisa359c672019-03-14 17:15:06 -0700637 device->addRngEntropy(entropy, [device, cb](Return<ErrorCode> rc) {
638 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device, rc)));
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600639 });
640
641 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700642}
643
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600644Status KeyStoreService::generateKey(
645 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
646 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
647 int uid, int flags, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700648 KEYSTORE_SERVICE_LOCK;
Max Biresef4f0672017-11-29 14:38:48 -0800649 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
650 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700651 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000652 auto logOnScopeExit = android::base::make_scope_guard([&] {
653 if (__android_log_security()) {
654 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600655 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000656 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
657 }
658 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100659 KeyStoreServiceReturnCode rc =
660 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
661 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600662 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700663 }
Rubin Xu67899de2017-04-21 19:15:13 +0100664 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
665 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600666 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100667 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700668
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700669 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700670 // TODO(jbires): remove uid checking upon implementation of b/25646100
Max Bires670467d2017-12-12 11:16:43 -0800671 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Biresef4f0672017-11-29 14:38:48 -0800672 originalUid != IPCThreadState::self()->getCallingUid()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600673 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700674 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600675 }
676
Janis Danisevskisc1460142017-12-18 16:48:46 -0800677 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
678 auto dev = mKeyStore->getDevice(securityLevel);
679 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600680 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800681 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400682
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100683 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700684 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
685 if (!lockedEntry) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600686 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100687 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400688
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700689 logOnScopeExit.Disable();
690
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600691 dev->generateKey(
692 std::move(lockedEntry), params.getParameters(), entropy, flags,
693 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
694 if (__android_log_security()) {
695 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
696 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
697 }
698 cb->onFinished(rc,
699 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
700 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700701
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600702 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700703}
704
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700705Status KeyStoreService::getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600706 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700707 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
Janis Danisevskis64ec1fe2018-02-26 16:47:21 -0800708 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600709 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700710 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700711
712 uid_t targetUid = getEffectiveUid(uid);
713 uid_t callingUid = IPCThreadState::self()->getCallingUid();
714 if (!is_granted_to(callingUid, targetUid)) {
715 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
716 targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600717 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700718 }
719
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700720 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700721
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700722 ResponseCode rc;
723 Blob keyBlob;
724 Blob charBlob;
725 LockedKeyBlobEntry lockedEntry;
Janis Danisevskisd714a672017-09-01 14:31:36 -0700726
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700727 std::tie(rc, keyBlob, charBlob, lockedEntry) =
728 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
729
730 if (rc != ResponseCode::NO_ERROR) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600731 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700732 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100733
Janis Danisevskisc1460142017-12-18 16:48:46 -0800734 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700735 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600736 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100737 }
738
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700739 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
740 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
741 // from keymaster. It may also upgrade the key blob.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700742 dev->getKeyCharacteristics(
743 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
744 std::move(charBlob),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600745 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
746 cb->onFinished(rc,
747 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700748 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100749
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600750 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700751}
752
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600753Status KeyStoreService::importKey(
754 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
755 const String16& name, const KeymasterArguments& params, int32_t format,
756 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700757 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700758 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000759 auto logOnScopeExit = android::base::make_scope_guard([&] {
760 if (__android_log_security()) {
761 android_log_event_list(SEC_TAG_KEY_IMPORTED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600762 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000763 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
764 }
765 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100766 KeyStoreServiceReturnCode rc =
767 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
768 if (!rc.isOk()) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700769 LOG(ERROR) << "permissission denied";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600770 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700771 }
Rubin Xu67899de2017-04-21 19:15:13 +0100772 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
773 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600774 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100775 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700776
Janis Danisevskisc1460142017-12-18 16:48:46 -0800777 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
778 auto dev = mKeyStore->getDevice(securityLevel);
779 if (!dev) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700780 LOG(ERROR) << "importKey - cound not get keymaster device";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600781 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800782 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700783
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700784 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700785 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
786 if (!lockedEntry) {
787 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
788 << " already exists.";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600789 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400790 }
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700791
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700792 logOnScopeExit.Disable();
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700793
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600794 dev->importKey(
795 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
796 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
797 if (__android_log_security()) {
798 android_log_event_list(SEC_TAG_KEY_IMPORTED)
799 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
800 }
801 cb->onFinished(rc,
802 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
803 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400804
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600805 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700806}
807
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600808Status KeyStoreService::exportKey(
809 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
810 const String16& name, int32_t format,
811 const ::android::security::keymaster::KeymasterBlob& clientId,
812 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
813 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700814 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700815
816 uid_t targetUid = getEffectiveUid(uid);
817 uid_t callingUid = IPCThreadState::self()->getCallingUid();
818 if (!is_granted_to(callingUid, targetUid)) {
819 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600820 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700821 }
822
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700823 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700824
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700825 KeyStoreServiceReturnCode rc;
826 Blob keyBlob;
827 Blob charBlob;
828 LockedKeyBlobEntry lockedEntry;
829
830 std::tie(rc, keyBlob, charBlob, lockedEntry) =
831 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskis3cf85322018-11-19 13:37:49 -0800832 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600833 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700834 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100835
Janis Danisevskisc1460142017-12-18 16:48:46 -0800836 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100837
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700838 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600839 std::move(keyBlob), std::move(charBlob),
840 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
Ji Wang2c142312016-10-14 17:21:10 +0800841
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600842 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700843}
844
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600845Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
846 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700847 bool pruneable, const KeymasterArguments& params,
848 const ::std::vector<uint8_t>& entropy, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600849 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700850 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700851 uid_t callingUid = IPCThreadState::self()->getCallingUid();
852 uid_t targetUid = getEffectiveUid(uid);
853 if (!is_granted_to(callingUid, targetUid)) {
854 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600855 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700856 }
857 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
858 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600859 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700860 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700861 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600862 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700863 }
Shawn Willden0329a822017-12-04 13:55:14 -0700864
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700865 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700866 Blob keyBlob;
867 Blob charBlob;
868 LockedKeyBlobEntry lockedEntry;
869 ResponseCode rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100870
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700871 std::tie(rc, keyBlob, charBlob, lockedEntry) =
872 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
873
874 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600875 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700876 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600877 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700878
Janis Danisevskisc1460142017-12-18 16:48:46 -0800879 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700880 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100881
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700882 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
883 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600884 [this, cb, dev](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700885 if (result_.resultCode.isOk() ||
886 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700887 mKeyStore->addOperationDevice(result_.token, dev);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700888 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600889 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700890 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400891
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600892 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700893}
894
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600895Status KeyStoreService::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
896 const ::android::sp<::android::IBinder>& token,
897 const ::android::security::keymaster::KeymasterArguments& params,
898 const ::std::vector<uint8_t>& input, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700899 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700900 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600901 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700902 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700903
Janis Danisevskisbec89992019-08-14 13:42:19 -0700904 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700905 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600906 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700907 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700908
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600909 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700910 if (!result_.resultCode.isOk()) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700911 mKeyStore->removeOperationDevice(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100912 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600913 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700914 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100915
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600916 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700917}
918
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600919Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
920 const ::android::sp<::android::IBinder>& token,
921 const ::android::security::keymaster::KeymasterArguments& params,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700922 const ::std::vector<uint8_t>& signature,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600923 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700924 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700925 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600926 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700927 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700928
Janis Danisevskisbec89992019-08-14 13:42:19 -0700929 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700930 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600931 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700932 }
933
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700934 dev->finish(token, params.getParameters(), {}, signature, entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600935 [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700936 if (!result_.resultCode.isOk()) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700937 mKeyStore->removeOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700938 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600939 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700940 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700941
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600942 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700943}
944
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600945Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
946 const ::android::sp<::android::IBinder>& token,
947 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700948 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisbec89992019-08-14 13:42:19 -0700949 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700950 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600951 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700952 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100953
Janis Danisevskisbec89992019-08-14 13:42:19 -0700954 dev->abort(token, [this, cb, token](KeyStoreServiceReturnCode rc) {
955 mKeyStore->removeOperationDevice(token);
956 cb->onFinished(rc);
957 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700958
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600959 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700960}
961
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700962Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000963 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700964 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700965
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000966 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
967 // receive a HardwareAuthToken, rather than an opaque byte array.
968
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700969 if (!checkBinderPermission(P_ADD_AUTH)) {
970 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700971 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
972 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700973 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700974 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
Branden Archer70080742018-11-20 11:04:11 -0800975 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700976 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000977 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100978
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000979 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700980 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000981 if (authToken.version != 0) {
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
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700986 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
987 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700988 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
989 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700990}
991
Eran Messerid9f8ae52018-10-24 13:54:00 +0100992bool isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -0700993 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700994 for (size_t i = 0; i < paramsVec.size(); ++i) {
995 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -0600996 case Tag::ATTESTATION_ID_BRAND:
997 case Tag::ATTESTATION_ID_DEVICE:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600998 case Tag::ATTESTATION_ID_MANUFACTURER:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600999 case Tag::ATTESTATION_ID_MODEL:
1000 case Tag::ATTESTATION_ID_PRODUCT:
Rubin Xu1a203e32018-05-08 14:25:21 +01001001 case Tag::ATTESTATION_ID_IMEI:
1002 case Tag::ATTESTATION_ID_MEID:
1003 case Tag::ATTESTATION_ID_SERIAL:
Eran Messerid9f8ae52018-10-24 13:54:00 +01001004 return true;
Rubin Xu1a203e32018-05-08 14:25:21 +01001005 default:
1006 continue;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001007 }
1008 }
Eran Messerid9f8ae52018-10-24 13:54:00 +01001009 return false;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001010}
1011
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001012Status KeyStoreService::attestKey(
1013 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1014 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001015 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001016 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1017 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001018 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001019 }
1020
Eran Messerie2c34152017-12-21 21:01:22 +00001021 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1022
Eran Messerid9f8ae52018-10-24 13:54:00 +01001023 if (isDeviceIdAttestationRequested(params) && (get_app_id(callingUid) != AID_SYSTEM)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001024 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001025 }
1026
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001027 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001028 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1029 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001030 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001031 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001032
Shawn Willden50eb1b22016-01-21 12:41:23 -07001033 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001034 Blob keyBlob;
1035 Blob charBlob;
1036 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001037
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001038 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1039 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1040
Janis Danisevskis9dff56c2019-07-10 14:08:06 -07001041 if (!rc.isOk()) {
1042 return AIDL_RETURN(rc);
1043 }
1044
Janis Danisevskisc1460142017-12-18 16:48:46 -08001045 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001046 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001047 dev->attestKey(
1048 std::move(hidlKey), mutableParams.hidl_data(),
Janis Danisevskisa359c672019-03-14 17:15:06 -07001049 [dev, cb](Return<void> rc,
1050 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001051 auto& [ret, certChain] = hidlResult;
1052 if (!rc.isOk()) {
1053 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1054 } else if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001055 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001056 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1057 } else {
1058 cb->onFinished(KeyStoreServiceReturnCode(ret),
1059 KeymasterCertificateChain(std::move(certChain)));
1060 }
1061 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001062
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001063 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001064}
1065
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001066// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1067// It should never be redefined by a build system though.
1068#ifndef CAPTURE_MOVE
1069#define CAPTURE_MOVE(x) x = std::move(x)
1070#endif
1071
1072Status KeyStoreService::attestDeviceIds(
1073 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1074 const KeymasterArguments& params, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001075 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001076 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001077
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001078 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001079 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001080 }
1081
1082 if (!isDeviceIdAttestationRequested(params)) {
1083 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001084 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001085 }
1086
1087 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1088 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
Yi Konge353f252018-07-30 01:38:39 -07001089 if (binder == nullptr) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001090 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001091 }
1092 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1093 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1094 IPCThreadState::self()->getCallingPid(), callingUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001095 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001096 }
1097
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001098 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001099 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1100 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001101 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001102 }
1103
1104 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001105 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001106
Shawn Willden70c1a782018-07-11 15:13:20 -06001107 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001108 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001109 }
1110
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001111
1112 AuthorizationSet keyCharacteristics;
1113 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1114 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1115 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1116 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1117 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001118
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001119 std::promise<KeyStoreServiceReturnCode> resultPromise;
1120 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001121
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001122 dev->generateKey(
1123 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001124 [cb, dev, CAPTURE_MOVE(mutableParams)](
1125 Return<void> rc,
1126 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001127 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1128 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1129 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001130 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001131 return;
1132 }
1133 if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001134 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001135 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001136 return;
1137 }
1138 dev->attestKey(
1139 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001140 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001141 hidlKeyBlob](Return<void> rc,
1142 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1143 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001144 // schedule temp key for deletion
Janis Danisevskisa359c672019-03-14 17:15:06 -07001145 dev->deleteKey(std::move(hidlKeyBlob), [dev](Return<ErrorCode> rc) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001146 // log error but don't return an error
Janis Danisevskisa359c672019-03-14 17:15:06 -07001147 KS_HANDLE_HIDL_ERROR(dev, rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001148 });
1149 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001150 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001151 return;
1152 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001153 if (ret == ErrorCode::OK) {
1154 cb->onFinished(
1155 KeyStoreServiceReturnCode(ret),
1156 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1157 } else {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001158 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001159 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001160 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001161 });
1162 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001163
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001164 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001165}
1166
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001167Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001168 KEYSTORE_SERVICE_LOCK;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001169 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001170 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001171 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1172 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001173}
1174
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001175Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001176 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001177 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1178 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1179 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001180 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001181 KEYSTORE_SERVICE_LOCK;
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001182
1183 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1184
1185 if (!checkBinderPermission(P_INSERT, callingUid)) {
1186 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1187 }
1188
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001189 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001190
1191 KeyStoreServiceReturnCode rc;
1192 Blob wrappingKeyBlob;
1193 Blob wrappingCharBlob;
1194 LockedKeyBlobEntry wrappingLockedEntry;
1195
1196 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1197 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
Branden Archerd166a882018-11-20 10:56:48 -08001198 if (!rc.isOk()) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001199 return AIDL_RETURN(rc);
1200 }
1201
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001202 String8 wrappedKeyName8(wrappedKeyAlias);
1203 auto wrappedLockedEntry =
1204 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1205 if (!wrappedLockedEntry) {
1206 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1207 }
1208
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001209 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1210 auto dev = mKeyStore->getDevice(securityLevel);
1211 if (!dev) {
1212 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1213 }
1214
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001215 dev->importWrappedKey(
1216 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1217 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001218 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1219 cb->onFinished(rc,
1220 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001221 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001222
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001223 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001224}
1225
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001226Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1227 const String16& promptText,
1228 const ::std::vector<uint8_t>& extraData,
1229 const String16& locale, int32_t uiOptionsAsFlags,
1230 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001231 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001232 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1233 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001234}
1235
1236Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1237 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001238 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001239 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001240}
1241
David Zeuthen1a492312018-02-26 11:00:30 -05001242Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001243 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001244 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001245}
1246
1247/**
1248 * Get the effective target uid for a binder operation that takes an
1249 * optional uid as the target.
1250 */
1251uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1252 if (targetUid == UID_SELF) {
1253 return IPCThreadState::self()->getCallingUid();
1254 }
1255 return static_cast<uid_t>(targetUid);
1256}
1257
1258/**
1259 * Check if the caller of the current binder method has the required
1260 * permission and if acting on other uids the grants to do so.
1261 */
1262bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1263 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1264 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001265 const char* ssid = IPCThreadState::self()->getCallingSid();
1266 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001267 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1268 return false;
1269 }
1270 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1271 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1272 return false;
1273 }
1274 return true;
1275}
1276
1277/**
1278 * Check if the caller of the current binder method has the required
1279 * permission and the target uid is the caller or the caller is system.
1280 */
1281bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1282 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1283 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001284 const char* ssid = IPCThreadState::self()->getCallingSid();
1285 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001286 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1287 return false;
1288 }
1289 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1290}
1291
1292/**
1293 * Check if the caller of the current binder method has the required
1294 * permission or the target of the operation is the caller's uid. This is
1295 * for operation where the permission is only for cross-uid activity and all
1296 * uids are allowed to act on their own (ie: clearing all entries for a
1297 * given uid).
1298 */
1299bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1300 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1301 if (getEffectiveUid(targetUid) == callingUid) {
1302 return true;
1303 } else {
1304 return checkBinderPermission(permission, targetUid);
1305 }
1306}
1307
1308/**
1309 * Helper method to check that the caller has the required permission as
1310 * well as the keystore is in the unlocked state if checkUnlocked is true.
1311 *
1312 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1313 * otherwise the state of keystore when not unlocked and checkUnlocked is
1314 * true.
1315 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001316KeyStoreServiceReturnCode
1317KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1318 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001319 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001320 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001321 }
1322 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1323 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001324 // All State values coincide with ResponseCodes
1325 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001326 }
1327
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001328 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001329}
1330
1331bool KeyStoreService::isKeystoreUnlocked(State state) {
1332 switch (state) {
1333 case ::STATE_NO_ERROR:
1334 return true;
1335 case ::STATE_UNINITIALIZED:
1336 case ::STATE_LOCKED:
1337 return false;
1338 }
1339 return false;
1340}
1341
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001342/**
Shawn Willden0329a822017-12-04 13:55:14 -07001343 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1344 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001345 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001346bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1347 for (size_t i = 0; i < params.size(); ++i) {
1348 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001349 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001350 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001351 return false;
1352 default:
1353 break;
1354 }
1355 }
1356 return true;
1357}
1358
Brian Young9a947d52018-02-23 18:03:14 +00001359Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
1360 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001361 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001362 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Brian Young9a947d52018-02-23 18:03:14 +00001363 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001364
1365 return Status::ok();
1366}
1367
Shawn Willdene2a7b522017-04-11 09:27:40 -06001368} // namespace keystore