blob: fa010e637caba93b0180a3a5f4f14fb188f7ed0c [file] [log] [blame]
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Janis Danisevskis011675d2016-09-01 11:41:29 +010017#define LOG_TAG "keystore"
18
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070019#include "key_store_service.h"
20
21#include <fcntl.h>
22#include <sys/stat.h>
23
Janis Danisevskis7612fd42016-09-01 11:50:02 +010024#include <algorithm>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070025#include <atomic>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070026#include <sstream>
27
Pavel Grafovff311b42018-01-24 20:34:37 +000028#include <android-base/scopeguard.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010029#include <binder/IInterface.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070030#include <binder/IPCThreadState.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010031#include <binder/IPermissionController.h>
32#include <binder/IServiceManager.h>
Brian Claire Young3133c452018-08-31 13:56:49 -070033#include <cutils/multiuser.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000034#include <log/log_event_list.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070035
36#include <private/android_filesystem_config.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000037#include <private/android_logger.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070038
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070039#include <android/hardware/confirmationui/1.0/IConfirmationUI.h>
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010040#include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070041
42#include "defaults.h"
Max Bires33aac2d2018-02-23 10:53:10 -080043#include "key_proto_handler.h"
Janis Danisevskis18f27ad2016-06-01 13:57:40 -070044#include "keystore_attestation_id.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010045#include "keystore_keymaster_enforcement.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070046#include "keystore_utils.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010047#include <keystore/keystore_hidl_support.h>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070048#include <keystore/keystore_return_types.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070049
Janis Danisevskis8f737ad2017-11-21 12:30:15 -080050#include <hardware/hw_auth_token.h>
51
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010052namespace keystore {
Shawn Willdend5a24e62017-02-28 13:53:24 -070053
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010054using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070055
Shawn Willdene2a7b522017-04-11 09:27:40 -060056namespace {
57
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070058using ::android::binder::Status;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070059using android::security::keymaster::ExportResult;
60using android::security::keymaster::KeymasterArguments;
61using android::security::keymaster::KeymasterBlob;
62using android::security::keymaster::KeymasterCertificateChain;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070063using android::security::keymaster::operationFailed;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070064using android::security::keymaster::OperationResult;
David Zeuthenc6eb7cd2017-11-27 11:33:55 -050065using ConfirmationResponseCode = android::hardware::confirmationui::V1_0::ResponseCode;
Rob Barnesbb6cabd2018-10-04 17:10:37 -060066using ::android::security::keystore::IKeystoreOperationResultCallback;
67using ::android::security::keystore::IKeystoreResponseCallback;
68using ::android::security::keystore::KeystoreResponse;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070069
Shawn Willdene2a7b522017-04-11 09:27:40 -060070constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
71const char* kTimestampFilePath = "timestamp";
Rubin Xu1a203e32018-05-08 14:25:21 +010072const int ID_ATTESTATION_REQUEST_GENERIC_INFO = 1 << 0;
73const int ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID = 1 << 1;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070074
75struct BIGNUM_Delete {
76 void operator()(BIGNUM* p) const { BN_free(p); }
77};
Janis Danisevskisccfff102017-05-01 11:02:51 -070078typedef std::unique_ptr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070079
Shawn Willdene2a7b522017-04-11 09:27:40 -060080bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070081 return params.end() !=
82 std::find_if(params.begin(), params.end(),
83 [&](const KeyParameter& param) { return param.tag == tag; });
Shawn Willdend5a24e62017-02-28 13:53:24 -070084}
85
Rob Barnesbb6cabd2018-10-04 17:10:37 -060086#define AIDL_RETURN(rc) \
87 (*_aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(rc)), Status::ok())
88
Shawn Willdene2a7b522017-04-11 09:27:40 -060089std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
90 struct stat sbuf;
91 if (stat(kTimestampFilePath, &sbuf) == 0) {
Yi Konge353f252018-07-30 01:38:39 -070092 double diff_secs = difftime(time(nullptr), sbuf.st_ctime);
Shawn Willdene2a7b522017-04-11 09:27:40 -060093 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
94 }
95
96 if (errno != ENOENT) {
97 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
98 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
99 }
100
101 int fd = creat(kTimestampFilePath, 0600);
102 if (fd < 0) {
103 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
104 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
105 }
106
107 if (close(fd)) {
108 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
109 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
110 }
111
112 return {ResponseCode::NO_ERROR, true};
113}
114
Eran Messeri03fc4c82018-08-16 18:53:15 +0100115using ::android::security::KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200116
117KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
118 KeyStoreServiceReturnCode responseCode;
119 bool factoryResetSinceIdRotation;
120 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
121
122 if (!responseCode.isOk()) return responseCode;
123 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
124
125 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
126 if (!asn1_attestation_id_result.isOk()) {
127 ALOGE("failed to gather attestation_id");
128 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
129 }
130 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
131
132 /*
Eran Messeri03fc4c82018-08-16 18:53:15 +0100133 * The attestation application ID must not be longer than
134 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, error out if gather_attestation_application_id
135 * returned such an invalid vector.
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200136 */
137 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Eran Messeri03fc4c82018-08-16 18:53:15 +0100138 ALOGE("BUG: Gathered Attestation Application ID is too big (%d)",
139 static_cast<int32_t>(asn1_attestation_id.size()));
140 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200141 }
142
143 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
144
145 return ResponseCode::NO_ERROR;
146}
147
Shawn Willdene2a7b522017-04-11 09:27:40 -0600148} // anonymous namespace
149
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700150Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700151 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700152 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
153 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700154 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700155 *aidl_return = mKeyStore->getState(userId);
156 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700157}
158
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700159Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700160 uid_t targetUid = getEffectiveUid(uid);
161 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700162 // see keystore/keystore.h
163 return Status::fromServiceSpecificError(
164 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700165 }
166
167 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700168 ResponseCode rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700169 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700170 Blob charBlob;
171 LockedKeyBlobEntry lockedEntry;
172
173 std::tie(rc, keyBlob, charBlob, lockedEntry) =
174 mKeyStore->getKeyForName(name8, targetUid, TYPE_GENERIC);
175 if (rc != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700176 *item = ::std::vector<uint8_t>();
177 // Return empty array if key is not found
178 // TODO: consider having returned value nullable or parse exception on the client.
179 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700180 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100181 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700182 // The static_cast here is needed to prevent a move, forcing a deep copy.
183 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
184 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700185}
186
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700187Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
188 int targetUid, int32_t flags, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700189 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700190 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700191 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100192 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700193 *aidl_return = static_cast<int32_t>(result);
194 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700195 }
196
197 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700198 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), targetUid);
199
200 if (!lockedEntry) {
201 ALOGE("failed to grab lock on blob entry %u_%s", targetUid, name8.string());
202 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_ALREADY_EXISTS);
203 return Status::ok();
204 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700205
Yi Konge353f252018-07-30 01:38:39 -0700206 Blob keyBlob(&item[0], item.size(), nullptr, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700207 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
208
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700209 *aidl_return = static_cast<int32_t>(mKeyStore->put(lockedEntry, keyBlob, {}));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700210 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700211}
212
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700213Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700214 targetUid = getEffectiveUid(targetUid);
215 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700216 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
217 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700218 }
219 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000220 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700221 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
222 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700223 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
224 return Status::ok();
225 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700226
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700227 ResponseCode result = mKeyStore->del(lockedEntry);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400228
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700229 *aidl_return = static_cast<int32_t>(result);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700230 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700231}
232
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700233Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700234 targetUid = getEffectiveUid(targetUid);
235 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700236 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
237 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700238 }
239
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700240 LockedKeyBlobEntry lockedEntry =
241 mKeyStore->getLockedBlobEntryIfExists(String8(name).string(), targetUid);
242 *aidl_return =
243 static_cast<int32_t>(lockedEntry ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700244 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700245}
246
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700247Status KeyStoreService::list(const String16& prefix, int32_t targetUid,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700248 ::std::vector<::android::String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700249 targetUid = getEffectiveUid(targetUid);
250 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700251 return Status::fromServiceSpecificError(
252 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700253 }
254 const String8 prefix8(prefix);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700255 const std::string stdPrefix(prefix8.string());
256
257 ResponseCode rc;
258 std::list<LockedKeyBlobEntry> internal_matches;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800259 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700260
Janis Danisevskis265435f2018-11-16 14:10:46 -0800261 std::tie(rc, internal_matches) =
262 LockedKeyBlobEntry::list(userDirName, [&](uid_t uid, const std::string& alias) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700263 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end());
264 return uid == static_cast<uid_t>(targetUid) &&
265 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end())
266 .first == stdPrefix.end();
267 });
268
269 if (rc != ResponseCode::NO_ERROR) {
270 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700271 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700272
273 for (LockedKeyBlobEntry& entry : internal_matches) {
274 matches->push_back(String16(entry->alias().substr(prefix8.size()).c_str()));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700275 }
276 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700277}
278
Rob Barneseb7f79b2018-11-08 15:44:10 -0700279/*
280 * This method will return the uids of all auth bound keys for the calling user.
281 * This is intended to be used for alerting the user about which apps will be affected
282 * if the password/pin is removed. Only allowed to be called by system.
283 * The output is bound by the initial size of uidsOut to be compatible with Java.
284 */
285Status KeyStoreService::listUidsOfAuthBoundKeys(::std::vector<int32_t>* uidsOut,
286 int32_t* aidl_return) {
287 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
316 auto it = uidsOut->begin();
317 for (LockedKeyBlobEntry& entry : internal_matches) {
318 if (it == uidsOut->end()) {
319 ALOGW("Maximum number (%d) of auth bound uids found, truncating remainder",
320 static_cast<int32_t>(uidsOut->capacity()));
321 break;
322 }
323 if (std::find(uidsOut->begin(), it, entry->uid()) != it) {
324 // uid already in list, skip
325 continue;
326 }
327
328 auto [rc, blob, charBlob] = entry.readBlobs(encryptionKey, state);
329 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::LOCKED) {
330 ALOGE("Error reading blob for key %s", entry->alias().c_str());
331 continue;
332 }
333
334 if (blob && blob.isEncrypted()) {
335 *it++ = entry->uid();
336 } else if (charBlob) {
337 auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
338 if (!success) {
339 ALOGE("Error reading blob characteristics for key %s", entry->alias().c_str());
340 continue;
341 }
342 if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
343 swEnforced.Contains(TAG_USER_SECURE_ID)) {
344 *it++ = entry->uid();
345 }
346 }
347 }
348 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
349 return Status::ok();
350}
351
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700352Status KeyStoreService::reset(int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700353 if (!checkBinderPermission(P_RESET)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700354 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
355 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700356 }
357
358 uid_t callingUid = IPCThreadState::self()->getCallingUid();
359 mKeyStore->resetUser(get_user_id(callingUid), false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700360 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
361 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700362}
363
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700364Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
365 int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700366 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700367 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
368 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700369 }
370
371 const String8 password8(password);
372 // Flush the auth token table to prevent stale tokens from sticking
373 // around.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700374 mKeyStore->getAuthTokenTable().Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700375
376 if (password.size() == 0) {
377 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
378 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700379 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
380 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700381 } else {
382 switch (mKeyStore->getState(userId)) {
383 case ::STATE_UNINITIALIZED: {
384 // generate master key, encrypt with password, write to file,
385 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700386 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
387 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700388 }
389 case ::STATE_NO_ERROR: {
390 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700391 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
392 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700393 }
394 case ::STATE_LOCKED: {
395 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
396 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700397 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
398 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700399 }
400 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700401 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
402 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700403 }
404}
405
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700406Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700407 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700408 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
409 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700410 }
411
412 // Sanity check that the new user has an empty keystore.
413 if (!mKeyStore->isEmpty(userId)) {
414 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
415 }
416 // Unconditionally clear the keystore, just to be safe.
417 mKeyStore->resetUser(userId, false);
418 if (parentId != -1) {
419 // This profile must share the same master key password as the parent profile. Because the
420 // password of the parent profile is not known here, the best we can do is copy the parent's
421 // master key and master key file. This makes this profile use the same master key as the
422 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700423 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
424 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700425 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700426 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
427 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700428 }
429}
430
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700431Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700432 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700433 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
434 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700435 }
436
437 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700438 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
439 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700440}
441
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700442Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700443 if (!checkBinderPermission(P_LOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700444 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
445 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700446 }
447
448 State state = mKeyStore->getState(userId);
449 if (state != ::STATE_NO_ERROR) {
450 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700451 *aidl_return = static_cast<int32_t>(ResponseCode(state));
452 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700453 }
454
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700455 mKeyStore->getEnforcementPolicy().set_device_locked(true, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700456 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700457 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
458 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700459}
460
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700461Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700462 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700463 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
464 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700465 }
466
467 State state = mKeyStore->getState(userId);
468 if (state != ::STATE_LOCKED) {
469 switch (state) {
470 case ::STATE_NO_ERROR:
471 ALOGI("calling unlock when already unlocked, ignoring.");
472 break;
473 case ::STATE_UNINITIALIZED:
474 ALOGE("unlock called on uninitialized keystore.");
475 break;
476 default:
477 ALOGE("unlock called on keystore in unknown state: %d", state);
478 break;
479 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700480 *aidl_return = static_cast<int32_t>(ResponseCode(state));
481 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700482 }
483
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700484 mKeyStore->getEnforcementPolicy().set_device_locked(false, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700485 const String8 password8(pw);
486 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700487 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
488 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700489}
490
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700491Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
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) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700503 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700504 auto result =
505 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100506 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700507 *aidl_return = String16();
508 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700509 }
510
511 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700512 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
513 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700514 *aidl_return = String16();
515 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700516 }
517
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700518 *aidl_return = String16(mKeyStore->addGrant(lockedEntry, granteeUid).c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700519 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700520}
521
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700522Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700523 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700524 KeyStoreServiceReturnCode result =
525 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100526 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700527 *aidl_return = static_cast<int32_t>(result);
528 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700529 }
530
531 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700532
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700533 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
534 if (!lockedEntry) {
535 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700536 }
537
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700538 *aidl_return = mKeyStore->removeGrant(lockedEntry, granteeUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700539 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700540}
541
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700542Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700543 uid_t targetUid = getEffectiveUid(uid);
544 if (!checkBinderPermission(P_GET, targetUid)) {
545 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700546 *time = -1L;
547 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700548 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700549 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700550
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700551 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
552 if (!lockedEntry) {
553 ALOGW("could not access key with alias %s for getmtime", name8.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700554 *time = -1L;
555 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700556 }
557
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700558 std::string filename = lockedEntry->getKeyBlobPath();
559
560 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700561 if (fd < 0) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700562 ALOGW("could not open %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700563 *time = -1L;
564 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700565 }
566
567 struct stat s;
568 int ret = fstat(fd, &s);
569 close(fd);
570 if (ret == -1) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700571 ALOGW("could not stat %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700572 *time = -1L;
573 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700574 }
575
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700576 *time = static_cast<int64_t>(s.st_mtime);
577 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700578}
579
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700580Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
581 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
582 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700583}
584
Janis Danisevskis265435f2018-11-16 14:10:46 -0800585Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700586 uid_t targetUid = getEffectiveUid(targetUid64);
587 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800588 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700589 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000590 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700591
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700592 mKeyStore->removeAllGrantsToUid(targetUid);
593
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700594 ResponseCode rc;
595 std::list<LockedKeyBlobEntry> entries;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800596 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700597
598 // list has a fence making sure no workers are modifying blob files before iterating the
599 // data base. All returned entries are locked.
600 std::tie(rc, entries) = LockedKeyBlobEntry::list(
Janis Danisevskis265435f2018-11-16 14:10:46 -0800601 userDirName, [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700602
603 if (rc != ResponseCode::NO_ERROR) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800604 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700605 }
606
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700607 for (LockedKeyBlobEntry& lockedEntry : entries) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100608 if (get_app_id(targetUid) == AID_SYSTEM) {
609 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700610 Blob charBlob;
611 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
612 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100613 // Do not clear keys critical to device encryption under system uid.
614 continue;
615 }
616 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700617 mKeyStore->del(lockedEntry);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700618 }
Janis Danisevskis265435f2018-11-16 14:10:46 -0800619 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700620}
621
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600622Status KeyStoreService::addRngEntropy(
623 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
624 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
Janis Danisevskisc1460142017-12-18 16:48:46 -0800625 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
626 if (!device) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600627 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800628 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700629
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600630 device->addRngEntropy(entropy, [cb](Return<ErrorCode> rc) {
631 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(rc)));
632 });
633
634 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700635}
636
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600637Status KeyStoreService::generateKey(
638 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
639 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
640 int uid, int flags, int32_t* _aidl_return) {
Max Biresef4f0672017-11-29 14:38:48 -0800641 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
642 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700643 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000644 auto logOnScopeExit = android::base::make_scope_guard([&] {
645 if (__android_log_security()) {
646 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600647 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000648 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
649 }
650 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100651 KeyStoreServiceReturnCode rc =
652 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
653 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600654 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700655 }
Rubin Xu67899de2017-04-21 19:15:13 +0100656 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
657 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600658 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100659 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700660
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700661 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700662 // TODO(jbires): remove uid checking upon implementation of b/25646100
Max Bires670467d2017-12-12 11:16:43 -0800663 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Biresef4f0672017-11-29 14:38:48 -0800664 originalUid != IPCThreadState::self()->getCallingUid()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600665 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700666 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600667 }
668
Janis Danisevskisc1460142017-12-18 16:48:46 -0800669 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
670 auto dev = mKeyStore->getDevice(securityLevel);
671 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600672 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800673 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400674
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100675 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700676 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
677 if (!lockedEntry) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600678 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100679 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400680
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700681 logOnScopeExit.Disable();
682
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600683 dev->generateKey(
684 std::move(lockedEntry), params.getParameters(), entropy, flags,
685 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
686 if (__android_log_security()) {
687 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
688 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
689 }
690 cb->onFinished(rc,
691 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
692 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700693
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600694 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700695}
696
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700697Status KeyStoreService::getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600698 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700699 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
Janis Danisevskis64ec1fe2018-02-26 16:47:21 -0800700 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600701 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700702
703 uid_t targetUid = getEffectiveUid(uid);
704 uid_t callingUid = IPCThreadState::self()->getCallingUid();
705 if (!is_granted_to(callingUid, targetUid)) {
706 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
707 targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600708 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700709 }
710
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700711 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700712
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700713 ResponseCode rc;
714 Blob keyBlob;
715 Blob charBlob;
716 LockedKeyBlobEntry lockedEntry;
Janis Danisevskisd714a672017-09-01 14:31:36 -0700717
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700718 std::tie(rc, keyBlob, charBlob, lockedEntry) =
719 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
720
721 if (rc != ResponseCode::NO_ERROR) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600722 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700723 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100724
Janis Danisevskisc1460142017-12-18 16:48:46 -0800725 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700726 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600727 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100728 }
729
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700730 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
731 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
732 // from keymaster. It may also upgrade the key blob.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700733 dev->getKeyCharacteristics(
734 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
735 std::move(charBlob),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600736 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
737 cb->onFinished(rc,
738 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700739 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100740
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600741 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700742}
743
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600744Status KeyStoreService::importKey(
745 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
746 const String16& name, const KeymasterArguments& params, int32_t format,
747 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700748 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000749 auto logOnScopeExit = android::base::make_scope_guard([&] {
750 if (__android_log_security()) {
751 android_log_event_list(SEC_TAG_KEY_IMPORTED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600752 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000753 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
754 }
755 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100756 KeyStoreServiceReturnCode rc =
757 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
758 if (!rc.isOk()) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700759 LOG(ERROR) << "permissission denied";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600760 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700761 }
Rubin Xu67899de2017-04-21 19:15:13 +0100762 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
763 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600764 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100765 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700766
Janis Danisevskisc1460142017-12-18 16:48:46 -0800767 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
768 auto dev = mKeyStore->getDevice(securityLevel);
769 if (!dev) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700770 LOG(ERROR) << "importKey - cound not get keymaster device";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600771 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800772 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700773
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700774 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700775 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
776 if (!lockedEntry) {
777 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
778 << " already exists.";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600779 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400780 }
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700781
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700782 logOnScopeExit.Disable();
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700783
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600784 dev->importKey(
785 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
786 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
787 if (__android_log_security()) {
788 android_log_event_list(SEC_TAG_KEY_IMPORTED)
789 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
790 }
791 cb->onFinished(rc,
792 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
793 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400794
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600795 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700796}
797
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600798Status KeyStoreService::exportKey(
799 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
800 const String16& name, int32_t format,
801 const ::android::security::keymaster::KeymasterBlob& clientId,
802 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
803 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700804
805 uid_t targetUid = getEffectiveUid(uid);
806 uid_t callingUid = IPCThreadState::self()->getCallingUid();
807 if (!is_granted_to(callingUid, targetUid)) {
808 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600809 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700810 }
811
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700812 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700813
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700814 KeyStoreServiceReturnCode rc;
815 Blob keyBlob;
816 Blob charBlob;
817 LockedKeyBlobEntry lockedEntry;
818
819 std::tie(rc, keyBlob, charBlob, lockedEntry) =
820 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
821 if (!rc) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600822 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700823 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100824
Janis Danisevskisc1460142017-12-18 16:48:46 -0800825 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100826
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700827 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600828 std::move(keyBlob), std::move(charBlob),
829 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
Ji Wang2c142312016-10-14 17:21:10 +0800830
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600831 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700832}
833
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600834Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
835 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700836 bool pruneable, const KeymasterArguments& params,
837 const ::std::vector<uint8_t>& entropy, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600838 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700839 uid_t callingUid = IPCThreadState::self()->getCallingUid();
840 uid_t targetUid = getEffectiveUid(uid);
841 if (!is_granted_to(callingUid, targetUid)) {
842 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600843 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700844 }
845 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
846 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600847 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700848 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700849 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600850 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700851 }
Shawn Willden0329a822017-12-04 13:55:14 -0700852
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700853 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700854 Blob keyBlob;
855 Blob charBlob;
856 LockedKeyBlobEntry lockedEntry;
857 ResponseCode rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100858
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700859 std::tie(rc, keyBlob, charBlob, lockedEntry) =
860 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
861
862 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600863 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700864 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600865 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700866
Janis Danisevskisc1460142017-12-18 16:48:46 -0800867 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700868 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100869
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700870 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
871 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600872 [this, cb, dev](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700873 if (result_.resultCode.isOk() ||
874 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
875 addOperationDevice(result_.token, dev);
876 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600877 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700878 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400879
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600880 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700881}
882
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600883Status KeyStoreService::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
884 const ::android::sp<::android::IBinder>& token,
885 const ::android::security::keymaster::KeymasterArguments& params,
886 const ::std::vector<uint8_t>& input, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700887 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600888 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700889 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700890
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700891 auto dev = getOperationDevice(token);
892 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600893 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700894 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700895
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600896 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700897 if (!result_.resultCode.isOk()) {
898 removeOperationDevice(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100899 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600900 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700901 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100902
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600903 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700904}
905
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600906Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
907 const ::android::sp<::android::IBinder>& token,
908 const ::android::security::keymaster::KeymasterArguments& params,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700909 const ::std::vector<uint8_t>& signature,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600910 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700911 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600912 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700913 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700914
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700915 auto dev = getOperationDevice(token);
916 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600917 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700918 }
919
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700920 dev->finish(token, params.getParameters(), {}, signature, entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600921 [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700922 if (!result_.resultCode.isOk()) {
923 removeOperationDevice(token);
924 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600925 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700926 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700927
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600928 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700929}
930
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600931Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
932 const ::android::sp<::android::IBinder>& token,
933 int32_t* _aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700934 auto dev = getOperationDevice(token);
935 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600936 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700937 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100938
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600939 dev->abort(token, [cb](KeyStoreServiceReturnCode rc) { cb->onFinished(rc); });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700940
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600941 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700942}
943
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700944Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000945 int32_t* aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700946
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000947 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
948 // receive a HardwareAuthToken, rather than an opaque byte array.
949
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700950 if (!checkBinderPermission(P_ADD_AUTH)) {
951 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700952 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
953 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700954 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700955 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
956 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
957 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000958 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100959
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000960 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700961 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000962 if (authToken.version != 0) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700963 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
964 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000965 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100966
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700967 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
968 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700969 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
970 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700971}
972
Rubin Xu1a203e32018-05-08 14:25:21 +0100973int isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -0700974 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Rubin Xu1a203e32018-05-08 14:25:21 +0100975 int result = 0;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700976 for (size_t i = 0; i < paramsVec.size(); ++i) {
977 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -0600978 case Tag::ATTESTATION_ID_BRAND:
979 case Tag::ATTESTATION_ID_DEVICE:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600980 case Tag::ATTESTATION_ID_MANUFACTURER:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600981 case Tag::ATTESTATION_ID_MODEL:
982 case Tag::ATTESTATION_ID_PRODUCT:
Rubin Xu1a203e32018-05-08 14:25:21 +0100983 result |= ID_ATTESTATION_REQUEST_GENERIC_INFO;
Shawn Willdene2a7b522017-04-11 09:27:40 -0600984 break;
Rubin Xu1a203e32018-05-08 14:25:21 +0100985 case Tag::ATTESTATION_ID_IMEI:
986 case Tag::ATTESTATION_ID_MEID:
987 case Tag::ATTESTATION_ID_SERIAL:
988 result |= ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID;
989 break;
990 default:
991 continue;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100992 }
993 }
Rubin Xu1a203e32018-05-08 14:25:21 +0100994 return result;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100995}
996
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600997Status KeyStoreService::attestKey(
998 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
999 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001000 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1001 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001002 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001003 }
1004
Eran Messerie2c34152017-12-21 21:01:22 +00001005 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1006
Rubin Xu1a203e32018-05-08 14:25:21 +01001007 int needsIdAttestation = isDeviceIdAttestationRequested(params);
1008 bool needsUniqueIdAttestation = needsIdAttestation & ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID;
1009 bool isPrimaryUserSystemUid = (callingUid == AID_SYSTEM);
1010 bool isSomeUserSystemUid = (get_app_id(callingUid) == AID_SYSTEM);
1011 // Allow system context from any user to request attestation with basic device information,
1012 // while only allow system context from user 0 (device owner) to request attestation with
1013 // unique device ID.
1014 if ((needsIdAttestation && !isSomeUserSystemUid) ||
1015 (needsUniqueIdAttestation && !isPrimaryUserSystemUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001016 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001017 }
1018
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001019 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001020 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1021 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001022 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001023 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001024
Shawn Willden50eb1b22016-01-21 12:41:23 -07001025 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001026 Blob keyBlob;
1027 Blob charBlob;
1028 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001029
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001030 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1031 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1032
Janis Danisevskisc1460142017-12-18 16:48:46 -08001033 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001034 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001035 dev->attestKey(
1036 std::move(hidlKey), mutableParams.hidl_data(),
1037 [cb](Return<void> rc, std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1038 auto& [ret, certChain] = hidlResult;
1039 if (!rc.isOk()) {
1040 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1041 } else if (ret != ErrorCode::OK) {
1042 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1043 } else {
1044 cb->onFinished(KeyStoreServiceReturnCode(ret),
1045 KeymasterCertificateChain(std::move(certChain)));
1046 }
1047 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001048
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001049 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001050}
1051
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001052// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1053// It should never be redefined by a build system though.
1054#ifndef CAPTURE_MOVE
1055#define CAPTURE_MOVE(x) x = std::move(x)
1056#endif
1057
1058Status KeyStoreService::attestDeviceIds(
1059 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1060 const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001061 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001062
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001063 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001064 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001065 }
1066
1067 if (!isDeviceIdAttestationRequested(params)) {
1068 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001069 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001070 }
1071
1072 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1073 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
Yi Konge353f252018-07-30 01:38:39 -07001074 if (binder == nullptr) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001075 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001076 }
1077 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1078 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1079 IPCThreadState::self()->getCallingPid(), callingUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001080 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001081 }
1082
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001083 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001084 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1085 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001086 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001087 }
1088
1089 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001090 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001091
Shawn Willden70c1a782018-07-11 15:13:20 -06001092 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001093 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001094 }
1095
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001096
1097 AuthorizationSet keyCharacteristics;
1098 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1099 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1100 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1101 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1102 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001103
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001104 std::promise<KeyStoreServiceReturnCode> resultPromise;
1105 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001106
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001107 dev->generateKey(
1108 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001109 [cb, dev, CAPTURE_MOVE(mutableParams)](
1110 Return<void> rc,
1111 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001112 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1113 auto hidlKeyBlob = std::move(hidlKeyBlob_);
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 }
1118 if (ret != ErrorCode::OK) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001119 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001120 return;
1121 }
1122 dev->attestKey(
1123 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001124 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001125 hidlKeyBlob](Return<void> rc,
1126 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1127 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001128 // schedule temp key for deletion
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001129 dev->deleteKey(std::move(hidlKeyBlob), [](Return<ErrorCode> rc) {
1130 // log error but don't return an error
1131 KS_HANDLE_HIDL_ERROR(rc);
1132 });
1133 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001134 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001135 return;
1136 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001137 if (ret == ErrorCode::OK) {
1138 cb->onFinished(
1139 KeyStoreServiceReturnCode(ret),
1140 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1141 } else {
1142 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001143 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001144 });
1145 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001146
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001147 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001148}
1149
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001150Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001151 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001152 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001153 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1154 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001155}
1156
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001157Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001158 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001159 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1160 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1161 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001162 int32_t* _aidl_return) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001163
1164 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1165
1166 if (!checkBinderPermission(P_INSERT, callingUid)) {
1167 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1168 }
1169
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001170 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001171
1172 KeyStoreServiceReturnCode rc;
1173 Blob wrappingKeyBlob;
1174 Blob wrappingCharBlob;
1175 LockedKeyBlobEntry wrappingLockedEntry;
1176
1177 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1178 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
1179 if (!rc) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001180 return AIDL_RETURN(rc);
1181 }
1182
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001183 String8 wrappedKeyName8(wrappedKeyAlias);
1184 auto wrappedLockedEntry =
1185 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1186 if (!wrappedLockedEntry) {
1187 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1188 }
1189
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001190 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1191 auto dev = mKeyStore->getDevice(securityLevel);
1192 if (!dev) {
1193 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1194 }
1195
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001196 dev->importWrappedKey(
1197 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1198 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001199 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1200 cb->onFinished(rc,
1201 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001202 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001203
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001204 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001205}
1206
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001207Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1208 const String16& promptText,
1209 const ::std::vector<uint8_t>& extraData,
1210 const String16& locale, int32_t uiOptionsAsFlags,
1211 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001212 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1213 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001214}
1215
1216Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1217 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001218 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001219}
1220
David Zeuthen1a492312018-02-26 11:00:30 -05001221Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001222 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001223}
1224
1225/**
1226 * Get the effective target uid for a binder operation that takes an
1227 * optional uid as the target.
1228 */
1229uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1230 if (targetUid == UID_SELF) {
1231 return IPCThreadState::self()->getCallingUid();
1232 }
1233 return static_cast<uid_t>(targetUid);
1234}
1235
1236/**
1237 * Check if the caller of the current binder method has the required
1238 * permission and if acting on other uids the grants to do so.
1239 */
1240bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1241 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1242 pid_t spid = IPCThreadState::self()->getCallingPid();
1243 if (!has_permission(callingUid, permission, spid)) {
1244 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1245 return false;
1246 }
1247 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1248 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1249 return false;
1250 }
1251 return true;
1252}
1253
1254/**
1255 * Check if the caller of the current binder method has the required
1256 * permission and the target uid is the caller or the caller is system.
1257 */
1258bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1259 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1260 pid_t spid = IPCThreadState::self()->getCallingPid();
1261 if (!has_permission(callingUid, permission, spid)) {
1262 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1263 return false;
1264 }
1265 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1266}
1267
1268/**
1269 * Check if the caller of the current binder method has the required
1270 * permission or the target of the operation is the caller's uid. This is
1271 * for operation where the permission is only for cross-uid activity and all
1272 * uids are allowed to act on their own (ie: clearing all entries for a
1273 * given uid).
1274 */
1275bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1276 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1277 if (getEffectiveUid(targetUid) == callingUid) {
1278 return true;
1279 } else {
1280 return checkBinderPermission(permission, targetUid);
1281 }
1282}
1283
1284/**
1285 * Helper method to check that the caller has the required permission as
1286 * well as the keystore is in the unlocked state if checkUnlocked is true.
1287 *
1288 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1289 * otherwise the state of keystore when not unlocked and checkUnlocked is
1290 * true.
1291 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001292KeyStoreServiceReturnCode
1293KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1294 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001295 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001296 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001297 }
1298 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1299 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001300 // All State values coincide with ResponseCodes
1301 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001302 }
1303
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001304 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001305}
1306
1307bool KeyStoreService::isKeystoreUnlocked(State state) {
1308 switch (state) {
1309 case ::STATE_NO_ERROR:
1310 return true;
1311 case ::STATE_UNINITIALIZED:
1312 case ::STATE_LOCKED:
1313 return false;
1314 }
1315 return false;
1316}
1317
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001318/**
Shawn Willden0329a822017-12-04 13:55:14 -07001319 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1320 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001321 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001322bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1323 for (size_t i = 0; i < params.size(); ++i) {
1324 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001325 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001326 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001327 return false;
1328 default:
1329 break;
1330 }
1331 }
1332 return true;
1333}
1334
Brian Young9a947d52018-02-23 18:03:14 +00001335Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
1336 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001337 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Brian Young9a947d52018-02-23 18:03:14 +00001338 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001339
1340 return Status::ok();
1341}
1342
Shawn Willdene2a7b522017-04-11 09:27:40 -06001343} // namespace keystore