blob: 0bd3e03ae584fb26d61f5fa4ac4023f6f11f8ae6 [file] [log] [blame]
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Janis Danisevskis011675d2016-09-01 11:41:29 +010017#define LOG_TAG "keystore"
18
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070019#include "key_store_service.h"
20
21#include <fcntl.h>
22#include <sys/stat.h>
23
Janis Danisevskis7612fd42016-09-01 11:50:02 +010024#include <algorithm>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070025#include <atomic>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070026#include <sstream>
27
Pavel Grafovff311b42018-01-24 20:34:37 +000028#include <android-base/scopeguard.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010029#include <binder/IInterface.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070030#include <binder/IPCThreadState.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010031#include <binder/IPermissionController.h>
32#include <binder/IServiceManager.h>
Brian Claire Young3133c452018-08-31 13:56:49 -070033#include <cutils/multiuser.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000034#include <log/log_event_list.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070035
36#include <private/android_filesystem_config.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000037#include <private/android_logger.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070038
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070039#include <android/hardware/confirmationui/1.0/IConfirmationUI.h>
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010040#include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070041
42#include "defaults.h"
Max Bires33aac2d2018-02-23 10:53:10 -080043#include "key_proto_handler.h"
Janis Danisevskis18f27ad2016-06-01 13:57:40 -070044#include "keystore_attestation_id.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010045#include "keystore_keymaster_enforcement.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070046#include "keystore_utils.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010047#include <keystore/keystore_hidl_support.h>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070048#include <keystore/keystore_return_types.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070049
Janis Danisevskis8f737ad2017-11-21 12:30:15 -080050#include <hardware/hw_auth_token.h>
51
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010052namespace keystore {
Shawn Willdend5a24e62017-02-28 13:53:24 -070053
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010054using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070055
Shawn Willdene2a7b522017-04-11 09:27:40 -060056namespace {
57
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070058using ::android::binder::Status;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070059using android::security::keymaster::ExportResult;
60using android::security::keymaster::KeymasterArguments;
61using android::security::keymaster::KeymasterBlob;
62using android::security::keymaster::KeymasterCertificateChain;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070063using android::security::keymaster::operationFailed;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070064using android::security::keymaster::OperationResult;
David Zeuthenc6eb7cd2017-11-27 11:33:55 -050065using ConfirmationResponseCode = android::hardware::confirmationui::V1_0::ResponseCode;
Rob Barnesbb6cabd2018-10-04 17:10:37 -060066using ::android::security::keystore::IKeystoreOperationResultCallback;
67using ::android::security::keystore::IKeystoreResponseCallback;
68using ::android::security::keystore::KeystoreResponse;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070069
Shawn Willdene2a7b522017-04-11 09:27:40 -060070constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
71const char* kTimestampFilePath = "timestamp";
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070072
73struct BIGNUM_Delete {
74 void operator()(BIGNUM* p) const { BN_free(p); }
75};
Janis Danisevskisccfff102017-05-01 11:02:51 -070076typedef std::unique_ptr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070077
Shawn Willdene2a7b522017-04-11 09:27:40 -060078bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070079 return params.end() !=
80 std::find_if(params.begin(), params.end(),
81 [&](const KeyParameter& param) { return param.tag == tag; });
Shawn Willdend5a24e62017-02-28 13:53:24 -070082}
83
Branden Archer70080742018-11-20 11:04:11 -080084#define AIDL_RETURN(rc) (*_aidl_return = KeyStoreServiceReturnCode(rc).getErrorCode(), Status::ok())
Rob Barnesbb6cabd2018-10-04 17:10:37 -060085
Shawn Willdene2a7b522017-04-11 09:27:40 -060086std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
87 struct stat sbuf;
88 if (stat(kTimestampFilePath, &sbuf) == 0) {
Yi Konge353f252018-07-30 01:38:39 -070089 double diff_secs = difftime(time(nullptr), sbuf.st_ctime);
Shawn Willdene2a7b522017-04-11 09:27:40 -060090 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
91 }
92
93 if (errno != ENOENT) {
94 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
95 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
96 }
97
98 int fd = creat(kTimestampFilePath, 0600);
99 if (fd < 0) {
100 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
101 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
102 }
103
104 if (close(fd)) {
105 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
106 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
107 }
108
109 return {ResponseCode::NO_ERROR, true};
110}
111
Eran Messeri03fc4c82018-08-16 18:53:15 +0100112using ::android::security::KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200113
114KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
115 KeyStoreServiceReturnCode responseCode;
116 bool factoryResetSinceIdRotation;
117 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
118
119 if (!responseCode.isOk()) return responseCode;
120 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
121
122 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
123 if (!asn1_attestation_id_result.isOk()) {
124 ALOGE("failed to gather attestation_id");
125 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
126 }
127 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
128
129 /*
Eran Messeri03fc4c82018-08-16 18:53:15 +0100130 * The attestation application ID must not be longer than
131 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, error out if gather_attestation_application_id
132 * returned such an invalid vector.
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200133 */
134 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Eran Messeri03fc4c82018-08-16 18:53:15 +0100135 ALOGE("BUG: Gathered Attestation Application ID is too big (%d)",
136 static_cast<int32_t>(asn1_attestation_id.size()));
137 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200138 }
139
140 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
141
142 return ResponseCode::NO_ERROR;
143}
144
Shawn Willdene2a7b522017-04-11 09:27:40 -0600145} // anonymous namespace
146
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700147Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700148 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700149 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
150 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700151 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700152 *aidl_return = mKeyStore->getState(userId);
153 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700154}
155
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700156Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700157 uid_t targetUid = getEffectiveUid(uid);
158 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700159 // see keystore/keystore.h
160 return Status::fromServiceSpecificError(
161 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700162 }
163
164 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700165 ResponseCode rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700166 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700167 Blob charBlob;
168 LockedKeyBlobEntry lockedEntry;
169
170 std::tie(rc, keyBlob, charBlob, lockedEntry) =
171 mKeyStore->getKeyForName(name8, targetUid, TYPE_GENERIC);
172 if (rc != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700173 *item = ::std::vector<uint8_t>();
174 // Return empty array if key is not found
175 // TODO: consider having returned value nullable or parse exception on the client.
176 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700177 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100178 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700179 // The static_cast here is needed to prevent a move, forcing a deep copy.
180 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
181 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700182}
183
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700184Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
185 int targetUid, int32_t flags, int32_t* aidl_return) {
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) {
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) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700231 targetUid = getEffectiveUid(targetUid);
232 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700233 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
234 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700235 }
236
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700237 LockedKeyBlobEntry lockedEntry =
238 mKeyStore->getLockedBlobEntryIfExists(String8(name).string(), targetUid);
239 *aidl_return =
240 static_cast<int32_t>(lockedEntry ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700241 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700242}
243
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700244Status KeyStoreService::list(const String16& prefix, int32_t targetUid,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700245 ::std::vector<::android::String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700246 targetUid = getEffectiveUid(targetUid);
247 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700248 return Status::fromServiceSpecificError(
249 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700250 }
251 const String8 prefix8(prefix);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700252 const std::string stdPrefix(prefix8.string());
253
254 ResponseCode rc;
255 std::list<LockedKeyBlobEntry> internal_matches;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800256 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700257
Janis Danisevskis265435f2018-11-16 14:10:46 -0800258 std::tie(rc, internal_matches) =
259 LockedKeyBlobEntry::list(userDirName, [&](uid_t uid, const std::string& alias) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700260 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end());
261 return uid == static_cast<uid_t>(targetUid) &&
262 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end())
263 .first == stdPrefix.end();
264 });
265
266 if (rc != ResponseCode::NO_ERROR) {
267 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700268 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700269
270 for (LockedKeyBlobEntry& entry : internal_matches) {
271 matches->push_back(String16(entry->alias().substr(prefix8.size()).c_str()));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700272 }
273 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700274}
275
Rob Barneseb7f79b2018-11-08 15:44:10 -0700276/*
277 * This method will return the uids of all auth bound keys for the calling user.
278 * This is intended to be used for alerting the user about which apps will be affected
279 * if the password/pin is removed. Only allowed to be called by system.
280 * The output is bound by the initial size of uidsOut to be compatible with Java.
281 */
Rob Barnes5d59e632018-12-07 16:09:02 -0700282Status KeyStoreService::listUidsOfAuthBoundKeys(std::vector<std::string>* uidsOut,
Rob Barneseb7f79b2018-11-08 15:44:10 -0700283 int32_t* aidl_return) {
284 const int32_t callingUid = IPCThreadState::self()->getCallingUid();
285 const int32_t userId = get_user_id(callingUid);
286 const int32_t appId = get_app_id(callingUid);
287 if (appId != AID_SYSTEM) {
288 ALOGE("Permission listUidsOfAuthBoundKeys denied for aid %d", appId);
289 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
290 return Status::ok();
291 }
292
293 const String8 prefix8("");
294 auto userState = mKeyStore->getUserStateDB().getUserState(userId);
295 const std::string userDirName = userState->getUserDirName();
296 auto encryptionKey = userState->getEncryptionKey();
297 auto state = userState->getState();
298 // unlock the user state
299 userState = {};
300
301 ResponseCode rc;
302 std::list<LockedKeyBlobEntry> internal_matches;
303 std::tie(rc, internal_matches) =
304 LockedKeyBlobEntry::list(userDirName, [&](uid_t, const std::string&) {
305 // Need to filter on auth bound state, so just return true.
306 return true;
307 });
308 if (rc != ResponseCode::NO_ERROR) {
309 ALOGE("Error listing blob entries for user %d", userId);
310 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
311 }
312
Rob Barneseb7f79b2018-11-08 15:44:10 -0700313 for (LockedKeyBlobEntry& entry : internal_matches) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700314 // Need to store uids as a list of strings because integer list output
315 // parameters is not supported in aidl-cpp.
316 std::string entryUid = std::to_string(entry->uid());
317 if (std::find(uidsOut->begin(), uidsOut->end(), entryUid) != uidsOut->end()) {
Rob Barneseb7f79b2018-11-08 15:44:10 -0700318 // uid already in list, skip
319 continue;
320 }
321
322 auto [rc, blob, charBlob] = entry.readBlobs(encryptionKey, state);
323 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::LOCKED) {
324 ALOGE("Error reading blob for key %s", entry->alias().c_str());
325 continue;
326 }
327
328 if (blob && blob.isEncrypted()) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700329 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700330 } else if (charBlob) {
331 auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
332 if (!success) {
333 ALOGE("Error reading blob characteristics for key %s", entry->alias().c_str());
334 continue;
335 }
336 if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
337 swEnforced.Contains(TAG_USER_SECURE_ID)) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700338 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700339 }
340 }
341 }
342 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
343 return Status::ok();
344}
345
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700346Status KeyStoreService::reset(int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700347 if (!checkBinderPermission(P_RESET)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700348 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
349 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700350 }
351
352 uid_t callingUid = IPCThreadState::self()->getCallingUid();
353 mKeyStore->resetUser(get_user_id(callingUid), false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700354 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
355 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700356}
357
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700358Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
359 int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700360 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700361 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
362 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700363 }
364
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700365 if (password.size() == 0) {
366 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
367 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700368 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
369 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700370 } else {
Pavel Grafovf9b53eb2019-02-06 17:16:21 +0000371 const String8 password8(password);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700372 switch (mKeyStore->getState(userId)) {
373 case ::STATE_UNINITIALIZED: {
374 // generate master key, encrypt with password, write to file,
375 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700376 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
377 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700378 }
379 case ::STATE_NO_ERROR: {
380 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700381 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
382 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700383 }
384 case ::STATE_LOCKED: {
385 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
386 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700387 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
388 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700389 }
390 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700391 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
392 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700393 }
394}
395
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700396Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700397 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700398 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
399 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700400 }
401
402 // Sanity check that the new user has an empty keystore.
403 if (!mKeyStore->isEmpty(userId)) {
404 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
405 }
406 // Unconditionally clear the keystore, just to be safe.
407 mKeyStore->resetUser(userId, false);
408 if (parentId != -1) {
409 // This profile must share the same master key password as the parent profile. Because the
410 // password of the parent profile is not known here, the best we can do is copy the parent's
411 // master key and master key file. This makes this profile use the same master key as the
412 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700413 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
414 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700415 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700416 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
417 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700418 }
419}
420
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700421Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700422 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700423 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
424 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700425 }
426
427 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700428 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
429 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700430}
431
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700432Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700433 if (!checkBinderPermission(P_LOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700434 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
435 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700436 }
437
438 State state = mKeyStore->getState(userId);
439 if (state != ::STATE_NO_ERROR) {
440 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700441 *aidl_return = static_cast<int32_t>(ResponseCode(state));
442 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700443 }
444
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700445 mKeyStore->getEnforcementPolicy().set_device_locked(true, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700446 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700447 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
448 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700449}
450
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700451Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700452 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700453 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
454 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700455 }
456
457 State state = mKeyStore->getState(userId);
458 if (state != ::STATE_LOCKED) {
459 switch (state) {
460 case ::STATE_NO_ERROR:
461 ALOGI("calling unlock when already unlocked, ignoring.");
462 break;
463 case ::STATE_UNINITIALIZED:
464 ALOGE("unlock called on uninitialized keystore.");
465 break;
466 default:
467 ALOGE("unlock called on keystore in unknown state: %d", state);
468 break;
469 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700470 *aidl_return = static_cast<int32_t>(ResponseCode(state));
471 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700472 }
473
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700474 mKeyStore->getEnforcementPolicy().set_device_locked(false, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700475 const String8 password8(pw);
476 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700477 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
478 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700479}
480
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700481Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700482 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700483 *aidl_return = static_cast<int32_t>(false);
484 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700485 }
486
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700487 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
488 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700489}
490
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700491Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
492 ::android::String16* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700493 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700494 auto result =
495 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100496 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700497 *aidl_return = String16();
498 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700499 }
500
501 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700502 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
503 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700504 *aidl_return = String16();
505 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700506 }
507
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700508 *aidl_return = String16(mKeyStore->addGrant(lockedEntry, granteeUid).c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700509 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700510}
511
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700512Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700513 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700514 KeyStoreServiceReturnCode result =
515 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100516 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800517 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700518 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700519 }
520
521 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700522
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700523 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
524 if (!lockedEntry) {
525 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700526 }
527
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700528 *aidl_return = mKeyStore->removeGrant(lockedEntry, granteeUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700529 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700530}
531
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700532Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700533 uid_t targetUid = getEffectiveUid(uid);
534 if (!checkBinderPermission(P_GET, targetUid)) {
535 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700536 *time = -1L;
537 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700538 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700539 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700540
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700541 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
542 if (!lockedEntry) {
543 ALOGW("could not access key with alias %s for getmtime", name8.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700544 *time = -1L;
545 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700546 }
547
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700548 std::string filename = lockedEntry->getKeyBlobPath();
549
550 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700551 if (fd < 0) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700552 ALOGW("could not open %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700553 *time = -1L;
554 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700555 }
556
557 struct stat s;
558 int ret = fstat(fd, &s);
559 close(fd);
560 if (ret == -1) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700561 ALOGW("could not stat %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700562 *time = -1L;
563 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700564 }
565
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700566 *time = static_cast<int64_t>(s.st_mtime);
567 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700568}
569
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700570Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
571 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
572 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700573}
574
Janis Danisevskis265435f2018-11-16 14:10:46 -0800575Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700576 uid_t targetUid = getEffectiveUid(targetUid64);
577 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800578 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700579 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000580 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700581
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700582 mKeyStore->removeAllGrantsToUid(targetUid);
583
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700584 ResponseCode rc;
585 std::list<LockedKeyBlobEntry> entries;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800586 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700587
588 // list has a fence making sure no workers are modifying blob files before iterating the
589 // data base. All returned entries are locked.
590 std::tie(rc, entries) = LockedKeyBlobEntry::list(
Janis Danisevskis265435f2018-11-16 14:10:46 -0800591 userDirName, [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700592
593 if (rc != ResponseCode::NO_ERROR) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800594 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700595 }
596
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700597 for (LockedKeyBlobEntry& lockedEntry : entries) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100598 if (get_app_id(targetUid) == AID_SYSTEM) {
599 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700600 Blob charBlob;
601 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
602 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100603 // Do not clear keys critical to device encryption under system uid.
604 continue;
605 }
606 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700607 mKeyStore->del(lockedEntry);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700608 }
Janis Danisevskis265435f2018-11-16 14:10:46 -0800609 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700610}
611
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600612Status KeyStoreService::addRngEntropy(
613 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
614 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
Janis Danisevskisc1460142017-12-18 16:48:46 -0800615 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
616 if (!device) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600617 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800618 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700619
Janis Danisevskisa359c672019-03-14 17:15:06 -0700620 device->addRngEntropy(entropy, [device, cb](Return<ErrorCode> rc) {
621 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device, rc)));
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600622 });
623
624 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700625}
626
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600627Status KeyStoreService::generateKey(
628 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
629 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
630 int uid, int flags, int32_t* _aidl_return) {
Max Biresef4f0672017-11-29 14:38:48 -0800631 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
632 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700633 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000634 auto logOnScopeExit = android::base::make_scope_guard([&] {
635 if (__android_log_security()) {
636 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600637 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000638 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
639 }
640 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100641 KeyStoreServiceReturnCode rc =
642 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
643 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600644 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700645 }
Rubin Xu67899de2017-04-21 19:15:13 +0100646 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
647 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600648 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100649 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700650
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700651 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700652 // TODO(jbires): remove uid checking upon implementation of b/25646100
Max Bires670467d2017-12-12 11:16:43 -0800653 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Biresef4f0672017-11-29 14:38:48 -0800654 originalUid != IPCThreadState::self()->getCallingUid()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600655 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700656 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600657 }
658
Janis Danisevskisc1460142017-12-18 16:48:46 -0800659 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
660 auto dev = mKeyStore->getDevice(securityLevel);
661 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600662 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800663 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400664
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100665 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700666 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
667 if (!lockedEntry) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600668 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100669 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400670
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700671 logOnScopeExit.Disable();
672
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600673 dev->generateKey(
674 std::move(lockedEntry), params.getParameters(), entropy, flags,
675 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
676 if (__android_log_security()) {
677 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
678 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
679 }
680 cb->onFinished(rc,
681 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
682 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700683
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600684 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700685}
686
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700687Status KeyStoreService::getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600688 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700689 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
Janis Danisevskis64ec1fe2018-02-26 16:47:21 -0800690 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600691 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700692
693 uid_t targetUid = getEffectiveUid(uid);
694 uid_t callingUid = IPCThreadState::self()->getCallingUid();
695 if (!is_granted_to(callingUid, targetUid)) {
696 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
697 targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600698 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700699 }
700
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700701 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700702
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700703 ResponseCode rc;
704 Blob keyBlob;
705 Blob charBlob;
706 LockedKeyBlobEntry lockedEntry;
Janis Danisevskisd714a672017-09-01 14:31:36 -0700707
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700708 std::tie(rc, keyBlob, charBlob, lockedEntry) =
709 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
710
711 if (rc != ResponseCode::NO_ERROR) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600712 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700713 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100714
Janis Danisevskisc1460142017-12-18 16:48:46 -0800715 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700716 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600717 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100718 }
719
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700720 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
721 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
722 // from keymaster. It may also upgrade the key blob.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700723 dev->getKeyCharacteristics(
724 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
725 std::move(charBlob),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600726 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
727 cb->onFinished(rc,
728 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700729 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100730
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600731 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700732}
733
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600734Status KeyStoreService::importKey(
735 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
736 const String16& name, const KeymasterArguments& params, int32_t format,
737 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700738 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000739 auto logOnScopeExit = android::base::make_scope_guard([&] {
740 if (__android_log_security()) {
741 android_log_event_list(SEC_TAG_KEY_IMPORTED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600742 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000743 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
744 }
745 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100746 KeyStoreServiceReturnCode rc =
747 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
748 if (!rc.isOk()) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700749 LOG(ERROR) << "permissission denied";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600750 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700751 }
Rubin Xu67899de2017-04-21 19:15:13 +0100752 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
753 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600754 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100755 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700756
Janis Danisevskisc1460142017-12-18 16:48:46 -0800757 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
758 auto dev = mKeyStore->getDevice(securityLevel);
759 if (!dev) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700760 LOG(ERROR) << "importKey - cound not get keymaster device";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600761 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800762 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700763
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700764 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700765 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
766 if (!lockedEntry) {
767 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
768 << " already exists.";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600769 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400770 }
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700771
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700772 logOnScopeExit.Disable();
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700773
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600774 dev->importKey(
775 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
776 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
777 if (__android_log_security()) {
778 android_log_event_list(SEC_TAG_KEY_IMPORTED)
779 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
780 }
781 cb->onFinished(rc,
782 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
783 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400784
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600785 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700786}
787
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600788Status KeyStoreService::exportKey(
789 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
790 const String16& name, int32_t format,
791 const ::android::security::keymaster::KeymasterBlob& clientId,
792 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
793 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700794
795 uid_t targetUid = getEffectiveUid(uid);
796 uid_t callingUid = IPCThreadState::self()->getCallingUid();
797 if (!is_granted_to(callingUid, targetUid)) {
798 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600799 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700800 }
801
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700802 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700803
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700804 KeyStoreServiceReturnCode rc;
805 Blob keyBlob;
806 Blob charBlob;
807 LockedKeyBlobEntry lockedEntry;
808
809 std::tie(rc, keyBlob, charBlob, lockedEntry) =
810 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskis3cf85322018-11-19 13:37:49 -0800811 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600812 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700813 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100814
Janis Danisevskisc1460142017-12-18 16:48:46 -0800815 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100816
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700817 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600818 std::move(keyBlob), std::move(charBlob),
819 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
Ji Wang2c142312016-10-14 17:21:10 +0800820
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600821 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700822}
823
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600824Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
825 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700826 bool pruneable, const KeymasterArguments& params,
827 const ::std::vector<uint8_t>& entropy, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600828 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700829 uid_t callingUid = IPCThreadState::self()->getCallingUid();
830 uid_t targetUid = getEffectiveUid(uid);
831 if (!is_granted_to(callingUid, targetUid)) {
832 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600833 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700834 }
835 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
836 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600837 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700838 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700839 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600840 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700841 }
Shawn Willden0329a822017-12-04 13:55:14 -0700842
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700843 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700844 Blob keyBlob;
845 Blob charBlob;
846 LockedKeyBlobEntry lockedEntry;
847 ResponseCode rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100848
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700849 std::tie(rc, keyBlob, charBlob, lockedEntry) =
850 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
851
852 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600853 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700854 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600855 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700856
Janis Danisevskisc1460142017-12-18 16:48:46 -0800857 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700858 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100859
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700860 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
861 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600862 [this, cb, dev](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700863 if (result_.resultCode.isOk() ||
864 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
865 addOperationDevice(result_.token, dev);
866 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600867 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700868 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400869
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600870 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700871}
872
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600873Status KeyStoreService::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
874 const ::android::sp<::android::IBinder>& token,
875 const ::android::security::keymaster::KeymasterArguments& params,
876 const ::std::vector<uint8_t>& input, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700877 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600878 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700879 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700880
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700881 auto dev = getOperationDevice(token);
882 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600883 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700884 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700885
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600886 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700887 if (!result_.resultCode.isOk()) {
888 removeOperationDevice(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100889 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600890 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700891 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100892
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600893 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700894}
895
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600896Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
897 const ::android::sp<::android::IBinder>& token,
898 const ::android::security::keymaster::KeymasterArguments& params,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700899 const ::std::vector<uint8_t>& signature,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600900 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700901 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600902 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700903 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700904
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700905 auto dev = getOperationDevice(token);
906 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600907 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700908 }
909
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700910 dev->finish(token, params.getParameters(), {}, signature, entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600911 [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700912 if (!result_.resultCode.isOk()) {
913 removeOperationDevice(token);
914 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600915 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700916 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700917
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600918 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700919}
920
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600921Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
922 const ::android::sp<::android::IBinder>& token,
923 int32_t* _aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700924 auto dev = getOperationDevice(token);
925 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600926 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700927 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100928
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600929 dev->abort(token, [cb](KeyStoreServiceReturnCode rc) { cb->onFinished(rc); });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700930
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600931 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700932}
933
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700934Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000935 int32_t* aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700936
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000937 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
938 // receive a HardwareAuthToken, rather than an opaque byte array.
939
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700940 if (!checkBinderPermission(P_ADD_AUTH)) {
941 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700942 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
943 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700944 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700945 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
Branden Archer70080742018-11-20 11:04:11 -0800946 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700947 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000948 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100949
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000950 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700951 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000952 if (authToken.version != 0) {
Branden Archer70080742018-11-20 11:04:11 -0800953 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700954 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000955 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100956
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700957 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
958 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700959 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
960 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700961}
962
Eran Messerid9f8ae52018-10-24 13:54:00 +0100963bool isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -0700964 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700965 for (size_t i = 0; i < paramsVec.size(); ++i) {
966 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -0600967 case Tag::ATTESTATION_ID_BRAND:
968 case Tag::ATTESTATION_ID_DEVICE:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600969 case Tag::ATTESTATION_ID_MANUFACTURER:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600970 case Tag::ATTESTATION_ID_MODEL:
971 case Tag::ATTESTATION_ID_PRODUCT:
Rubin Xu1a203e32018-05-08 14:25:21 +0100972 case Tag::ATTESTATION_ID_IMEI:
973 case Tag::ATTESTATION_ID_MEID:
974 case Tag::ATTESTATION_ID_SERIAL:
Eran Messerid9f8ae52018-10-24 13:54:00 +0100975 return true;
Rubin Xu1a203e32018-05-08 14:25:21 +0100976 default:
977 continue;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100978 }
979 }
Eran Messerid9f8ae52018-10-24 13:54:00 +0100980 return false;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100981}
982
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600983Status KeyStoreService::attestKey(
984 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
985 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700986 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
987 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600988 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -0700989 }
990
Eran Messerie2c34152017-12-21 21:01:22 +0000991 uid_t callingUid = IPCThreadState::self()->getCallingUid();
992
Eran Messerid9f8ae52018-10-24 13:54:00 +0100993 if (isDeviceIdAttestationRequested(params) && (get_app_id(callingUid) != AID_SYSTEM)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600994 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100995 }
996
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700997 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200998 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
999 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001000 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001001 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001002
Shawn Willden50eb1b22016-01-21 12:41:23 -07001003 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001004 Blob keyBlob;
1005 Blob charBlob;
1006 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001007
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001008 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1009 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1010
Janis Danisevskisc1460142017-12-18 16:48:46 -08001011 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001012 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001013 dev->attestKey(
1014 std::move(hidlKey), mutableParams.hidl_data(),
Janis Danisevskisa359c672019-03-14 17:15:06 -07001015 [dev, cb](Return<void> rc,
1016 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001017 auto& [ret, certChain] = hidlResult;
1018 if (!rc.isOk()) {
1019 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1020 } else if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001021 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001022 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1023 } else {
1024 cb->onFinished(KeyStoreServiceReturnCode(ret),
1025 KeymasterCertificateChain(std::move(certChain)));
1026 }
1027 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001028
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001029 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001030}
1031
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001032// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1033// It should never be redefined by a build system though.
1034#ifndef CAPTURE_MOVE
1035#define CAPTURE_MOVE(x) x = std::move(x)
1036#endif
1037
1038Status KeyStoreService::attestDeviceIds(
1039 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1040 const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001041 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001042
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001043 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001044 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001045 }
1046
1047 if (!isDeviceIdAttestationRequested(params)) {
1048 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001049 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001050 }
1051
1052 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1053 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
Yi Konge353f252018-07-30 01:38:39 -07001054 if (binder == nullptr) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001055 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001056 }
1057 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1058 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1059 IPCThreadState::self()->getCallingPid(), callingUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001060 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001061 }
1062
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001063 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001064 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1065 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001066 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001067 }
1068
1069 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001070 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001071
Shawn Willden70c1a782018-07-11 15:13:20 -06001072 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001073 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001074 }
1075
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001076
1077 AuthorizationSet keyCharacteristics;
1078 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1079 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1080 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1081 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1082 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001083
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001084 std::promise<KeyStoreServiceReturnCode> resultPromise;
1085 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001086
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001087 dev->generateKey(
1088 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001089 [cb, dev, CAPTURE_MOVE(mutableParams)](
1090 Return<void> rc,
1091 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001092 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1093 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1094 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001095 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001096 return;
1097 }
1098 if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001099 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001100 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001101 return;
1102 }
1103 dev->attestKey(
1104 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001105 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001106 hidlKeyBlob](Return<void> rc,
1107 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1108 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001109 // schedule temp key for deletion
Janis Danisevskisa359c672019-03-14 17:15:06 -07001110 dev->deleteKey(std::move(hidlKeyBlob), [dev](Return<ErrorCode> rc) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001111 // log error but don't return an error
Janis Danisevskisa359c672019-03-14 17:15:06 -07001112 KS_HANDLE_HIDL_ERROR(dev, rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001113 });
1114 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001115 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001116 return;
1117 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001118 if (ret == ErrorCode::OK) {
1119 cb->onFinished(
1120 KeyStoreServiceReturnCode(ret),
1121 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1122 } else {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001123 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001124 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001125 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001126 });
1127 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001128
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001129 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001130}
1131
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001132Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001133 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001134 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001135 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1136 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001137}
1138
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001139Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001140 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001141 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1142 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1143 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001144 int32_t* _aidl_return) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001145
1146 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1147
1148 if (!checkBinderPermission(P_INSERT, callingUid)) {
1149 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1150 }
1151
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001152 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001153
1154 KeyStoreServiceReturnCode rc;
1155 Blob wrappingKeyBlob;
1156 Blob wrappingCharBlob;
1157 LockedKeyBlobEntry wrappingLockedEntry;
1158
1159 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1160 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
Branden Archerd166a882018-11-20 10:56:48 -08001161 if (!rc.isOk()) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001162 return AIDL_RETURN(rc);
1163 }
1164
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001165 String8 wrappedKeyName8(wrappedKeyAlias);
1166 auto wrappedLockedEntry =
1167 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1168 if (!wrappedLockedEntry) {
1169 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1170 }
1171
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001172 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1173 auto dev = mKeyStore->getDevice(securityLevel);
1174 if (!dev) {
1175 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1176 }
1177
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001178 dev->importWrappedKey(
1179 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1180 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001181 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1182 cb->onFinished(rc,
1183 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001184 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001185
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001186 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001187}
1188
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001189Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1190 const String16& promptText,
1191 const ::std::vector<uint8_t>& extraData,
1192 const String16& locale, int32_t uiOptionsAsFlags,
1193 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001194 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1195 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001196}
1197
1198Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1199 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001200 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001201}
1202
David Zeuthen1a492312018-02-26 11:00:30 -05001203Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001204 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001205}
1206
1207/**
1208 * Get the effective target uid for a binder operation that takes an
1209 * optional uid as the target.
1210 */
1211uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1212 if (targetUid == UID_SELF) {
1213 return IPCThreadState::self()->getCallingUid();
1214 }
1215 return static_cast<uid_t>(targetUid);
1216}
1217
1218/**
1219 * Check if the caller of the current binder method has the required
1220 * permission and if acting on other uids the grants to do so.
1221 */
1222bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1223 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1224 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001225 const char* ssid = IPCThreadState::self()->getCallingSid();
1226 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001227 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1228 return false;
1229 }
1230 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1231 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1232 return false;
1233 }
1234 return true;
1235}
1236
1237/**
1238 * Check if the caller of the current binder method has the required
1239 * permission and the target uid is the caller or the caller is system.
1240 */
1241bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1242 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1243 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001244 const char* ssid = IPCThreadState::self()->getCallingSid();
1245 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001246 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1247 return false;
1248 }
1249 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1250}
1251
1252/**
1253 * Check if the caller of the current binder method has the required
1254 * permission or the target of the operation is the caller's uid. This is
1255 * for operation where the permission is only for cross-uid activity and all
1256 * uids are allowed to act on their own (ie: clearing all entries for a
1257 * given uid).
1258 */
1259bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1260 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1261 if (getEffectiveUid(targetUid) == callingUid) {
1262 return true;
1263 } else {
1264 return checkBinderPermission(permission, targetUid);
1265 }
1266}
1267
1268/**
1269 * Helper method to check that the caller has the required permission as
1270 * well as the keystore is in the unlocked state if checkUnlocked is true.
1271 *
1272 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1273 * otherwise the state of keystore when not unlocked and checkUnlocked is
1274 * true.
1275 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001276KeyStoreServiceReturnCode
1277KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1278 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001279 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001280 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001281 }
1282 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1283 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001284 // All State values coincide with ResponseCodes
1285 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001286 }
1287
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001288 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001289}
1290
1291bool KeyStoreService::isKeystoreUnlocked(State state) {
1292 switch (state) {
1293 case ::STATE_NO_ERROR:
1294 return true;
1295 case ::STATE_UNINITIALIZED:
1296 case ::STATE_LOCKED:
1297 return false;
1298 }
1299 return false;
1300}
1301
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001302/**
Shawn Willden0329a822017-12-04 13:55:14 -07001303 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1304 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001305 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001306bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1307 for (size_t i = 0; i < params.size(); ++i) {
1308 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001309 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001310 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001311 return false;
1312 default:
1313 break;
1314 }
1315 }
1316 return true;
1317}
1318
Brian Young9a947d52018-02-23 18:03:14 +00001319Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
1320 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001321 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Brian Young9a947d52018-02-23 18:03:14 +00001322 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001323
1324 return Status::ok();
1325}
1326
Shawn Willdene2a7b522017-04-11 09:27:40 -06001327} // namespace keystore