blob: 24bf3318df8703c3f298bd75fc6ba834768f0c2c [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;
259
260 std::tie(rc, internal_matches) = LockedKeyBlobEntry::list(
261 mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName(),
262 [&](uid_t uid, const std::string& alias) {
263 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
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700585Status 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)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700588 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
589 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700590 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000591 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700592
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700593 mKeyStore->removeAllGrantsToUid(targetUid);
594
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700595 ResponseCode rc;
596 std::list<LockedKeyBlobEntry> entries;
597
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(
601 mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName(),
602 [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
603
604 if (rc != ResponseCode::NO_ERROR) {
605 *aidl_return = static_cast<int32_t>(rc);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700606 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700607 }
608
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700609 for (LockedKeyBlobEntry& lockedEntry : entries) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100610 if (get_app_id(targetUid) == AID_SYSTEM) {
611 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700612 Blob charBlob;
613 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
614 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100615 // Do not clear keys critical to device encryption under system uid.
616 continue;
617 }
618 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700619 mKeyStore->del(lockedEntry);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700620 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700621 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
622 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700623}
624
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600625Status KeyStoreService::addRngEntropy(
626 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
627 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
Janis Danisevskisc1460142017-12-18 16:48:46 -0800628 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
629 if (!device) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600630 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800631 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700632
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600633 device->addRngEntropy(entropy, [cb](Return<ErrorCode> rc) {
634 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(rc)));
635 });
636
637 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700638}
639
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600640Status KeyStoreService::generateKey(
641 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
642 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
643 int uid, int flags, int32_t* _aidl_return) {
Max Biresef4f0672017-11-29 14:38:48 -0800644 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
645 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700646 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000647 auto logOnScopeExit = android::base::make_scope_guard([&] {
648 if (__android_log_security()) {
649 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600650 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000651 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
652 }
653 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100654 KeyStoreServiceReturnCode rc =
655 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
656 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600657 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700658 }
Rubin Xu67899de2017-04-21 19:15:13 +0100659 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
660 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600661 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100662 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700663
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700664 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700665 // TODO(jbires): remove uid checking upon implementation of b/25646100
Max Bires670467d2017-12-12 11:16:43 -0800666 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Biresef4f0672017-11-29 14:38:48 -0800667 originalUid != IPCThreadState::self()->getCallingUid()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600668 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700669 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600670 }
671
Janis Danisevskisc1460142017-12-18 16:48:46 -0800672 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
673 auto dev = mKeyStore->getDevice(securityLevel);
674 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600675 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800676 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400677
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100678 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700679 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
680 if (!lockedEntry) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600681 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100682 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400683
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700684 logOnScopeExit.Disable();
685
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600686 dev->generateKey(
687 std::move(lockedEntry), params.getParameters(), entropy, flags,
688 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
689 if (__android_log_security()) {
690 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
691 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
692 }
693 cb->onFinished(rc,
694 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
695 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700696
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600697 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700698}
699
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700700Status KeyStoreService::getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600701 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700702 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
Janis Danisevskis64ec1fe2018-02-26 16:47:21 -0800703 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600704 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700705
706 uid_t targetUid = getEffectiveUid(uid);
707 uid_t callingUid = IPCThreadState::self()->getCallingUid();
708 if (!is_granted_to(callingUid, targetUid)) {
709 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
710 targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600711 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700712 }
713
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700714 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700715
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700716 ResponseCode rc;
717 Blob keyBlob;
718 Blob charBlob;
719 LockedKeyBlobEntry lockedEntry;
Janis Danisevskisd714a672017-09-01 14:31:36 -0700720
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700721 std::tie(rc, keyBlob, charBlob, lockedEntry) =
722 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
723
724 if (rc != ResponseCode::NO_ERROR) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600725 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700726 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100727
Janis Danisevskisc1460142017-12-18 16:48:46 -0800728 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700729 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600730 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100731 }
732
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700733 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
734 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
735 // from keymaster. It may also upgrade the key blob.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700736 dev->getKeyCharacteristics(
737 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
738 std::move(charBlob),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600739 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
740 cb->onFinished(rc,
741 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700742 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100743
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600744 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700745}
746
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600747Status KeyStoreService::importKey(
748 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
749 const String16& name, const KeymasterArguments& params, int32_t format,
750 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700751 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000752 auto logOnScopeExit = android::base::make_scope_guard([&] {
753 if (__android_log_security()) {
754 android_log_event_list(SEC_TAG_KEY_IMPORTED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600755 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000756 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
757 }
758 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100759 KeyStoreServiceReturnCode rc =
760 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
761 if (!rc.isOk()) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700762 LOG(ERROR) << "permissission denied";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600763 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700764 }
Rubin Xu67899de2017-04-21 19:15:13 +0100765 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
766 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600767 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100768 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700769
Janis Danisevskisc1460142017-12-18 16:48:46 -0800770 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
771 auto dev = mKeyStore->getDevice(securityLevel);
772 if (!dev) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700773 LOG(ERROR) << "importKey - cound not get keymaster device";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600774 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800775 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700776
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700777 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700778 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
779 if (!lockedEntry) {
780 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
781 << " already exists.";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600782 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400783 }
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700784
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700785 logOnScopeExit.Disable();
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700786
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600787 dev->importKey(
788 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
789 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
790 if (__android_log_security()) {
791 android_log_event_list(SEC_TAG_KEY_IMPORTED)
792 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
793 }
794 cb->onFinished(rc,
795 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
796 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400797
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600798 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700799}
800
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600801Status KeyStoreService::exportKey(
802 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
803 const String16& name, int32_t format,
804 const ::android::security::keymaster::KeymasterBlob& clientId,
805 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
806 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700807
808 uid_t targetUid = getEffectiveUid(uid);
809 uid_t callingUid = IPCThreadState::self()->getCallingUid();
810 if (!is_granted_to(callingUid, targetUid)) {
811 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600812 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700813 }
814
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700815 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700816
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700817 KeyStoreServiceReturnCode rc;
818 Blob keyBlob;
819 Blob charBlob;
820 LockedKeyBlobEntry lockedEntry;
821
822 std::tie(rc, keyBlob, charBlob, lockedEntry) =
823 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
824 if (!rc) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600825 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700826 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100827
Janis Danisevskisc1460142017-12-18 16:48:46 -0800828 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100829
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700830 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600831 std::move(keyBlob), std::move(charBlob),
832 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
Ji Wang2c142312016-10-14 17:21:10 +0800833
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600834 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700835}
836
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600837Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
838 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700839 bool pruneable, const KeymasterArguments& params,
840 const ::std::vector<uint8_t>& entropy, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600841 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700842 uid_t callingUid = IPCThreadState::self()->getCallingUid();
843 uid_t targetUid = getEffectiveUid(uid);
844 if (!is_granted_to(callingUid, targetUid)) {
845 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600846 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700847 }
848 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
849 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600850 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700851 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700852 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600853 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700854 }
Shawn Willden0329a822017-12-04 13:55:14 -0700855
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700856 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700857 Blob keyBlob;
858 Blob charBlob;
859 LockedKeyBlobEntry lockedEntry;
860 ResponseCode rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100861
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700862 std::tie(rc, keyBlob, charBlob, lockedEntry) =
863 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
864
865 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600866 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700867 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600868 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700869
Janis Danisevskisc1460142017-12-18 16:48:46 -0800870 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700871 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100872
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700873 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
874 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600875 [this, cb, dev](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700876 if (result_.resultCode.isOk() ||
877 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
878 addOperationDevice(result_.token, dev);
879 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600880 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700881 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400882
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600883 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700884}
885
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600886Status KeyStoreService::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
887 const ::android::sp<::android::IBinder>& token,
888 const ::android::security::keymaster::KeymasterArguments& params,
889 const ::std::vector<uint8_t>& input, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700890 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600891 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700892 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700893
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700894 auto dev = getOperationDevice(token);
895 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600896 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700897 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700898
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600899 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700900 if (!result_.resultCode.isOk()) {
901 removeOperationDevice(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100902 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600903 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700904 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100905
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600906 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700907}
908
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600909Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
910 const ::android::sp<::android::IBinder>& token,
911 const ::android::security::keymaster::KeymasterArguments& params,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700912 const ::std::vector<uint8_t>& signature,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600913 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700914 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600915 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700916 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700917
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700918 auto dev = getOperationDevice(token);
919 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600920 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700921 }
922
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700923 dev->finish(token, params.getParameters(), {}, signature, entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600924 [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700925 if (!result_.resultCode.isOk()) {
926 removeOperationDevice(token);
927 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600928 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700929 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700930
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600931 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700932}
933
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600934Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
935 const ::android::sp<::android::IBinder>& token,
936 int32_t* _aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700937 auto dev = getOperationDevice(token);
938 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600939 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700940 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100941
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600942 dev->abort(token, [cb](KeyStoreServiceReturnCode rc) { cb->onFinished(rc); });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700943
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600944 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700945}
946
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700947Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000948 int32_t* aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700949
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000950 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
951 // receive a HardwareAuthToken, rather than an opaque byte array.
952
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700953 if (!checkBinderPermission(P_ADD_AUTH)) {
954 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700955 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
956 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700957 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700958 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
959 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
960 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000961 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100962
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000963 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700964 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000965 if (authToken.version != 0) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700966 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
967 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000968 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100969
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700970 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
971 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700972 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
973 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700974}
975
Rubin Xu1a203e32018-05-08 14:25:21 +0100976int isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -0700977 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Rubin Xu1a203e32018-05-08 14:25:21 +0100978 int result = 0;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700979 for (size_t i = 0; i < paramsVec.size(); ++i) {
980 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -0600981 case Tag::ATTESTATION_ID_BRAND:
982 case Tag::ATTESTATION_ID_DEVICE:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600983 case Tag::ATTESTATION_ID_MANUFACTURER:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600984 case Tag::ATTESTATION_ID_MODEL:
985 case Tag::ATTESTATION_ID_PRODUCT:
Rubin Xu1a203e32018-05-08 14:25:21 +0100986 result |= ID_ATTESTATION_REQUEST_GENERIC_INFO;
Shawn Willdene2a7b522017-04-11 09:27:40 -0600987 break;
Rubin Xu1a203e32018-05-08 14:25:21 +0100988 case Tag::ATTESTATION_ID_IMEI:
989 case Tag::ATTESTATION_ID_MEID:
990 case Tag::ATTESTATION_ID_SERIAL:
991 result |= ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID;
992 break;
993 default:
994 continue;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100995 }
996 }
Rubin Xu1a203e32018-05-08 14:25:21 +0100997 return result;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100998}
999
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001000Status KeyStoreService::attestKey(
1001 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1002 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001003 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1004 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001005 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001006 }
1007
Eran Messerie2c34152017-12-21 21:01:22 +00001008 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1009
Rubin Xu1a203e32018-05-08 14:25:21 +01001010 int needsIdAttestation = isDeviceIdAttestationRequested(params);
1011 bool needsUniqueIdAttestation = needsIdAttestation & ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID;
1012 bool isPrimaryUserSystemUid = (callingUid == AID_SYSTEM);
1013 bool isSomeUserSystemUid = (get_app_id(callingUid) == AID_SYSTEM);
1014 // Allow system context from any user to request attestation with basic device information,
1015 // while only allow system context from user 0 (device owner) to request attestation with
1016 // unique device ID.
1017 if ((needsIdAttestation && !isSomeUserSystemUid) ||
1018 (needsUniqueIdAttestation && !isPrimaryUserSystemUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001019 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001020 }
1021
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001022 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001023 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1024 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001025 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001026 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001027
Shawn Willden50eb1b22016-01-21 12:41:23 -07001028 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001029 Blob keyBlob;
1030 Blob charBlob;
1031 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001032
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001033 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1034 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1035
Janis Danisevskisc1460142017-12-18 16:48:46 -08001036 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001037 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001038 dev->attestKey(
1039 std::move(hidlKey), mutableParams.hidl_data(),
1040 [cb](Return<void> rc, std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1041 auto& [ret, certChain] = hidlResult;
1042 if (!rc.isOk()) {
1043 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1044 } else if (ret != ErrorCode::OK) {
1045 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1046 } else {
1047 cb->onFinished(KeyStoreServiceReturnCode(ret),
1048 KeymasterCertificateChain(std::move(certChain)));
1049 }
1050 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001051
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001052 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001053}
1054
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001055// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1056// It should never be redefined by a build system though.
1057#ifndef CAPTURE_MOVE
1058#define CAPTURE_MOVE(x) x = std::move(x)
1059#endif
1060
1061Status KeyStoreService::attestDeviceIds(
1062 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1063 const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001064 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001065
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001066 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001067 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001068 }
1069
1070 if (!isDeviceIdAttestationRequested(params)) {
1071 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001072 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001073 }
1074
1075 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1076 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
Yi Konge353f252018-07-30 01:38:39 -07001077 if (binder == nullptr) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001078 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001079 }
1080 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1081 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1082 IPCThreadState::self()->getCallingPid(), callingUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001083 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001084 }
1085
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001086 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001087 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1088 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001089 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001090 }
1091
1092 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001093 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001094
Shawn Willden70c1a782018-07-11 15:13:20 -06001095 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001096 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001097 }
1098
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001099
1100 AuthorizationSet keyCharacteristics;
1101 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1102 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1103 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1104 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1105 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001106
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001107 std::promise<KeyStoreServiceReturnCode> resultPromise;
1108 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001109
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001110 dev->generateKey(
1111 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001112 [cb, dev, CAPTURE_MOVE(mutableParams)](
1113 Return<void> rc,
1114 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001115 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1116 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1117 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001118 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001119 return;
1120 }
1121 if (ret != ErrorCode::OK) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001122 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001123 return;
1124 }
1125 dev->attestKey(
1126 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001127 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001128 hidlKeyBlob](Return<void> rc,
1129 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1130 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001131 // schedule temp key for deletion
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001132 dev->deleteKey(std::move(hidlKeyBlob), [](Return<ErrorCode> rc) {
1133 // log error but don't return an error
1134 KS_HANDLE_HIDL_ERROR(rc);
1135 });
1136 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001137 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001138 return;
1139 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001140 if (ret == ErrorCode::OK) {
1141 cb->onFinished(
1142 KeyStoreServiceReturnCode(ret),
1143 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1144 } else {
1145 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001146 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001147 });
1148 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001149
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001150 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001151}
1152
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001153Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001154 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001155 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001156 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1157 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001158}
1159
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001160Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001161 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001162 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1163 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1164 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001165 int32_t* _aidl_return) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001166
1167 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1168
1169 if (!checkBinderPermission(P_INSERT, callingUid)) {
1170 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1171 }
1172
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001173 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001174
1175 KeyStoreServiceReturnCode rc;
1176 Blob wrappingKeyBlob;
1177 Blob wrappingCharBlob;
1178 LockedKeyBlobEntry wrappingLockedEntry;
1179
1180 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1181 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
1182 if (!rc) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001183 return AIDL_RETURN(rc);
1184 }
1185
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001186 String8 wrappedKeyName8(wrappedKeyAlias);
1187 auto wrappedLockedEntry =
1188 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1189 if (!wrappedLockedEntry) {
1190 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1191 }
1192
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001193 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1194 auto dev = mKeyStore->getDevice(securityLevel);
1195 if (!dev) {
1196 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1197 }
1198
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001199 dev->importWrappedKey(
1200 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1201 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001202 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1203 cb->onFinished(rc,
1204 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001205 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001206
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001207 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001208}
1209
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001210Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1211 const String16& promptText,
1212 const ::std::vector<uint8_t>& extraData,
1213 const String16& locale, int32_t uiOptionsAsFlags,
1214 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001215 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1216 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001217}
1218
1219Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1220 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001221 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001222}
1223
David Zeuthen1a492312018-02-26 11:00:30 -05001224Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001225 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001226}
1227
1228/**
1229 * Get the effective target uid for a binder operation that takes an
1230 * optional uid as the target.
1231 */
1232uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1233 if (targetUid == UID_SELF) {
1234 return IPCThreadState::self()->getCallingUid();
1235 }
1236 return static_cast<uid_t>(targetUid);
1237}
1238
1239/**
1240 * Check if the caller of the current binder method has the required
1241 * permission and if acting on other uids the grants to do so.
1242 */
1243bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1244 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1245 pid_t spid = IPCThreadState::self()->getCallingPid();
1246 if (!has_permission(callingUid, permission, spid)) {
1247 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1248 return false;
1249 }
1250 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1251 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1252 return false;
1253 }
1254 return true;
1255}
1256
1257/**
1258 * Check if the caller of the current binder method has the required
1259 * permission and the target uid is the caller or the caller is system.
1260 */
1261bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1262 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1263 pid_t spid = IPCThreadState::self()->getCallingPid();
1264 if (!has_permission(callingUid, permission, spid)) {
1265 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1266 return false;
1267 }
1268 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1269}
1270
1271/**
1272 * Check if the caller of the current binder method has the required
1273 * permission or the target of the operation is the caller's uid. This is
1274 * for operation where the permission is only for cross-uid activity and all
1275 * uids are allowed to act on their own (ie: clearing all entries for a
1276 * given uid).
1277 */
1278bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1279 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1280 if (getEffectiveUid(targetUid) == callingUid) {
1281 return true;
1282 } else {
1283 return checkBinderPermission(permission, targetUid);
1284 }
1285}
1286
1287/**
1288 * Helper method to check that the caller has the required permission as
1289 * well as the keystore is in the unlocked state if checkUnlocked is true.
1290 *
1291 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1292 * otherwise the state of keystore when not unlocked and checkUnlocked is
1293 * true.
1294 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001295KeyStoreServiceReturnCode
1296KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1297 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001298 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001299 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001300 }
1301 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1302 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001303 // All State values coincide with ResponseCodes
1304 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001305 }
1306
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001307 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001308}
1309
1310bool KeyStoreService::isKeystoreUnlocked(State state) {
1311 switch (state) {
1312 case ::STATE_NO_ERROR:
1313 return true;
1314 case ::STATE_UNINITIALIZED:
1315 case ::STATE_LOCKED:
1316 return false;
1317 }
1318 return false;
1319}
1320
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001321/**
Shawn Willden0329a822017-12-04 13:55:14 -07001322 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1323 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001324 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001325bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1326 for (size_t i = 0; i < params.size(); ++i) {
1327 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001328 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001329 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001330 return false;
1331 default:
1332 break;
1333 }
1334 }
1335 return true;
1336}
1337
Brian Young9a947d52018-02-23 18:03:14 +00001338Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
1339 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001340 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Brian Young9a947d52018-02-23 18:03:14 +00001341 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001342
1343 return Status::ok();
1344}
1345
Shawn Willdene2a7b522017-04-11 09:27:40 -06001346} // namespace keystore