blob: ba8a3f3e95960c47c12acd3d855e6fe8eed09024 [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");
121 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
122 }
123 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
124
125 /*
Eran Messeri03fc4c82018-08-16 18:53:15 +0100126 * The attestation application ID must not be longer than
127 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, error out if gather_attestation_application_id
128 * returned such an invalid vector.
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200129 */
130 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Eran Messeri03fc4c82018-08-16 18:53:15 +0100131 ALOGE("BUG: Gathered Attestation Application ID is too big (%d)",
132 static_cast<int32_t>(asn1_attestation_id.size()));
133 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200134 }
135
136 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
137
138 return ResponseCode::NO_ERROR;
139}
140
Shawn Willdene2a7b522017-04-11 09:27:40 -0600141} // anonymous namespace
142
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700143Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700144 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700145 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700146 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
147 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700148 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700149 *aidl_return = mKeyStore->getState(userId);
150 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700151}
152
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700153Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700154 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700155 uid_t targetUid = getEffectiveUid(uid);
156 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700157 // see keystore/keystore.h
158 return Status::fromServiceSpecificError(
159 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700160 }
161
162 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700163 ResponseCode rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700164 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700165 Blob charBlob;
166 LockedKeyBlobEntry lockedEntry;
167
168 std::tie(rc, keyBlob, charBlob, lockedEntry) =
169 mKeyStore->getKeyForName(name8, targetUid, TYPE_GENERIC);
170 if (rc != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700171 *item = ::std::vector<uint8_t>();
172 // Return empty array if key is not found
173 // TODO: consider having returned value nullable or parse exception on the client.
174 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700175 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100176 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700177 // The static_cast here is needed to prevent a move, forcing a deep copy.
178 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
179 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700180}
181
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700182Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
183 int targetUid, int32_t flags, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700184 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700185 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700186 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700187 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100188 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800189 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700190 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700191 }
192
193 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700194 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), targetUid);
195
196 if (!lockedEntry) {
197 ALOGE("failed to grab lock on blob entry %u_%s", targetUid, name8.string());
198 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_ALREADY_EXISTS);
199 return Status::ok();
200 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700201
Yi Konge353f252018-07-30 01:38:39 -0700202 Blob keyBlob(&item[0], item.size(), nullptr, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700203 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
204
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700205 *aidl_return = static_cast<int32_t>(mKeyStore->put(lockedEntry, keyBlob, {}));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700206 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700207}
208
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700209Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700210 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700211 targetUid = getEffectiveUid(targetUid);
212 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700213 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
214 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700215 }
216 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000217 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700218 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
219 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700220 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
221 return Status::ok();
222 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700223
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700224 ResponseCode result = mKeyStore->del(lockedEntry);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400225
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700226 *aidl_return = static_cast<int32_t>(result);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700227 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700228}
229
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700230Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700231 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700232 targetUid = getEffectiveUid(targetUid);
233 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700234 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
235 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700236 }
237
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700238 LockedKeyBlobEntry lockedEntry =
239 mKeyStore->getLockedBlobEntryIfExists(String8(name).string(), targetUid);
240 *aidl_return =
241 static_cast<int32_t>(lockedEntry ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700242 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700243}
244
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700245Status KeyStoreService::list(const String16& prefix, int32_t targetUid,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700246 ::std::vector<::android::String16>* matches) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700247 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700248 targetUid = getEffectiveUid(targetUid);
249 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700250 return Status::fromServiceSpecificError(
251 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700252 }
253 const String8 prefix8(prefix);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700254 const std::string stdPrefix(prefix8.string());
255
256 ResponseCode rc;
257 std::list<LockedKeyBlobEntry> internal_matches;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800258 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700259
Janis Danisevskis265435f2018-11-16 14:10:46 -0800260 std::tie(rc, internal_matches) =
261 LockedKeyBlobEntry::list(userDirName, [&](uid_t uid, const std::string& alias) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700262 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end());
263 return uid == static_cast<uid_t>(targetUid) &&
264 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end())
265 .first == stdPrefix.end();
266 });
267
268 if (rc != ResponseCode::NO_ERROR) {
269 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700270 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700271
272 for (LockedKeyBlobEntry& entry : internal_matches) {
273 matches->push_back(String16(entry->alias().substr(prefix8.size()).c_str()));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700274 }
275 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700276}
277
Rob Barneseb7f79b2018-11-08 15:44:10 -0700278/*
279 * This method will return the uids of all auth bound keys for the calling user.
280 * This is intended to be used for alerting the user about which apps will be affected
281 * if the password/pin is removed. Only allowed to be called by system.
282 * The output is bound by the initial size of uidsOut to be compatible with Java.
283 */
Rob Barnes5d59e632018-12-07 16:09:02 -0700284Status KeyStoreService::listUidsOfAuthBoundKeys(std::vector<std::string>* uidsOut,
Rob Barneseb7f79b2018-11-08 15:44:10 -0700285 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700286 KEYSTORE_SERVICE_LOCK;
Rob Barneseb7f79b2018-11-08 15:44:10 -0700287 const int32_t callingUid = IPCThreadState::self()->getCallingUid();
288 const int32_t userId = get_user_id(callingUid);
289 const int32_t appId = get_app_id(callingUid);
290 if (appId != AID_SYSTEM) {
291 ALOGE("Permission listUidsOfAuthBoundKeys denied for aid %d", appId);
292 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
293 return Status::ok();
294 }
295
296 const String8 prefix8("");
297 auto userState = mKeyStore->getUserStateDB().getUserState(userId);
298 const std::string userDirName = userState->getUserDirName();
299 auto encryptionKey = userState->getEncryptionKey();
300 auto state = userState->getState();
301 // unlock the user state
302 userState = {};
303
304 ResponseCode rc;
305 std::list<LockedKeyBlobEntry> internal_matches;
306 std::tie(rc, internal_matches) =
307 LockedKeyBlobEntry::list(userDirName, [&](uid_t, const std::string&) {
308 // Need to filter on auth bound state, so just return true.
309 return true;
310 });
311 if (rc != ResponseCode::NO_ERROR) {
312 ALOGE("Error listing blob entries for user %d", userId);
313 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
314 }
315
Rob Barneseb7f79b2018-11-08 15:44:10 -0700316 for (LockedKeyBlobEntry& entry : internal_matches) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700317 // Need to store uids as a list of strings because integer list output
318 // parameters is not supported in aidl-cpp.
319 std::string entryUid = std::to_string(entry->uid());
320 if (std::find(uidsOut->begin(), uidsOut->end(), entryUid) != uidsOut->end()) {
Rob Barneseb7f79b2018-11-08 15:44:10 -0700321 // uid already in list, skip
322 continue;
323 }
324
325 auto [rc, blob, charBlob] = entry.readBlobs(encryptionKey, state);
326 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::LOCKED) {
327 ALOGE("Error reading blob for key %s", entry->alias().c_str());
328 continue;
329 }
330
331 if (blob && blob.isEncrypted()) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700332 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700333 } else if (charBlob) {
334 auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
335 if (!success) {
336 ALOGE("Error reading blob characteristics for key %s", entry->alias().c_str());
337 continue;
338 }
339 if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
340 swEnforced.Contains(TAG_USER_SECURE_ID)) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700341 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700342 }
343 }
344 }
345 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
346 return Status::ok();
347}
348
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700349Status KeyStoreService::reset(int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700350 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700351 if (!checkBinderPermission(P_RESET)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700352 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
353 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700354 }
355
356 uid_t callingUid = IPCThreadState::self()->getCallingUid();
357 mKeyStore->resetUser(get_user_id(callingUid), false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700358 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
359 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700360}
361
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700362Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
363 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700364 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700365 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700366 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
367 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700368 }
369
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700370 if (password.size() == 0) {
371 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
372 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700373 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
374 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700375 } else {
Pavel Grafovf9b53eb2019-02-06 17:16:21 +0000376 const String8 password8(password);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700377 switch (mKeyStore->getState(userId)) {
378 case ::STATE_UNINITIALIZED: {
379 // generate master key, encrypt with password, write to file,
380 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700381 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
382 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700383 }
384 case ::STATE_NO_ERROR: {
385 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700386 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
387 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700388 }
389 case ::STATE_LOCKED: {
390 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
391 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700392 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
393 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700394 }
395 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700396 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
397 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700398 }
399}
400
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700401Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700402 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700403 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700404 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
405 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700406 }
407
408 // Sanity check that the new user has an empty keystore.
409 if (!mKeyStore->isEmpty(userId)) {
410 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
411 }
412 // Unconditionally clear the keystore, just to be safe.
413 mKeyStore->resetUser(userId, false);
414 if (parentId != -1) {
415 // This profile must share the same master key password as the parent profile. Because the
416 // password of the parent profile is not known here, the best we can do is copy the parent's
417 // master key and master key file. This makes this profile use the same master key as the
418 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700419 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
420 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700421 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700422 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
423 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700424 }
425}
426
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700427Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700428 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700429 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700430 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
431 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700432 }
433
434 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700435 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
436 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700437}
438
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700439Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700440 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700441 if (!checkBinderPermission(P_LOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700442 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
443 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700444 }
445
446 State state = mKeyStore->getState(userId);
447 if (state != ::STATE_NO_ERROR) {
448 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700449 *aidl_return = static_cast<int32_t>(ResponseCode(state));
450 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700451 }
452
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700453 mKeyStore->getEnforcementPolicy().set_device_locked(true, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700454 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700455 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
456 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700457}
458
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700459Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700460 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700461 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700462 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
463 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700464 }
465
466 State state = mKeyStore->getState(userId);
467 if (state != ::STATE_LOCKED) {
468 switch (state) {
469 case ::STATE_NO_ERROR:
470 ALOGI("calling unlock when already unlocked, ignoring.");
471 break;
472 case ::STATE_UNINITIALIZED:
473 ALOGE("unlock called on uninitialized keystore.");
474 break;
475 default:
476 ALOGE("unlock called on keystore in unknown state: %d", state);
477 break;
478 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700479 *aidl_return = static_cast<int32_t>(ResponseCode(state));
480 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700481 }
482
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700483 mKeyStore->getEnforcementPolicy().set_device_locked(false, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700484 const String8 password8(pw);
485 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700486 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
487 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700488}
489
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700490Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700491 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700492 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700493 *aidl_return = static_cast<int32_t>(false);
494 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700495 }
496
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700497 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
498 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700499}
500
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700501Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
502 ::android::String16* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700503 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700504 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700505 auto result =
506 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100507 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700508 *aidl_return = String16();
509 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700510 }
511
512 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700513 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
514 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700515 *aidl_return = String16();
516 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700517 }
518
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700519 *aidl_return = String16(mKeyStore->addGrant(lockedEntry, granteeUid).c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700520 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700521}
522
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700523Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700524 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700525 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700526 KeyStoreServiceReturnCode result =
527 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100528 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800529 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700530 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700531 }
532
533 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700534
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700535 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
536 if (!lockedEntry) {
537 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700538 }
539
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700540 *aidl_return = mKeyStore->removeGrant(lockedEntry, granteeUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700541 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700542}
543
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700544Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700545 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700546 uid_t targetUid = getEffectiveUid(uid);
547 if (!checkBinderPermission(P_GET, targetUid)) {
548 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700549 *time = -1L;
550 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700551 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700552 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700553
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700554 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
555 if (!lockedEntry) {
556 ALOGW("could not access key with alias %s for getmtime", name8.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700557 *time = -1L;
558 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700559 }
560
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700561 std::string filename = lockedEntry->getKeyBlobPath();
562
563 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700564 if (fd < 0) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700565 ALOGW("could not open %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700566 *time = -1L;
567 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700568 }
569
570 struct stat s;
571 int ret = fstat(fd, &s);
572 close(fd);
573 if (ret == -1) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700574 ALOGW("could not stat %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700575 *time = -1L;
576 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700577 }
578
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700579 *time = static_cast<int64_t>(s.st_mtime);
580 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700581}
582
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700583Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700584 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700585 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
586 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700587}
588
Janis Danisevskis265435f2018-11-16 14:10:46 -0800589Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700590 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700591 uid_t targetUid = getEffectiveUid(targetUid64);
592 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800593 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700594 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000595 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700596
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700597 mKeyStore->removeAllGrantsToUid(targetUid);
598
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700599 ResponseCode rc;
600 std::list<LockedKeyBlobEntry> entries;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800601 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700602
603 // list has a fence making sure no workers are modifying blob files before iterating the
604 // data base. All returned entries are locked.
605 std::tie(rc, entries) = LockedKeyBlobEntry::list(
Janis Danisevskis265435f2018-11-16 14:10:46 -0800606 userDirName, [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700607
608 if (rc != ResponseCode::NO_ERROR) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800609 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700610 }
611
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700612 for (LockedKeyBlobEntry& lockedEntry : entries) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100613 if (get_app_id(targetUid) == AID_SYSTEM) {
614 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700615 Blob charBlob;
616 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
617 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100618 // Do not clear keys critical to device encryption under system uid.
619 continue;
620 }
621 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700622 mKeyStore->del(lockedEntry);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700623 }
Janis Danisevskis265435f2018-11-16 14:10:46 -0800624 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700625}
626
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600627Status KeyStoreService::addRngEntropy(
628 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
629 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700630 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisc1460142017-12-18 16:48:46 -0800631 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
632 if (!device) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600633 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800634 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700635
Janis Danisevskisa359c672019-03-14 17:15:06 -0700636 device->addRngEntropy(entropy, [device, cb](Return<ErrorCode> rc) {
637 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device, rc)));
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600638 });
639
640 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700641}
642
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600643Status KeyStoreService::generateKey(
644 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
645 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
646 int uid, int flags, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700647 KEYSTORE_SERVICE_LOCK;
Max Biresef4f0672017-11-29 14:38:48 -0800648 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
649 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700650 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000651 auto logOnScopeExit = android::base::make_scope_guard([&] {
652 if (__android_log_security()) {
653 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600654 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000655 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
656 }
657 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100658 KeyStoreServiceReturnCode rc =
659 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
660 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600661 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700662 }
Rubin Xu67899de2017-04-21 19:15:13 +0100663 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
664 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600665 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100666 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700667
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700668 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700669 // TODO(jbires): remove uid checking upon implementation of b/25646100
Max Bires670467d2017-12-12 11:16:43 -0800670 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Biresef4f0672017-11-29 14:38:48 -0800671 originalUid != IPCThreadState::self()->getCallingUid()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600672 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700673 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600674 }
675
Janis Danisevskisc1460142017-12-18 16:48:46 -0800676 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
677 auto dev = mKeyStore->getDevice(securityLevel);
678 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600679 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800680 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400681
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100682 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700683 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
684 if (!lockedEntry) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600685 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100686 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400687
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700688 logOnScopeExit.Disable();
689
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600690 dev->generateKey(
691 std::move(lockedEntry), params.getParameters(), entropy, flags,
692 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
693 if (__android_log_security()) {
694 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
695 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
696 }
697 cb->onFinished(rc,
698 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
699 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700700
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600701 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700702}
703
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700704Status KeyStoreService::getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600705 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700706 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
Janis Danisevskis64ec1fe2018-02-26 16:47:21 -0800707 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600708 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700709 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700710
711 uid_t targetUid = getEffectiveUid(uid);
712 uid_t callingUid = IPCThreadState::self()->getCallingUid();
713 if (!is_granted_to(callingUid, targetUid)) {
714 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
715 targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600716 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700717 }
718
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700719 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700720
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700721 ResponseCode rc;
722 Blob keyBlob;
723 Blob charBlob;
724 LockedKeyBlobEntry lockedEntry;
Janis Danisevskisd714a672017-09-01 14:31:36 -0700725
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700726 std::tie(rc, keyBlob, charBlob, lockedEntry) =
727 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
728
729 if (rc != ResponseCode::NO_ERROR) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600730 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700731 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100732
Janis Danisevskisc1460142017-12-18 16:48:46 -0800733 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700734 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600735 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100736 }
737
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700738 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
739 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
740 // from keymaster. It may also upgrade the key blob.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700741 dev->getKeyCharacteristics(
742 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
743 std::move(charBlob),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600744 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
745 cb->onFinished(rc,
746 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700747 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100748
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600749 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700750}
751
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600752Status KeyStoreService::importKey(
753 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
754 const String16& name, const KeymasterArguments& params, int32_t format,
755 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700756 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700757 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000758 auto logOnScopeExit = android::base::make_scope_guard([&] {
759 if (__android_log_security()) {
760 android_log_event_list(SEC_TAG_KEY_IMPORTED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600761 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000762 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
763 }
764 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100765 KeyStoreServiceReturnCode rc =
766 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
767 if (!rc.isOk()) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700768 LOG(ERROR) << "permissission denied";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600769 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700770 }
Rubin Xu67899de2017-04-21 19:15:13 +0100771 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
772 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600773 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100774 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700775
Janis Danisevskisc1460142017-12-18 16:48:46 -0800776 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
777 auto dev = mKeyStore->getDevice(securityLevel);
778 if (!dev) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700779 LOG(ERROR) << "importKey - cound not get keymaster device";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600780 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800781 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700782
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700783 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700784 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
785 if (!lockedEntry) {
786 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
787 << " already exists.";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600788 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400789 }
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700790
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700791 logOnScopeExit.Disable();
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700792
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600793 dev->importKey(
794 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
795 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
796 if (__android_log_security()) {
797 android_log_event_list(SEC_TAG_KEY_IMPORTED)
798 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
799 }
800 cb->onFinished(rc,
801 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
802 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400803
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600804 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700805}
806
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600807Status KeyStoreService::exportKey(
808 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
809 const String16& name, int32_t format,
810 const ::android::security::keymaster::KeymasterBlob& clientId,
811 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
812 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700813 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700814
815 uid_t targetUid = getEffectiveUid(uid);
816 uid_t callingUid = IPCThreadState::self()->getCallingUid();
817 if (!is_granted_to(callingUid, targetUid)) {
818 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600819 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700820 }
821
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700822 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700823
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700824 KeyStoreServiceReturnCode rc;
825 Blob keyBlob;
826 Blob charBlob;
827 LockedKeyBlobEntry lockedEntry;
828
829 std::tie(rc, keyBlob, charBlob, lockedEntry) =
830 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskis3cf85322018-11-19 13:37:49 -0800831 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600832 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700833 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100834
Janis Danisevskisc1460142017-12-18 16:48:46 -0800835 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100836
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700837 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600838 std::move(keyBlob), std::move(charBlob),
839 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
Ji Wang2c142312016-10-14 17:21:10 +0800840
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600841 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700842}
843
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600844Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
845 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700846 bool pruneable, const KeymasterArguments& params,
847 const ::std::vector<uint8_t>& entropy, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600848 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700849 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700850 uid_t callingUid = IPCThreadState::self()->getCallingUid();
851 uid_t targetUid = getEffectiveUid(uid);
852 if (!is_granted_to(callingUid, targetUid)) {
853 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600854 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700855 }
856 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
857 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600858 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700859 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700860 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600861 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700862 }
Shawn Willden0329a822017-12-04 13:55:14 -0700863
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700864 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700865 Blob keyBlob;
866 Blob charBlob;
867 LockedKeyBlobEntry lockedEntry;
868 ResponseCode rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100869
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700870 std::tie(rc, keyBlob, charBlob, lockedEntry) =
871 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
872
873 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600874 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700875 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600876 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700877
Janis Danisevskisc1460142017-12-18 16:48:46 -0800878 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700879 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100880
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700881 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
882 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600883 [this, cb, dev](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700884 if (result_.resultCode.isOk() ||
885 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
886 addOperationDevice(result_.token, dev);
887 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600888 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700889 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400890
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600891 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700892}
893
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600894Status KeyStoreService::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
895 const ::android::sp<::android::IBinder>& token,
896 const ::android::security::keymaster::KeymasterArguments& params,
897 const ::std::vector<uint8_t>& input, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700898 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700899 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600900 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700901 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700902
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700903 auto dev = getOperationDevice(token);
904 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600905 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700906 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700907
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600908 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700909 if (!result_.resultCode.isOk()) {
910 removeOperationDevice(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100911 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600912 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700913 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100914
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600915 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700916}
917
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600918Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
919 const ::android::sp<::android::IBinder>& token,
920 const ::android::security::keymaster::KeymasterArguments& params,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700921 const ::std::vector<uint8_t>& signature,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600922 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700923 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700924 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600925 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700926 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700927
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700928 auto dev = getOperationDevice(token);
929 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600930 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700931 }
932
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700933 dev->finish(token, params.getParameters(), {}, signature, entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600934 [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700935 if (!result_.resultCode.isOk()) {
936 removeOperationDevice(token);
937 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600938 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700939 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700940
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600941 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700942}
943
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600944Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
945 const ::android::sp<::android::IBinder>& token,
946 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700947 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700948 auto dev = getOperationDevice(token);
949 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600950 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700951 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100952
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600953 dev->abort(token, [cb](KeyStoreServiceReturnCode rc) { cb->onFinished(rc); });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700954
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600955 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700956}
957
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700958Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000959 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700960 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700961
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000962 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
963 // receive a HardwareAuthToken, rather than an opaque byte array.
964
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700965 if (!checkBinderPermission(P_ADD_AUTH)) {
966 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700967 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
968 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700969 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700970 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
Branden Archer70080742018-11-20 11:04:11 -0800971 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700972 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000973 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100974
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000975 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700976 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000977 if (authToken.version != 0) {
Branden Archer70080742018-11-20 11:04:11 -0800978 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700979 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000980 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100981
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700982 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
983 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700984 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
985 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700986}
987
Eran Messerid9f8ae52018-10-24 13:54:00 +0100988bool isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -0700989 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700990 for (size_t i = 0; i < paramsVec.size(); ++i) {
991 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -0600992 case Tag::ATTESTATION_ID_BRAND:
993 case Tag::ATTESTATION_ID_DEVICE:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600994 case Tag::ATTESTATION_ID_MANUFACTURER:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600995 case Tag::ATTESTATION_ID_MODEL:
996 case Tag::ATTESTATION_ID_PRODUCT:
Rubin Xu1a203e32018-05-08 14:25:21 +0100997 case Tag::ATTESTATION_ID_IMEI:
998 case Tag::ATTESTATION_ID_MEID:
999 case Tag::ATTESTATION_ID_SERIAL:
Eran Messerid9f8ae52018-10-24 13:54:00 +01001000 return true;
Rubin Xu1a203e32018-05-08 14:25:21 +01001001 default:
1002 continue;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001003 }
1004 }
Eran Messerid9f8ae52018-10-24 13:54:00 +01001005 return false;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001006}
1007
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001008Status KeyStoreService::attestKey(
1009 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1010 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001011 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001012 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1013 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001014 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001015 }
1016
Eran Messerie2c34152017-12-21 21:01:22 +00001017 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1018
Eran Messerid9f8ae52018-10-24 13:54:00 +01001019 if (isDeviceIdAttestationRequested(params) && (get_app_id(callingUid) != AID_SYSTEM)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001020 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001021 }
1022
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001023 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001024 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1025 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001026 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001027 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001028
Shawn Willden50eb1b22016-01-21 12:41:23 -07001029 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001030 Blob keyBlob;
1031 Blob charBlob;
1032 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001033
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001034 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1035 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1036
Janis Danisevskis9dff56c2019-07-10 14:08:06 -07001037 if (!rc.isOk()) {
1038 return AIDL_RETURN(rc);
1039 }
1040
Janis Danisevskisc1460142017-12-18 16:48:46 -08001041 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001042 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001043 dev->attestKey(
1044 std::move(hidlKey), mutableParams.hidl_data(),
Janis Danisevskisa359c672019-03-14 17:15:06 -07001045 [dev, cb](Return<void> rc,
1046 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001047 auto& [ret, certChain] = hidlResult;
1048 if (!rc.isOk()) {
1049 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1050 } else if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001051 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001052 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1053 } else {
1054 cb->onFinished(KeyStoreServiceReturnCode(ret),
1055 KeymasterCertificateChain(std::move(certChain)));
1056 }
1057 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001058
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001059 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001060}
1061
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001062// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1063// It should never be redefined by a build system though.
1064#ifndef CAPTURE_MOVE
1065#define CAPTURE_MOVE(x) x = std::move(x)
1066#endif
1067
1068Status KeyStoreService::attestDeviceIds(
1069 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1070 const KeymasterArguments& params, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001071 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001072 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001073
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001074 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001075 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001076 }
1077
1078 if (!isDeviceIdAttestationRequested(params)) {
1079 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001080 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001081 }
1082
1083 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1084 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
Yi Konge353f252018-07-30 01:38:39 -07001085 if (binder == nullptr) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001086 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001087 }
1088 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1089 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1090 IPCThreadState::self()->getCallingPid(), callingUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001091 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001092 }
1093
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001094 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001095 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1096 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001097 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001098 }
1099
1100 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001101 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001102
Shawn Willden70c1a782018-07-11 15:13:20 -06001103 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001104 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001105 }
1106
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001107
1108 AuthorizationSet keyCharacteristics;
1109 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1110 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1111 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1112 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1113 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001114
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001115 std::promise<KeyStoreServiceReturnCode> resultPromise;
1116 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001117
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001118 dev->generateKey(
1119 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001120 [cb, dev, CAPTURE_MOVE(mutableParams)](
1121 Return<void> rc,
1122 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001123 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1124 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1125 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001126 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001127 return;
1128 }
1129 if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001130 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001131 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001132 return;
1133 }
1134 dev->attestKey(
1135 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001136 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001137 hidlKeyBlob](Return<void> rc,
1138 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1139 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001140 // schedule temp key for deletion
Janis Danisevskisa359c672019-03-14 17:15:06 -07001141 dev->deleteKey(std::move(hidlKeyBlob), [dev](Return<ErrorCode> rc) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001142 // log error but don't return an error
Janis Danisevskisa359c672019-03-14 17:15:06 -07001143 KS_HANDLE_HIDL_ERROR(dev, rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001144 });
1145 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001146 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001147 return;
1148 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001149 if (ret == ErrorCode::OK) {
1150 cb->onFinished(
1151 KeyStoreServiceReturnCode(ret),
1152 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1153 } else {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001154 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001155 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001156 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001157 });
1158 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001159
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001160 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001161}
1162
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001163Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001164 KEYSTORE_SERVICE_LOCK;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001165 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001166 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001167 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1168 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001169}
1170
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001171Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001172 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001173 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1174 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1175 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001176 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001177 KEYSTORE_SERVICE_LOCK;
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001178
1179 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1180
1181 if (!checkBinderPermission(P_INSERT, callingUid)) {
1182 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1183 }
1184
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001185 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001186
1187 KeyStoreServiceReturnCode rc;
1188 Blob wrappingKeyBlob;
1189 Blob wrappingCharBlob;
1190 LockedKeyBlobEntry wrappingLockedEntry;
1191
1192 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1193 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
Branden Archerd166a882018-11-20 10:56:48 -08001194 if (!rc.isOk()) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001195 return AIDL_RETURN(rc);
1196 }
1197
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001198 String8 wrappedKeyName8(wrappedKeyAlias);
1199 auto wrappedLockedEntry =
1200 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1201 if (!wrappedLockedEntry) {
1202 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1203 }
1204
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001205 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1206 auto dev = mKeyStore->getDevice(securityLevel);
1207 if (!dev) {
1208 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1209 }
1210
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001211 dev->importWrappedKey(
1212 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1213 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001214 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1215 cb->onFinished(rc,
1216 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001217 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001218
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001219 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001220}
1221
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001222Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1223 const String16& promptText,
1224 const ::std::vector<uint8_t>& extraData,
1225 const String16& locale, int32_t uiOptionsAsFlags,
1226 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001227 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001228 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1229 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001230}
1231
1232Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1233 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001234 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001235 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001236}
1237
David Zeuthen1a492312018-02-26 11:00:30 -05001238Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001239 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001240 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001241}
1242
1243/**
1244 * Get the effective target uid for a binder operation that takes an
1245 * optional uid as the target.
1246 */
1247uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1248 if (targetUid == UID_SELF) {
1249 return IPCThreadState::self()->getCallingUid();
1250 }
1251 return static_cast<uid_t>(targetUid);
1252}
1253
1254/**
1255 * Check if the caller of the current binder method has the required
1256 * permission and if acting on other uids the grants to do so.
1257 */
1258bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1259 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1260 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001261 const char* ssid = IPCThreadState::self()->getCallingSid();
1262 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001263 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1264 return false;
1265 }
1266 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1267 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1268 return false;
1269 }
1270 return true;
1271}
1272
1273/**
1274 * Check if the caller of the current binder method has the required
1275 * permission and the target uid is the caller or the caller is system.
1276 */
1277bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1278 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1279 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001280 const char* ssid = IPCThreadState::self()->getCallingSid();
1281 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001282 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1283 return false;
1284 }
1285 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1286}
1287
1288/**
1289 * Check if the caller of the current binder method has the required
1290 * permission or the target of the operation is the caller's uid. This is
1291 * for operation where the permission is only for cross-uid activity and all
1292 * uids are allowed to act on their own (ie: clearing all entries for a
1293 * given uid).
1294 */
1295bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1296 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1297 if (getEffectiveUid(targetUid) == callingUid) {
1298 return true;
1299 } else {
1300 return checkBinderPermission(permission, targetUid);
1301 }
1302}
1303
1304/**
1305 * Helper method to check that the caller has the required permission as
1306 * well as the keystore is in the unlocked state if checkUnlocked is true.
1307 *
1308 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1309 * otherwise the state of keystore when not unlocked and checkUnlocked is
1310 * true.
1311 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001312KeyStoreServiceReturnCode
1313KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1314 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001315 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001316 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001317 }
1318 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1319 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001320 // All State values coincide with ResponseCodes
1321 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001322 }
1323
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001324 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001325}
1326
1327bool KeyStoreService::isKeystoreUnlocked(State state) {
1328 switch (state) {
1329 case ::STATE_NO_ERROR:
1330 return true;
1331 case ::STATE_UNINITIALIZED:
1332 case ::STATE_LOCKED:
1333 return false;
1334 }
1335 return false;
1336}
1337
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001338/**
Shawn Willden0329a822017-12-04 13:55:14 -07001339 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1340 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001341 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001342bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1343 for (size_t i = 0; i < params.size(); ++i) {
1344 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001345 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001346 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001347 return false;
1348 default:
1349 break;
1350 }
1351 }
1352 return true;
1353}
1354
Brian Young9a947d52018-02-23 18:03:14 +00001355Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
1356 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001357 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001358 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Brian Young9a947d52018-02-23 18:03:14 +00001359 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001360
1361 return Status::ok();
1362}
1363
Shawn Willdene2a7b522017-04-11 09:27:40 -06001364} // namespace keystore