blob: 2f1784881d7233e69eabac8e93b9409950eb8da8 [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
Branden Archer70080742018-11-20 11:04:11 -080086#define AIDL_RETURN(rc) (*_aidl_return = KeyStoreServiceReturnCode(rc).getErrorCode(), Status::ok())
Rob Barnesbb6cabd2018-10-04 17:10:37 -060087
Shawn Willdene2a7b522017-04-11 09:27:40 -060088std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
89 struct stat sbuf;
90 if (stat(kTimestampFilePath, &sbuf) == 0) {
Yi Konge353f252018-07-30 01:38:39 -070091 double diff_secs = difftime(time(nullptr), sbuf.st_ctime);
Shawn Willdene2a7b522017-04-11 09:27:40 -060092 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
93 }
94
95 if (errno != ENOENT) {
96 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
97 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
98 }
99
100 int fd = creat(kTimestampFilePath, 0600);
101 if (fd < 0) {
102 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
103 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
104 }
105
106 if (close(fd)) {
107 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
108 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
109 }
110
111 return {ResponseCode::NO_ERROR, true};
112}
113
Eran Messeri03fc4c82018-08-16 18:53:15 +0100114using ::android::security::KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200115
116KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
117 KeyStoreServiceReturnCode responseCode;
118 bool factoryResetSinceIdRotation;
119 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
120
121 if (!responseCode.isOk()) return responseCode;
122 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
123
124 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
125 if (!asn1_attestation_id_result.isOk()) {
126 ALOGE("failed to gather attestation_id");
127 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
128 }
129 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
130
131 /*
Eran Messeri03fc4c82018-08-16 18:53:15 +0100132 * The attestation application ID must not be longer than
133 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, error out if gather_attestation_application_id
134 * returned such an invalid vector.
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200135 */
136 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Eran Messeri03fc4c82018-08-16 18:53:15 +0100137 ALOGE("BUG: Gathered Attestation Application ID is too big (%d)",
138 static_cast<int32_t>(asn1_attestation_id.size()));
139 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200140 }
141
142 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
143
144 return ResponseCode::NO_ERROR;
145}
146
Shawn Willdene2a7b522017-04-11 09:27:40 -0600147} // anonymous namespace
148
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700149Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700150 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700151 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
152 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700153 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700154 *aidl_return = mKeyStore->getState(userId);
155 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700156}
157
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700158Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700159 uid_t targetUid = getEffectiveUid(uid);
160 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700161 // see keystore/keystore.h
162 return Status::fromServiceSpecificError(
163 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700164 }
165
166 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700167 ResponseCode rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700168 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700169 Blob charBlob;
170 LockedKeyBlobEntry lockedEntry;
171
172 std::tie(rc, keyBlob, charBlob, lockedEntry) =
173 mKeyStore->getKeyForName(name8, targetUid, TYPE_GENERIC);
174 if (rc != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700175 *item = ::std::vector<uint8_t>();
176 // Return empty array if key is not found
177 // TODO: consider having returned value nullable or parse exception on the client.
178 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700179 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100180 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700181 // The static_cast here is needed to prevent a move, forcing a deep copy.
182 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
183 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700184}
185
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700186Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
187 int targetUid, int32_t flags, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700188 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700189 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700190 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100191 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800192 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700193 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700194 }
195
196 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700197 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), targetUid);
198
199 if (!lockedEntry) {
200 ALOGE("failed to grab lock on blob entry %u_%s", targetUid, name8.string());
201 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_ALREADY_EXISTS);
202 return Status::ok();
203 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700204
Yi Konge353f252018-07-30 01:38:39 -0700205 Blob keyBlob(&item[0], item.size(), nullptr, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700206 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
207
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700208 *aidl_return = static_cast<int32_t>(mKeyStore->put(lockedEntry, keyBlob, {}));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700209 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700210}
211
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700212Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700213 targetUid = getEffectiveUid(targetUid);
214 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700215 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
216 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700217 }
218 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000219 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700220 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
221 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700222 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
223 return Status::ok();
224 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700225
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700226 ResponseCode result = mKeyStore->del(lockedEntry);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400227
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700228 *aidl_return = static_cast<int32_t>(result);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700229 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700230}
231
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700232Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700233 targetUid = getEffectiveUid(targetUid);
234 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700235 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
236 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700237 }
238
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700239 LockedKeyBlobEntry lockedEntry =
240 mKeyStore->getLockedBlobEntryIfExists(String8(name).string(), targetUid);
241 *aidl_return =
242 static_cast<int32_t>(lockedEntry ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700243 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700244}
245
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700246Status KeyStoreService::list(const String16& prefix, int32_t targetUid,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700247 ::std::vector<::android::String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700248 targetUid = getEffectiveUid(targetUid);
249 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700250 return Status::fromServiceSpecificError(
251 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700252 }
253 const String8 prefix8(prefix);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700254 const std::string stdPrefix(prefix8.string());
255
256 ResponseCode rc;
257 std::list<LockedKeyBlobEntry> internal_matches;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800258 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700259
Janis Danisevskis265435f2018-11-16 14:10:46 -0800260 std::tie(rc, internal_matches) =
261 LockedKeyBlobEntry::list(userDirName, [&](uid_t uid, const std::string& alias) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700262 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end());
263 return uid == static_cast<uid_t>(targetUid) &&
264 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end())
265 .first == stdPrefix.end();
266 });
267
268 if (rc != ResponseCode::NO_ERROR) {
269 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700270 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700271
272 for (LockedKeyBlobEntry& entry : internal_matches) {
273 matches->push_back(String16(entry->alias().substr(prefix8.size()).c_str()));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700274 }
275 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700276}
277
Rob Barneseb7f79b2018-11-08 15:44:10 -0700278/*
279 * This method will return the uids of all auth bound keys for the calling user.
280 * This is intended to be used for alerting the user about which apps will be affected
281 * if the password/pin is removed. Only allowed to be called by system.
282 * The output is bound by the initial size of uidsOut to be compatible with Java.
283 */
284Status KeyStoreService::listUidsOfAuthBoundKeys(::std::vector<int32_t>* uidsOut,
285 int32_t* aidl_return) {
286 const int32_t callingUid = IPCThreadState::self()->getCallingUid();
287 const int32_t userId = get_user_id(callingUid);
288 const int32_t appId = get_app_id(callingUid);
289 if (appId != AID_SYSTEM) {
290 ALOGE("Permission listUidsOfAuthBoundKeys denied for aid %d", appId);
291 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
292 return Status::ok();
293 }
294
295 const String8 prefix8("");
296 auto userState = mKeyStore->getUserStateDB().getUserState(userId);
297 const std::string userDirName = userState->getUserDirName();
298 auto encryptionKey = userState->getEncryptionKey();
299 auto state = userState->getState();
300 // unlock the user state
301 userState = {};
302
303 ResponseCode rc;
304 std::list<LockedKeyBlobEntry> internal_matches;
305 std::tie(rc, internal_matches) =
306 LockedKeyBlobEntry::list(userDirName, [&](uid_t, const std::string&) {
307 // Need to filter on auth bound state, so just return true.
308 return true;
309 });
310 if (rc != ResponseCode::NO_ERROR) {
311 ALOGE("Error listing blob entries for user %d", userId);
312 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
313 }
314
315 auto it = uidsOut->begin();
316 for (LockedKeyBlobEntry& entry : internal_matches) {
317 if (it == uidsOut->end()) {
318 ALOGW("Maximum number (%d) of auth bound uids found, truncating remainder",
319 static_cast<int32_t>(uidsOut->capacity()));
320 break;
321 }
322 if (std::find(uidsOut->begin(), it, entry->uid()) != it) {
323 // uid already in list, skip
324 continue;
325 }
326
327 auto [rc, blob, charBlob] = entry.readBlobs(encryptionKey, state);
328 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::LOCKED) {
329 ALOGE("Error reading blob for key %s", entry->alias().c_str());
330 continue;
331 }
332
333 if (blob && blob.isEncrypted()) {
334 *it++ = entry->uid();
335 } else if (charBlob) {
336 auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
337 if (!success) {
338 ALOGE("Error reading blob characteristics for key %s", entry->alias().c_str());
339 continue;
340 }
341 if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
342 swEnforced.Contains(TAG_USER_SECURE_ID)) {
343 *it++ = entry->uid();
344 }
345 }
346 }
347 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
348 return Status::ok();
349}
350
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700351Status KeyStoreService::reset(int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700352 if (!checkBinderPermission(P_RESET)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700353 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
354 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700355 }
356
357 uid_t callingUid = IPCThreadState::self()->getCallingUid();
358 mKeyStore->resetUser(get_user_id(callingUid), false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700359 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
360 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700361}
362
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700363Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
364 int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700365 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700366 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
367 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700368 }
369
370 const String8 password8(password);
371 // Flush the auth token table to prevent stale tokens from sticking
372 // around.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700373 mKeyStore->getAuthTokenTable().Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700374
375 if (password.size() == 0) {
376 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
377 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700378 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
379 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700380 } else {
381 switch (mKeyStore->getState(userId)) {
382 case ::STATE_UNINITIALIZED: {
383 // generate master key, encrypt with password, write to file,
384 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700385 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
386 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700387 }
388 case ::STATE_NO_ERROR: {
389 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700390 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
391 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700392 }
393 case ::STATE_LOCKED: {
394 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
395 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700396 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
397 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700398 }
399 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700400 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
401 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700402 }
403}
404
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700405Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700406 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700407 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
408 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700409 }
410
411 // Sanity check that the new user has an empty keystore.
412 if (!mKeyStore->isEmpty(userId)) {
413 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
414 }
415 // Unconditionally clear the keystore, just to be safe.
416 mKeyStore->resetUser(userId, false);
417 if (parentId != -1) {
418 // This profile must share the same master key password as the parent profile. Because the
419 // password of the parent profile is not known here, the best we can do is copy the parent's
420 // master key and master key file. This makes this profile use the same master key as the
421 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700422 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
423 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700424 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700425 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
426 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700427 }
428}
429
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700430Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700431 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700432 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
433 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700434 }
435
436 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700437 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
438 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700439}
440
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700441Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700442 if (!checkBinderPermission(P_LOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700443 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
444 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700445 }
446
447 State state = mKeyStore->getState(userId);
448 if (state != ::STATE_NO_ERROR) {
449 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700450 *aidl_return = static_cast<int32_t>(ResponseCode(state));
451 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700452 }
453
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700454 mKeyStore->getEnforcementPolicy().set_device_locked(true, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700455 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700456 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
457 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700458}
459
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700460Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700461 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700462 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
463 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700464 }
465
466 State state = mKeyStore->getState(userId);
467 if (state != ::STATE_LOCKED) {
468 switch (state) {
469 case ::STATE_NO_ERROR:
470 ALOGI("calling unlock when already unlocked, ignoring.");
471 break;
472 case ::STATE_UNINITIALIZED:
473 ALOGE("unlock called on uninitialized keystore.");
474 break;
475 default:
476 ALOGE("unlock called on keystore in unknown state: %d", state);
477 break;
478 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700479 *aidl_return = static_cast<int32_t>(ResponseCode(state));
480 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700481 }
482
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700483 mKeyStore->getEnforcementPolicy().set_device_locked(false, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700484 const String8 password8(pw);
485 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700486 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
487 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700488}
489
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700490Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700491 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700492 *aidl_return = static_cast<int32_t>(false);
493 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700494 }
495
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700496 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
497 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700498}
499
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700500Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
501 ::android::String16* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700502 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700503 auto result =
504 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100505 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700506 *aidl_return = String16();
507 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700508 }
509
510 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700511 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
512 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700513 *aidl_return = String16();
514 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700515 }
516
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700517 *aidl_return = String16(mKeyStore->addGrant(lockedEntry, granteeUid).c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700518 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700519}
520
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700521Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700522 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700523 KeyStoreServiceReturnCode result =
524 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100525 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800526 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700527 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700528 }
529
530 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700531
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700532 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
533 if (!lockedEntry) {
534 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700535 }
536
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700537 *aidl_return = mKeyStore->removeGrant(lockedEntry, granteeUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700538 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700539}
540
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700541Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700542 uid_t targetUid = getEffectiveUid(uid);
543 if (!checkBinderPermission(P_GET, targetUid)) {
544 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700545 *time = -1L;
546 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700547 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700548 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700549
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700550 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
551 if (!lockedEntry) {
552 ALOGW("could not access key with alias %s for getmtime", name8.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700553 *time = -1L;
554 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700555 }
556
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700557 std::string filename = lockedEntry->getKeyBlobPath();
558
559 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700560 if (fd < 0) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700561 ALOGW("could not open %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700562 *time = -1L;
563 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700564 }
565
566 struct stat s;
567 int ret = fstat(fd, &s);
568 close(fd);
569 if (ret == -1) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700570 ALOGW("could not stat %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700571 *time = -1L;
572 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700573 }
574
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700575 *time = static_cast<int64_t>(s.st_mtime);
576 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700577}
578
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700579Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
580 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
581 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700582}
583
Janis Danisevskis265435f2018-11-16 14:10:46 -0800584Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700585 uid_t targetUid = getEffectiveUid(targetUid64);
586 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800587 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700588 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000589 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700590
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700591 mKeyStore->removeAllGrantsToUid(targetUid);
592
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700593 ResponseCode rc;
594 std::list<LockedKeyBlobEntry> entries;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800595 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700596
597 // list has a fence making sure no workers are modifying blob files before iterating the
598 // data base. All returned entries are locked.
599 std::tie(rc, entries) = LockedKeyBlobEntry::list(
Janis Danisevskis265435f2018-11-16 14:10:46 -0800600 userDirName, [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700601
602 if (rc != ResponseCode::NO_ERROR) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800603 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700604 }
605
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700606 for (LockedKeyBlobEntry& lockedEntry : entries) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100607 if (get_app_id(targetUid) == AID_SYSTEM) {
608 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700609 Blob charBlob;
610 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
611 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100612 // Do not clear keys critical to device encryption under system uid.
613 continue;
614 }
615 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700616 mKeyStore->del(lockedEntry);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700617 }
Janis Danisevskis265435f2018-11-16 14:10:46 -0800618 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700619}
620
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600621Status KeyStoreService::addRngEntropy(
622 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
623 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
Janis Danisevskisc1460142017-12-18 16:48:46 -0800624 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
625 if (!device) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600626 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800627 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700628
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600629 device->addRngEntropy(entropy, [cb](Return<ErrorCode> rc) {
630 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(rc)));
631 });
632
633 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700634}
635
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600636Status KeyStoreService::generateKey(
637 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
638 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
639 int uid, int flags, int32_t* _aidl_return) {
Max Biresef4f0672017-11-29 14:38:48 -0800640 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
641 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700642 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000643 auto logOnScopeExit = android::base::make_scope_guard([&] {
644 if (__android_log_security()) {
645 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600646 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000647 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
648 }
649 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100650 KeyStoreServiceReturnCode rc =
651 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
652 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600653 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700654 }
Rubin Xu67899de2017-04-21 19:15:13 +0100655 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
656 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600657 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100658 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700659
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700660 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700661 // TODO(jbires): remove uid checking upon implementation of b/25646100
Max Bires670467d2017-12-12 11:16:43 -0800662 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Biresef4f0672017-11-29 14:38:48 -0800663 originalUid != IPCThreadState::self()->getCallingUid()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600664 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700665 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600666 }
667
Janis Danisevskisc1460142017-12-18 16:48:46 -0800668 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
669 auto dev = mKeyStore->getDevice(securityLevel);
670 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600671 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800672 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400673
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100674 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700675 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
676 if (!lockedEntry) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600677 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100678 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400679
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700680 logOnScopeExit.Disable();
681
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600682 dev->generateKey(
683 std::move(lockedEntry), params.getParameters(), entropy, flags,
684 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
685 if (__android_log_security()) {
686 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
687 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
688 }
689 cb->onFinished(rc,
690 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
691 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700692
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600693 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700694}
695
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700696Status KeyStoreService::getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600697 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700698 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
Janis Danisevskis64ec1fe2018-02-26 16:47:21 -0800699 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600700 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700701
702 uid_t targetUid = getEffectiveUid(uid);
703 uid_t callingUid = IPCThreadState::self()->getCallingUid();
704 if (!is_granted_to(callingUid, targetUid)) {
705 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
706 targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600707 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700708 }
709
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700710 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700711
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700712 ResponseCode rc;
713 Blob keyBlob;
714 Blob charBlob;
715 LockedKeyBlobEntry lockedEntry;
Janis Danisevskisd714a672017-09-01 14:31:36 -0700716
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700717 std::tie(rc, keyBlob, charBlob, lockedEntry) =
718 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
719
720 if (rc != ResponseCode::NO_ERROR) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600721 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700722 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100723
Janis Danisevskisc1460142017-12-18 16:48:46 -0800724 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700725 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600726 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100727 }
728
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700729 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
730 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
731 // from keymaster. It may also upgrade the key blob.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700732 dev->getKeyCharacteristics(
733 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
734 std::move(charBlob),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600735 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
736 cb->onFinished(rc,
737 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700738 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100739
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600740 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700741}
742
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600743Status KeyStoreService::importKey(
744 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
745 const String16& name, const KeymasterArguments& params, int32_t format,
746 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700747 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000748 auto logOnScopeExit = android::base::make_scope_guard([&] {
749 if (__android_log_security()) {
750 android_log_event_list(SEC_TAG_KEY_IMPORTED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600751 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000752 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
753 }
754 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100755 KeyStoreServiceReturnCode rc =
756 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
757 if (!rc.isOk()) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700758 LOG(ERROR) << "permissission denied";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600759 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700760 }
Rubin Xu67899de2017-04-21 19:15:13 +0100761 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
762 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600763 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100764 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700765
Janis Danisevskisc1460142017-12-18 16:48:46 -0800766 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
767 auto dev = mKeyStore->getDevice(securityLevel);
768 if (!dev) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700769 LOG(ERROR) << "importKey - cound not get keymaster device";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600770 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800771 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700772
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700773 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700774 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
775 if (!lockedEntry) {
776 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
777 << " already exists.";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600778 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400779 }
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700780
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700781 logOnScopeExit.Disable();
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700782
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600783 dev->importKey(
784 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
785 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
786 if (__android_log_security()) {
787 android_log_event_list(SEC_TAG_KEY_IMPORTED)
788 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
789 }
790 cb->onFinished(rc,
791 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
792 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400793
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600794 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700795}
796
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600797Status KeyStoreService::exportKey(
798 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
799 const String16& name, int32_t format,
800 const ::android::security::keymaster::KeymasterBlob& clientId,
801 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
802 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700803
804 uid_t targetUid = getEffectiveUid(uid);
805 uid_t callingUid = IPCThreadState::self()->getCallingUid();
806 if (!is_granted_to(callingUid, targetUid)) {
807 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600808 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700809 }
810
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700811 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700812
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700813 KeyStoreServiceReturnCode rc;
814 Blob keyBlob;
815 Blob charBlob;
816 LockedKeyBlobEntry lockedEntry;
817
818 std::tie(rc, keyBlob, charBlob, lockedEntry) =
819 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskis3cf85322018-11-19 13:37:49 -0800820 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600821 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700822 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100823
Janis Danisevskisc1460142017-12-18 16:48:46 -0800824 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100825
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700826 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600827 std::move(keyBlob), std::move(charBlob),
828 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
Ji Wang2c142312016-10-14 17:21:10 +0800829
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600830 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700831}
832
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600833Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
834 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700835 bool pruneable, const KeymasterArguments& params,
836 const ::std::vector<uint8_t>& entropy, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600837 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700838 uid_t callingUid = IPCThreadState::self()->getCallingUid();
839 uid_t targetUid = getEffectiveUid(uid);
840 if (!is_granted_to(callingUid, targetUid)) {
841 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600842 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700843 }
844 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
845 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600846 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700847 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700848 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600849 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700850 }
Shawn Willden0329a822017-12-04 13:55:14 -0700851
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700852 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700853 Blob keyBlob;
854 Blob charBlob;
855 LockedKeyBlobEntry lockedEntry;
856 ResponseCode rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100857
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700858 std::tie(rc, keyBlob, charBlob, lockedEntry) =
859 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
860
861 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600862 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700863 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600864 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700865
Janis Danisevskisc1460142017-12-18 16:48:46 -0800866 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700867 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100868
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700869 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
870 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600871 [this, cb, dev](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700872 if (result_.resultCode.isOk() ||
873 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
874 addOperationDevice(result_.token, dev);
875 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600876 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700877 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400878
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600879 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700880}
881
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600882Status KeyStoreService::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
883 const ::android::sp<::android::IBinder>& token,
884 const ::android::security::keymaster::KeymasterArguments& params,
885 const ::std::vector<uint8_t>& input, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700886 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600887 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700888 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700889
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700890 auto dev = getOperationDevice(token);
891 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600892 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700893 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700894
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600895 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700896 if (!result_.resultCode.isOk()) {
897 removeOperationDevice(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100898 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600899 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700900 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100901
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600902 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700903}
904
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600905Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
906 const ::android::sp<::android::IBinder>& token,
907 const ::android::security::keymaster::KeymasterArguments& params,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700908 const ::std::vector<uint8_t>& signature,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600909 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700910 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600911 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700912 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700913
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700914 auto dev = getOperationDevice(token);
915 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600916 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700917 }
918
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700919 dev->finish(token, params.getParameters(), {}, signature, entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600920 [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700921 if (!result_.resultCode.isOk()) {
922 removeOperationDevice(token);
923 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600924 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700925 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700926
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600927 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700928}
929
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600930Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
931 const ::android::sp<::android::IBinder>& token,
932 int32_t* _aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700933 auto dev = getOperationDevice(token);
934 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600935 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700936 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100937
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600938 dev->abort(token, [cb](KeyStoreServiceReturnCode rc) { cb->onFinished(rc); });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700939
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600940 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700941}
942
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700943Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000944 int32_t* aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700945
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000946 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
947 // receive a HardwareAuthToken, rather than an opaque byte array.
948
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700949 if (!checkBinderPermission(P_ADD_AUTH)) {
950 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700951 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
952 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700953 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700954 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
Branden Archer70080742018-11-20 11:04:11 -0800955 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700956 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000957 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100958
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000959 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700960 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000961 if (authToken.version != 0) {
Branden Archer70080742018-11-20 11:04:11 -0800962 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700963 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000964 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100965
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700966 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
967 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700968 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
969 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700970}
971
Rubin Xu1a203e32018-05-08 14:25:21 +0100972int isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -0700973 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Rubin Xu1a203e32018-05-08 14:25:21 +0100974 int result = 0;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700975 for (size_t i = 0; i < paramsVec.size(); ++i) {
976 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -0600977 case Tag::ATTESTATION_ID_BRAND:
978 case Tag::ATTESTATION_ID_DEVICE:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600979 case Tag::ATTESTATION_ID_MANUFACTURER:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600980 case Tag::ATTESTATION_ID_MODEL:
981 case Tag::ATTESTATION_ID_PRODUCT:
Rubin Xu1a203e32018-05-08 14:25:21 +0100982 result |= ID_ATTESTATION_REQUEST_GENERIC_INFO;
Shawn Willdene2a7b522017-04-11 09:27:40 -0600983 break;
Rubin Xu1a203e32018-05-08 14:25:21 +0100984 case Tag::ATTESTATION_ID_IMEI:
985 case Tag::ATTESTATION_ID_MEID:
986 case Tag::ATTESTATION_ID_SERIAL:
987 result |= ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID;
988 break;
989 default:
990 continue;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100991 }
992 }
Rubin Xu1a203e32018-05-08 14:25:21 +0100993 return result;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100994}
995
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600996Status KeyStoreService::attestKey(
997 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
998 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700999 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1000 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001001 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001002 }
1003
Eran Messerie2c34152017-12-21 21:01:22 +00001004 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1005
Rubin Xu1a203e32018-05-08 14:25:21 +01001006 int needsIdAttestation = isDeviceIdAttestationRequested(params);
1007 bool needsUniqueIdAttestation = needsIdAttestation & ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID;
1008 bool isPrimaryUserSystemUid = (callingUid == AID_SYSTEM);
1009 bool isSomeUserSystemUid = (get_app_id(callingUid) == AID_SYSTEM);
1010 // Allow system context from any user to request attestation with basic device information,
1011 // while only allow system context from user 0 (device owner) to request attestation with
1012 // unique device ID.
1013 if ((needsIdAttestation && !isSomeUserSystemUid) ||
1014 (needsUniqueIdAttestation && !isPrimaryUserSystemUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001015 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001016 }
1017
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001018 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001019 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1020 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001021 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001022 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001023
Shawn Willden50eb1b22016-01-21 12:41:23 -07001024 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001025 Blob keyBlob;
1026 Blob charBlob;
1027 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001028
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001029 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1030 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1031
Janis Danisevskisc1460142017-12-18 16:48:46 -08001032 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001033 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001034 dev->attestKey(
1035 std::move(hidlKey), mutableParams.hidl_data(),
1036 [cb](Return<void> rc, std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1037 auto& [ret, certChain] = hidlResult;
1038 if (!rc.isOk()) {
1039 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1040 } else if (ret != ErrorCode::OK) {
1041 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1042 } else {
1043 cb->onFinished(KeyStoreServiceReturnCode(ret),
1044 KeymasterCertificateChain(std::move(certChain)));
1045 }
1046 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001047
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001048 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001049}
1050
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001051// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1052// It should never be redefined by a build system though.
1053#ifndef CAPTURE_MOVE
1054#define CAPTURE_MOVE(x) x = std::move(x)
1055#endif
1056
1057Status KeyStoreService::attestDeviceIds(
1058 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1059 const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001060 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001061
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001062 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001063 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001064 }
1065
1066 if (!isDeviceIdAttestationRequested(params)) {
1067 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001068 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001069 }
1070
1071 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1072 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
Yi Konge353f252018-07-30 01:38:39 -07001073 if (binder == nullptr) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001074 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001075 }
1076 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1077 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1078 IPCThreadState::self()->getCallingPid(), callingUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001079 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001080 }
1081
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001082 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001083 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1084 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001085 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001086 }
1087
1088 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001089 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001090
Shawn Willden70c1a782018-07-11 15:13:20 -06001091 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001092 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001093 }
1094
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001095
1096 AuthorizationSet keyCharacteristics;
1097 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1098 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1099 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1100 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1101 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001102
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001103 std::promise<KeyStoreServiceReturnCode> resultPromise;
1104 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001105
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001106 dev->generateKey(
1107 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001108 [cb, dev, CAPTURE_MOVE(mutableParams)](
1109 Return<void> rc,
1110 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001111 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1112 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1113 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001114 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001115 return;
1116 }
1117 if (ret != ErrorCode::OK) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001118 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001119 return;
1120 }
1121 dev->attestKey(
1122 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001123 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001124 hidlKeyBlob](Return<void> rc,
1125 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1126 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001127 // schedule temp key for deletion
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001128 dev->deleteKey(std::move(hidlKeyBlob), [](Return<ErrorCode> rc) {
1129 // log error but don't return an error
1130 KS_HANDLE_HIDL_ERROR(rc);
1131 });
1132 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001133 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001134 return;
1135 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001136 if (ret == ErrorCode::OK) {
1137 cb->onFinished(
1138 KeyStoreServiceReturnCode(ret),
1139 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1140 } else {
1141 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001142 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001143 });
1144 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001145
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001146 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001147}
1148
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001149Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001150 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001151 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001152 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1153 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001154}
1155
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001156Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001157 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001158 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1159 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1160 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001161 int32_t* _aidl_return) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001162
1163 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1164
1165 if (!checkBinderPermission(P_INSERT, callingUid)) {
1166 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1167 }
1168
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001169 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001170
1171 KeyStoreServiceReturnCode rc;
1172 Blob wrappingKeyBlob;
1173 Blob wrappingCharBlob;
1174 LockedKeyBlobEntry wrappingLockedEntry;
1175
1176 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1177 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
Branden Archerd166a882018-11-20 10:56:48 -08001178 if (!rc.isOk()) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001179 return AIDL_RETURN(rc);
1180 }
1181
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001182 String8 wrappedKeyName8(wrappedKeyAlias);
1183 auto wrappedLockedEntry =
1184 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1185 if (!wrappedLockedEntry) {
1186 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1187 }
1188
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001189 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1190 auto dev = mKeyStore->getDevice(securityLevel);
1191 if (!dev) {
1192 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1193 }
1194
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001195 dev->importWrappedKey(
1196 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1197 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001198 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1199 cb->onFinished(rc,
1200 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001201 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001202
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001203 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001204}
1205
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001206Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1207 const String16& promptText,
1208 const ::std::vector<uint8_t>& extraData,
1209 const String16& locale, int32_t uiOptionsAsFlags,
1210 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001211 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1212 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001213}
1214
1215Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1216 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001217 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001218}
1219
David Zeuthen1a492312018-02-26 11:00:30 -05001220Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001221 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001222}
1223
1224/**
1225 * Get the effective target uid for a binder operation that takes an
1226 * optional uid as the target.
1227 */
1228uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1229 if (targetUid == UID_SELF) {
1230 return IPCThreadState::self()->getCallingUid();
1231 }
1232 return static_cast<uid_t>(targetUid);
1233}
1234
1235/**
1236 * Check if the caller of the current binder method has the required
1237 * permission and if acting on other uids the grants to do so.
1238 */
1239bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1240 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1241 pid_t spid = IPCThreadState::self()->getCallingPid();
1242 if (!has_permission(callingUid, permission, spid)) {
1243 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1244 return false;
1245 }
1246 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1247 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1248 return false;
1249 }
1250 return true;
1251}
1252
1253/**
1254 * Check if the caller of the current binder method has the required
1255 * permission and the target uid is the caller or the caller is system.
1256 */
1257bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1258 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1259 pid_t spid = IPCThreadState::self()->getCallingPid();
1260 if (!has_permission(callingUid, permission, spid)) {
1261 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1262 return false;
1263 }
1264 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1265}
1266
1267/**
1268 * Check if the caller of the current binder method has the required
1269 * permission or the target of the operation is the caller's uid. This is
1270 * for operation where the permission is only for cross-uid activity and all
1271 * uids are allowed to act on their own (ie: clearing all entries for a
1272 * given uid).
1273 */
1274bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1275 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1276 if (getEffectiveUid(targetUid) == callingUid) {
1277 return true;
1278 } else {
1279 return checkBinderPermission(permission, targetUid);
1280 }
1281}
1282
1283/**
1284 * Helper method to check that the caller has the required permission as
1285 * well as the keystore is in the unlocked state if checkUnlocked is true.
1286 *
1287 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1288 * otherwise the state of keystore when not unlocked and checkUnlocked is
1289 * true.
1290 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001291KeyStoreServiceReturnCode
1292KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1293 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001294 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001295 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001296 }
1297 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1298 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001299 // All State values coincide with ResponseCodes
1300 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001301 }
1302
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001303 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001304}
1305
1306bool KeyStoreService::isKeystoreUnlocked(State state) {
1307 switch (state) {
1308 case ::STATE_NO_ERROR:
1309 return true;
1310 case ::STATE_UNINITIALIZED:
1311 case ::STATE_LOCKED:
1312 return false;
1313 }
1314 return false;
1315}
1316
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001317/**
Shawn Willden0329a822017-12-04 13:55:14 -07001318 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1319 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001320 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001321bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1322 for (size_t i = 0; i < params.size(); ++i) {
1323 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001324 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001325 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001326 return false;
1327 default:
1328 break;
1329 }
1330 }
1331 return true;
1332}
1333
Brian Young9a947d52018-02-23 18:03:14 +00001334Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
1335 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001336 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Brian Young9a947d52018-02-23 18:03:14 +00001337 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001338
1339 return Status::ok();
1340}
1341
Shawn Willdene2a7b522017-04-11 09:27:40 -06001342} // namespace keystore