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