blob: 9a93b459132c987428106204ade1361b5c668821 [file] [log] [blame]
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Janis Danisevskis011675d2016-09-01 11:41:29 +010017#define LOG_TAG "keystore"
18
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070019#include "key_store_service.h"
20
21#include <fcntl.h>
22#include <sys/stat.h>
23
Janis Danisevskis7612fd42016-09-01 11:50:02 +010024#include <algorithm>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070025#include <atomic>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070026#include <sstream>
27
Pavel Grafovff311b42018-01-24 20:34:37 +000028#include <android-base/scopeguard.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010029#include <binder/IInterface.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070030#include <binder/IPCThreadState.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010031#include <binder/IPermissionController.h>
32#include <binder/IServiceManager.h>
Brian Claire Young3133c452018-08-31 13:56:49 -070033#include <cutils/multiuser.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000034#include <log/log_event_list.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070035
36#include <private/android_filesystem_config.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000037#include <private/android_logger.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070038
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070039#include <android/hardware/confirmationui/1.0/IConfirmationUI.h>
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010040#include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070041
42#include "defaults.h"
Max Bires33aac2d2018-02-23 10:53:10 -080043#include "key_proto_handler.h"
Janis Danisevskis18f27ad2016-06-01 13:57:40 -070044#include "keystore_attestation_id.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010045#include "keystore_keymaster_enforcement.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070046#include "keystore_utils.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010047#include <keystore/keystore_hidl_support.h>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070048#include <keystore/keystore_return_types.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070049
Janis Danisevskis8f737ad2017-11-21 12:30:15 -080050#include <hardware/hw_auth_token.h>
51
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010052namespace keystore {
Shawn Willdend5a24e62017-02-28 13:53:24 -070053
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010054using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070055
Shawn Willdene2a7b522017-04-11 09:27:40 -060056namespace {
57
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070058using ::android::binder::Status;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070059using android::security::keymaster::ExportResult;
60using android::security::keymaster::KeymasterArguments;
61using android::security::keymaster::KeymasterBlob;
62using android::security::keymaster::KeymasterCertificateChain;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070063using android::security::keymaster::operationFailed;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070064using android::security::keymaster::OperationResult;
David Zeuthenc6eb7cd2017-11-27 11:33:55 -050065using ConfirmationResponseCode = android::hardware::confirmationui::V1_0::ResponseCode;
Rob Barnesbb6cabd2018-10-04 17:10:37 -060066using ::android::security::keystore::IKeystoreOperationResultCallback;
67using ::android::security::keystore::IKeystoreResponseCallback;
68using ::android::security::keystore::KeystoreResponse;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070069
Shawn Willdene2a7b522017-04-11 09:27:40 -060070constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
71const char* kTimestampFilePath = "timestamp";
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070072
Shawn Willdene2a7b522017-04-11 09:27:40 -060073bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070074 return params.end() !=
75 std::find_if(params.begin(), params.end(),
76 [&](const KeyParameter& param) { return param.tag == tag; });
Shawn Willdend5a24e62017-02-28 13:53:24 -070077}
78
Branden Archer70080742018-11-20 11:04:11 -080079#define AIDL_RETURN(rc) (*_aidl_return = KeyStoreServiceReturnCode(rc).getErrorCode(), Status::ok())
Rob Barnesbb6cabd2018-10-04 17:10:37 -060080
Shawn Willdene2a7b522017-04-11 09:27:40 -060081std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
82 struct stat sbuf;
83 if (stat(kTimestampFilePath, &sbuf) == 0) {
Yi Konge353f252018-07-30 01:38:39 -070084 double diff_secs = difftime(time(nullptr), sbuf.st_ctime);
Shawn Willdene2a7b522017-04-11 09:27:40 -060085 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
86 }
87
88 if (errno != ENOENT) {
89 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
90 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
91 }
92
93 int fd = creat(kTimestampFilePath, 0600);
94 if (fd < 0) {
95 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
96 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
97 }
98
99 if (close(fd)) {
100 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
101 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
102 }
103
104 return {ResponseCode::NO_ERROR, true};
105}
106
Eran Messeri03fc4c82018-08-16 18:53:15 +0100107using ::android::security::KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200108
109KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
110 KeyStoreServiceReturnCode responseCode;
111 bool factoryResetSinceIdRotation;
112 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
113
114 if (!responseCode.isOk()) return responseCode;
115 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
116
117 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
118 if (!asn1_attestation_id_result.isOk()) {
119 ALOGE("failed to gather attestation_id");
Shawn Willden6f7d27c2019-09-11 22:51:46 -0600120 // Couldn't get attestation ID; just use an empty one rather than failing.
121 asn1_attestation_id_result = std::vector<uint8_t>();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200122 }
123 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
124
125 /*
Eran Messeri03fc4c82018-08-16 18:53:15 +0100126 * The attestation application ID must not be longer than
127 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, error out if gather_attestation_application_id
128 * returned such an invalid vector.
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200129 */
130 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Eran Messeri03fc4c82018-08-16 18:53:15 +0100131 ALOGE("BUG: Gathered Attestation Application ID is too big (%d)",
132 static_cast<int32_t>(asn1_attestation_id.size()));
133 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200134 }
135
136 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
137
138 return ResponseCode::NO_ERROR;
139}
140
Shawn Willdene2a7b522017-04-11 09:27:40 -0600141} // anonymous namespace
142
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700143Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700144 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700145 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
146 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700147 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700148 *aidl_return = mKeyStore->getState(userId);
149 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700150}
151
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700152Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700153 uid_t targetUid = getEffectiveUid(uid);
154 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700155 // see keystore/keystore.h
156 return Status::fromServiceSpecificError(
157 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700158 }
159
160 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700161 ResponseCode rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700162 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700163 Blob charBlob;
164 LockedKeyBlobEntry lockedEntry;
165
166 std::tie(rc, keyBlob, charBlob, lockedEntry) =
167 mKeyStore->getKeyForName(name8, targetUid, TYPE_GENERIC);
168 if (rc != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700169 *item = ::std::vector<uint8_t>();
170 // Return empty array if key is not found
171 // TODO: consider having returned value nullable or parse exception on the client.
172 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700173 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100174 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700175 // The static_cast here is needed to prevent a move, forcing a deep copy.
176 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
177 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700178}
179
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700180Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
181 int targetUid, int32_t flags, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700182 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700183 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700184 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100185 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800186 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700187 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700188 }
189
190 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700191 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), targetUid);
192
193 if (!lockedEntry) {
194 ALOGE("failed to grab lock on blob entry %u_%s", targetUid, name8.string());
195 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_ALREADY_EXISTS);
196 return Status::ok();
197 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700198
Yi Konge353f252018-07-30 01:38:39 -0700199 Blob keyBlob(&item[0], item.size(), nullptr, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700200 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
201
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700202 *aidl_return = static_cast<int32_t>(mKeyStore->put(lockedEntry, keyBlob, {}));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700203 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700204}
205
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700206Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700207 targetUid = getEffectiveUid(targetUid);
208 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700209 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
210 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700211 }
212 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000213 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700214 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
215 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700216 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
217 return Status::ok();
218 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700219
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700220 ResponseCode result = mKeyStore->del(lockedEntry);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400221
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700222 *aidl_return = static_cast<int32_t>(result);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700223 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700224}
225
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700226Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700227 targetUid = getEffectiveUid(targetUid);
228 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700229 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
230 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700231 }
232
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700233 LockedKeyBlobEntry lockedEntry =
234 mKeyStore->getLockedBlobEntryIfExists(String8(name).string(), targetUid);
235 *aidl_return =
236 static_cast<int32_t>(lockedEntry ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700237 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700238}
239
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700240Status KeyStoreService::list(const String16& prefix, int32_t targetUid,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700241 ::std::vector<::android::String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700242 targetUid = getEffectiveUid(targetUid);
243 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700244 return Status::fromServiceSpecificError(
245 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700246 }
247 const String8 prefix8(prefix);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700248 const std::string stdPrefix(prefix8.string());
249
250 ResponseCode rc;
251 std::list<LockedKeyBlobEntry> internal_matches;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800252 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700253
Janis Danisevskis265435f2018-11-16 14:10:46 -0800254 std::tie(rc, internal_matches) =
255 LockedKeyBlobEntry::list(userDirName, [&](uid_t uid, const std::string& alias) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700256 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end());
257 return uid == static_cast<uid_t>(targetUid) &&
258 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end())
259 .first == stdPrefix.end();
260 });
261
262 if (rc != ResponseCode::NO_ERROR) {
263 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700264 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700265
266 for (LockedKeyBlobEntry& entry : internal_matches) {
267 matches->push_back(String16(entry->alias().substr(prefix8.size()).c_str()));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700268 }
269 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700270}
271
Rob Barneseb7f79b2018-11-08 15:44:10 -0700272/*
273 * This method will return the uids of all auth bound keys for the calling user.
274 * This is intended to be used for alerting the user about which apps will be affected
275 * if the password/pin is removed. Only allowed to be called by system.
276 * The output is bound by the initial size of uidsOut to be compatible with Java.
277 */
Rob Barnes5d59e632018-12-07 16:09:02 -0700278Status KeyStoreService::listUidsOfAuthBoundKeys(std::vector<std::string>* uidsOut,
Rob Barneseb7f79b2018-11-08 15:44:10 -0700279 int32_t* aidl_return) {
280 const int32_t callingUid = IPCThreadState::self()->getCallingUid();
281 const int32_t userId = get_user_id(callingUid);
282 const int32_t appId = get_app_id(callingUid);
283 if (appId != AID_SYSTEM) {
284 ALOGE("Permission listUidsOfAuthBoundKeys denied for aid %d", appId);
285 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
286 return Status::ok();
287 }
288
289 const String8 prefix8("");
290 auto userState = mKeyStore->getUserStateDB().getUserState(userId);
291 const std::string userDirName = userState->getUserDirName();
292 auto encryptionKey = userState->getEncryptionKey();
293 auto state = userState->getState();
294 // unlock the user state
295 userState = {};
296
297 ResponseCode rc;
298 std::list<LockedKeyBlobEntry> internal_matches;
299 std::tie(rc, internal_matches) =
300 LockedKeyBlobEntry::list(userDirName, [&](uid_t, const std::string&) {
301 // Need to filter on auth bound state, so just return true.
302 return true;
303 });
304 if (rc != ResponseCode::NO_ERROR) {
305 ALOGE("Error listing blob entries for user %d", userId);
306 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
307 }
308
Rob Barneseb7f79b2018-11-08 15:44:10 -0700309 for (LockedKeyBlobEntry& entry : internal_matches) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700310 // Need to store uids as a list of strings because integer list output
311 // parameters is not supported in aidl-cpp.
312 std::string entryUid = std::to_string(entry->uid());
313 if (std::find(uidsOut->begin(), uidsOut->end(), entryUid) != uidsOut->end()) {
Rob Barneseb7f79b2018-11-08 15:44:10 -0700314 // uid already in list, skip
315 continue;
316 }
317
318 auto [rc, blob, charBlob] = entry.readBlobs(encryptionKey, state);
319 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::LOCKED) {
320 ALOGE("Error reading blob for key %s", entry->alias().c_str());
321 continue;
322 }
323
324 if (blob && blob.isEncrypted()) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700325 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700326 } else if (charBlob) {
327 auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
328 if (!success) {
329 ALOGE("Error reading blob characteristics for key %s", entry->alias().c_str());
330 continue;
331 }
332 if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
333 swEnforced.Contains(TAG_USER_SECURE_ID)) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700334 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700335 }
336 }
337 }
338 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
339 return Status::ok();
340}
341
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700342Status KeyStoreService::reset(int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700343 if (!checkBinderPermission(P_RESET)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700344 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
345 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700346 }
347
348 uid_t callingUid = IPCThreadState::self()->getCallingUid();
349 mKeyStore->resetUser(get_user_id(callingUid), false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700350 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
351 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700352}
353
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700354Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
355 int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700356 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700357 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
358 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700359 }
360
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700361 if (password.size() == 0) {
362 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
363 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700364 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
365 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700366 } else {
Pavel Grafovf9b53eb2019-02-06 17:16:21 +0000367 const String8 password8(password);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700368 switch (mKeyStore->getState(userId)) {
369 case ::STATE_UNINITIALIZED: {
370 // generate master key, encrypt with password, write to file,
371 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700372 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
373 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700374 }
375 case ::STATE_NO_ERROR: {
376 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700377 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
378 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700379 }
380 case ::STATE_LOCKED: {
381 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
382 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700383 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
384 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700385 }
386 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700387 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
388 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700389 }
390}
391
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700392Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700393 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700394 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
395 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700396 }
397
398 // Sanity check that the new user has an empty keystore.
399 if (!mKeyStore->isEmpty(userId)) {
400 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
401 }
402 // Unconditionally clear the keystore, just to be safe.
403 mKeyStore->resetUser(userId, false);
404 if (parentId != -1) {
405 // This profile must share the same master key password as the parent profile. Because the
406 // password of the parent profile is not known here, the best we can do is copy the parent's
407 // master key and master key file. This makes this profile use the same master key as the
408 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700409 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
410 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700411 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700412 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
413 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700414 }
415}
416
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700417Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700418 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700419 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
420 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700421 }
422
423 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700424 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
425 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700426}
427
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700428Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700429 if (!checkBinderPermission(P_LOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700430 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
431 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700432 }
433
434 State state = mKeyStore->getState(userId);
435 if (state != ::STATE_NO_ERROR) {
436 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700437 *aidl_return = static_cast<int32_t>(ResponseCode(state));
438 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700439 }
440
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700441 mKeyStore->getEnforcementPolicy().set_device_locked(true, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700442 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700443 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
444 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700445}
446
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700447Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700448 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700449 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
450 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700451 }
452
453 State state = mKeyStore->getState(userId);
454 if (state != ::STATE_LOCKED) {
455 switch (state) {
456 case ::STATE_NO_ERROR:
457 ALOGI("calling unlock when already unlocked, ignoring.");
458 break;
459 case ::STATE_UNINITIALIZED:
460 ALOGE("unlock called on uninitialized keystore.");
461 break;
462 default:
463 ALOGE("unlock called on keystore in unknown state: %d", state);
464 break;
465 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700466 *aidl_return = static_cast<int32_t>(ResponseCode(state));
467 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700468 }
469
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700470 mKeyStore->getEnforcementPolicy().set_device_locked(false, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700471 const String8 password8(pw);
472 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700473 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
474 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700475}
476
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700477Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700478 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700479 *aidl_return = static_cast<int32_t>(false);
480 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700481 }
482
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700483 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
484 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700485}
486
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700487Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
488 ::android::String16* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700489 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700490 auto result =
491 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100492 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700493 *aidl_return = String16();
494 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700495 }
496
497 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700498 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
499 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700500 *aidl_return = String16();
501 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700502 }
503
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700504 *aidl_return = String16(mKeyStore->addGrant(lockedEntry, granteeUid).c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700505 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700506}
507
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700508Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700509 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700510 KeyStoreServiceReturnCode result =
511 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100512 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800513 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700514 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700515 }
516
517 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700518
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700519 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
520 if (!lockedEntry) {
521 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700522 }
523
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700524 *aidl_return = mKeyStore->removeGrant(lockedEntry, granteeUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700525 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700526}
527
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700528Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700529 uid_t targetUid = getEffectiveUid(uid);
530 if (!checkBinderPermission(P_GET, targetUid)) {
531 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700532 *time = -1L;
533 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700534 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700535 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700536
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700537 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
538 if (!lockedEntry) {
539 ALOGW("could not access key with alias %s for getmtime", name8.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700540 *time = -1L;
541 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700542 }
543
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700544 std::string filename = lockedEntry->getKeyBlobPath();
545
546 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700547 if (fd < 0) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700548 ALOGW("could not open %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700549 *time = -1L;
550 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700551 }
552
553 struct stat s;
554 int ret = fstat(fd, &s);
555 close(fd);
556 if (ret == -1) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700557 ALOGW("could not stat %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700558 *time = -1L;
559 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700560 }
561
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700562 *time = static_cast<int64_t>(s.st_mtime);
563 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700564}
565
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700566Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
567 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
568 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700569}
570
Janis Danisevskis265435f2018-11-16 14:10:46 -0800571Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700572 uid_t targetUid = getEffectiveUid(targetUid64);
573 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800574 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700575 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000576 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700577
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700578 mKeyStore->removeAllGrantsToUid(targetUid);
579
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700580 ResponseCode rc;
581 std::list<LockedKeyBlobEntry> entries;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800582 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700583
584 // list has a fence making sure no workers are modifying blob files before iterating the
585 // data base. All returned entries are locked.
586 std::tie(rc, entries) = LockedKeyBlobEntry::list(
Janis Danisevskis265435f2018-11-16 14:10:46 -0800587 userDirName, [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700588
589 if (rc != ResponseCode::NO_ERROR) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800590 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700591 }
592
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700593 for (LockedKeyBlobEntry& lockedEntry : entries) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100594 if (get_app_id(targetUid) == AID_SYSTEM) {
595 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700596 Blob charBlob;
597 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
598 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100599 // Do not clear keys critical to device encryption under system uid.
600 continue;
601 }
602 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700603 mKeyStore->del(lockedEntry);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700604 }
Janis Danisevskis265435f2018-11-16 14:10:46 -0800605 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700606}
607
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600608Status KeyStoreService::addRngEntropy(
609 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
610 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
Janis Danisevskisc1460142017-12-18 16:48:46 -0800611 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
612 if (!device) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600613 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800614 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700615
Janis Danisevskisa359c672019-03-14 17:15:06 -0700616 device->addRngEntropy(entropy, [device, cb](Return<ErrorCode> rc) {
617 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device, rc)));
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600618 });
619
620 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700621}
622
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600623Status KeyStoreService::generateKey(
624 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
625 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
626 int uid, int flags, int32_t* _aidl_return) {
Max Biresef4f0672017-11-29 14:38:48 -0800627 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
628 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700629 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000630 auto logOnScopeExit = android::base::make_scope_guard([&] {
631 if (__android_log_security()) {
632 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600633 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000634 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
635 }
636 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100637 KeyStoreServiceReturnCode rc =
638 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
639 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600640 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700641 }
Rubin Xu67899de2017-04-21 19:15:13 +0100642 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
643 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600644 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100645 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700646
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700647 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700648 // TODO(jbires): remove uid checking upon implementation of b/25646100
Max Bires670467d2017-12-12 11:16:43 -0800649 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Biresef4f0672017-11-29 14:38:48 -0800650 originalUid != IPCThreadState::self()->getCallingUid()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600651 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700652 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600653 }
654
Janis Danisevskisc1460142017-12-18 16:48:46 -0800655 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
656 auto dev = mKeyStore->getDevice(securityLevel);
657 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600658 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800659 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400660
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100661 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700662 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
663 if (!lockedEntry) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600664 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100665 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400666
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700667 logOnScopeExit.Disable();
668
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600669 dev->generateKey(
670 std::move(lockedEntry), params.getParameters(), entropy, flags,
671 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
672 if (__android_log_security()) {
673 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
674 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
675 }
676 cb->onFinished(rc,
677 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
678 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700679
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600680 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700681}
682
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700683Status KeyStoreService::getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600684 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700685 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
Janis Danisevskis64ec1fe2018-02-26 16:47:21 -0800686 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600687 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700688
689 uid_t targetUid = getEffectiveUid(uid);
690 uid_t callingUid = IPCThreadState::self()->getCallingUid();
691 if (!is_granted_to(callingUid, targetUid)) {
692 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
693 targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600694 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700695 }
696
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700697 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700698
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700699 ResponseCode rc;
700 Blob keyBlob;
701 Blob charBlob;
702 LockedKeyBlobEntry lockedEntry;
Janis Danisevskisd714a672017-09-01 14:31:36 -0700703
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700704 std::tie(rc, keyBlob, charBlob, lockedEntry) =
705 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
706
707 if (rc != ResponseCode::NO_ERROR) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600708 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700709 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100710
Janis Danisevskisc1460142017-12-18 16:48:46 -0800711 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700712 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600713 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100714 }
715
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700716 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
717 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
718 // from keymaster. It may also upgrade the key blob.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700719 dev->getKeyCharacteristics(
720 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
721 std::move(charBlob),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600722 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
723 cb->onFinished(rc,
724 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700725 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100726
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600727 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700728}
729
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600730Status KeyStoreService::importKey(
731 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
732 const String16& name, const KeymasterArguments& params, int32_t format,
733 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700734 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000735 auto logOnScopeExit = android::base::make_scope_guard([&] {
736 if (__android_log_security()) {
737 android_log_event_list(SEC_TAG_KEY_IMPORTED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600738 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000739 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
740 }
741 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100742 KeyStoreServiceReturnCode rc =
743 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
744 if (!rc.isOk()) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700745 LOG(ERROR) << "permissission denied";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600746 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700747 }
Rubin Xu67899de2017-04-21 19:15:13 +0100748 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
749 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600750 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100751 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700752
Janis Danisevskisc1460142017-12-18 16:48:46 -0800753 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
754 auto dev = mKeyStore->getDevice(securityLevel);
755 if (!dev) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700756 LOG(ERROR) << "importKey - cound not get keymaster device";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600757 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800758 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700759
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700760 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700761 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
762 if (!lockedEntry) {
763 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
764 << " already exists.";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600765 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400766 }
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700767
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700768 logOnScopeExit.Disable();
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700769
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600770 dev->importKey(
771 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
772 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
773 if (__android_log_security()) {
774 android_log_event_list(SEC_TAG_KEY_IMPORTED)
775 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
776 }
777 cb->onFinished(rc,
778 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
779 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400780
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600781 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700782}
783
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600784Status KeyStoreService::exportKey(
785 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
786 const String16& name, int32_t format,
787 const ::android::security::keymaster::KeymasterBlob& clientId,
788 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
789 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700790
791 uid_t targetUid = getEffectiveUid(uid);
792 uid_t callingUid = IPCThreadState::self()->getCallingUid();
793 if (!is_granted_to(callingUid, targetUid)) {
794 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600795 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700796 }
797
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700798 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700799
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700800 KeyStoreServiceReturnCode rc;
801 Blob keyBlob;
802 Blob charBlob;
803 LockedKeyBlobEntry lockedEntry;
804
805 std::tie(rc, keyBlob, charBlob, lockedEntry) =
806 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskis3cf85322018-11-19 13:37:49 -0800807 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600808 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700809 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100810
Janis Danisevskisc1460142017-12-18 16:48:46 -0800811 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100812
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700813 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600814 std::move(keyBlob), std::move(charBlob),
815 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
Ji Wang2c142312016-10-14 17:21:10 +0800816
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600817 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700818}
819
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600820Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
821 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700822 bool pruneable, const KeymasterArguments& params,
823 const ::std::vector<uint8_t>& entropy, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600824 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700825 uid_t callingUid = IPCThreadState::self()->getCallingUid();
826 uid_t targetUid = getEffectiveUid(uid);
827 if (!is_granted_to(callingUid, targetUid)) {
828 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600829 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700830 }
831 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
832 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600833 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700834 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700835 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600836 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700837 }
Shawn Willden0329a822017-12-04 13:55:14 -0700838
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700839 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700840 Blob keyBlob;
841 Blob charBlob;
842 LockedKeyBlobEntry lockedEntry;
843 ResponseCode rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100844
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700845 std::tie(rc, keyBlob, charBlob, lockedEntry) =
846 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
847
848 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600849 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700850 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600851 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700852
Janis Danisevskisc1460142017-12-18 16:48:46 -0800853 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700854 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100855
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700856 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
857 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600858 [this, cb, dev](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700859 if (result_.resultCode.isOk() ||
860 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700861 mKeyStore->addOperationDevice(result_.token, dev);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700862 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600863 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700864 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400865
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600866 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700867}
868
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600869Status KeyStoreService::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
870 const ::android::sp<::android::IBinder>& token,
871 const ::android::security::keymaster::KeymasterArguments& params,
872 const ::std::vector<uint8_t>& input, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700873 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600874 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700875 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700876
Janis Danisevskisbec89992019-08-14 13:42:19 -0700877 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700878 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600879 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700880 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700881
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600882 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700883 if (!result_.resultCode.isOk()) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700884 mKeyStore->removeOperationDevice(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100885 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600886 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700887 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100888
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600889 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700890}
891
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600892Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
893 const ::android::sp<::android::IBinder>& token,
894 const ::android::security::keymaster::KeymasterArguments& params,
Rob Barnes3af223f2019-11-14 14:50:30 -0700895 const ::std::vector<uint8_t>& input,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700896 const ::std::vector<uint8_t>& signature,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600897 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700898 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600899 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700900 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700901
Janis Danisevskisbec89992019-08-14 13:42:19 -0700902 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700903 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600904 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700905 }
906
Rob Barnes3af223f2019-11-14 14:50:30 -0700907 dev->finish(token, params.getParameters(), input, signature, entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600908 [this, cb, token](OperationResult result_) {
Janis Danisevskis8c4c1d62019-10-04 11:01:54 -0700909 mKeyStore->removeOperationDevice(token);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600910 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700911 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700912
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600913 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700914}
915
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600916Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
917 const ::android::sp<::android::IBinder>& token,
918 int32_t* _aidl_return) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700919 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700920 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600921 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700922 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100923
Janis Danisevskisbec89992019-08-14 13:42:19 -0700924 dev->abort(token, [this, cb, token](KeyStoreServiceReturnCode rc) {
925 mKeyStore->removeOperationDevice(token);
926 cb->onFinished(rc);
927 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700928
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600929 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700930}
931
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700932Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000933 int32_t* aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700934
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000935 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
936 // receive a HardwareAuthToken, rather than an opaque byte array.
937
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700938 if (!checkBinderPermission(P_ADD_AUTH)) {
939 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700940 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
941 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700942 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700943 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
Branden Archer70080742018-11-20 11:04:11 -0800944 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700945 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000946 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100947
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000948 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700949 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000950 if (authToken.version != 0) {
Branden Archer70080742018-11-20 11:04:11 -0800951 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700952 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000953 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100954
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700955 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
956 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700957 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
958 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700959}
960
Eran Messerid9f8ae52018-10-24 13:54:00 +0100961bool isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -0700962 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700963 for (size_t i = 0; i < paramsVec.size(); ++i) {
964 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -0600965 case Tag::ATTESTATION_ID_BRAND:
966 case Tag::ATTESTATION_ID_DEVICE:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600967 case Tag::ATTESTATION_ID_MANUFACTURER:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600968 case Tag::ATTESTATION_ID_MODEL:
969 case Tag::ATTESTATION_ID_PRODUCT:
Rubin Xu1a203e32018-05-08 14:25:21 +0100970 case Tag::ATTESTATION_ID_IMEI:
971 case Tag::ATTESTATION_ID_MEID:
972 case Tag::ATTESTATION_ID_SERIAL:
Eran Messerid9f8ae52018-10-24 13:54:00 +0100973 return true;
Rubin Xu1a203e32018-05-08 14:25:21 +0100974 default:
975 continue;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100976 }
977 }
Eran Messerid9f8ae52018-10-24 13:54:00 +0100978 return false;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100979}
980
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600981Status KeyStoreService::attestKey(
982 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
983 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700984 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
985 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600986 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -0700987 }
988
Eran Messerie2c34152017-12-21 21:01:22 +0000989 uid_t callingUid = IPCThreadState::self()->getCallingUid();
990
Eran Messerid9f8ae52018-10-24 13:54:00 +0100991 if (isDeviceIdAttestationRequested(params) && (get_app_id(callingUid) != AID_SYSTEM)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600992 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100993 }
994
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700995 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200996 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
997 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600998 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200999 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001000
Shawn Willden50eb1b22016-01-21 12:41:23 -07001001 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001002 Blob keyBlob;
1003 Blob charBlob;
1004 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001005
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001006 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1007 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1008
Janis Danisevskis9dff56c2019-07-10 14:08:06 -07001009 if (!rc.isOk()) {
1010 return AIDL_RETURN(rc);
1011 }
1012
Janis Danisevskisc1460142017-12-18 16:48:46 -08001013 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001014 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001015 dev->attestKey(
1016 std::move(hidlKey), mutableParams.hidl_data(),
Janis Danisevskisa359c672019-03-14 17:15:06 -07001017 [dev, cb](Return<void> rc,
1018 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001019 auto& [ret, certChain] = hidlResult;
1020 if (!rc.isOk()) {
1021 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1022 } else if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001023 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001024 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1025 } else {
1026 cb->onFinished(KeyStoreServiceReturnCode(ret),
1027 KeymasterCertificateChain(std::move(certChain)));
1028 }
1029 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001030
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001031 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001032}
1033
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001034// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1035// It should never be redefined by a build system though.
1036#ifndef CAPTURE_MOVE
1037#define CAPTURE_MOVE(x) x = std::move(x)
1038#endif
1039
1040Status KeyStoreService::attestDeviceIds(
1041 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1042 const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001043 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001044
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001045 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001046 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001047 }
1048
1049 if (!isDeviceIdAttestationRequested(params)) {
1050 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001051 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001052 }
1053
1054 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1055 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
Yi Konge353f252018-07-30 01:38:39 -07001056 if (binder == nullptr) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001057 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001058 }
1059 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1060 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1061 IPCThreadState::self()->getCallingPid(), callingUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001062 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001063 }
1064
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001065 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001066 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1067 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001068 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001069 }
1070
1071 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001072 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001073
Shawn Willden70c1a782018-07-11 15:13:20 -06001074 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001075 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001076 }
1077
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001078
1079 AuthorizationSet keyCharacteristics;
1080 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1081 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1082 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1083 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1084 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001085
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001086 std::promise<KeyStoreServiceReturnCode> resultPromise;
1087 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001088
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001089 dev->generateKey(
1090 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001091 [cb, dev, CAPTURE_MOVE(mutableParams)](
1092 Return<void> rc,
1093 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001094 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1095 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1096 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001097 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001098 return;
1099 }
1100 if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001101 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001102 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001103 return;
1104 }
1105 dev->attestKey(
1106 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001107 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001108 hidlKeyBlob](Return<void> rc,
1109 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1110 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001111 // schedule temp key for deletion
Janis Danisevskisa359c672019-03-14 17:15:06 -07001112 dev->deleteKey(std::move(hidlKeyBlob), [dev](Return<ErrorCode> rc) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001113 // log error but don't return an error
Janis Danisevskisa359c672019-03-14 17:15:06 -07001114 KS_HANDLE_HIDL_ERROR(dev, rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001115 });
1116 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001117 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001118 return;
1119 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001120 if (ret == ErrorCode::OK) {
1121 cb->onFinished(
1122 KeyStoreServiceReturnCode(ret),
1123 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1124 } else {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001125 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001126 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001127 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001128 });
1129 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001130
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001131 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001132}
1133
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001134Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001135 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001136 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001137 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1138 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001139}
1140
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001141Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001142 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001143 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1144 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1145 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001146 int32_t* _aidl_return) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001147
1148 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1149
1150 if (!checkBinderPermission(P_INSERT, callingUid)) {
1151 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1152 }
1153
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001154 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001155
1156 KeyStoreServiceReturnCode rc;
1157 Blob wrappingKeyBlob;
1158 Blob wrappingCharBlob;
1159 LockedKeyBlobEntry wrappingLockedEntry;
1160
1161 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1162 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
Branden Archerd166a882018-11-20 10:56:48 -08001163 if (!rc.isOk()) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001164 return AIDL_RETURN(rc);
1165 }
1166
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001167 String8 wrappedKeyName8(wrappedKeyAlias);
1168 auto wrappedLockedEntry =
1169 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1170 if (!wrappedLockedEntry) {
1171 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1172 }
1173
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001174 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1175 auto dev = mKeyStore->getDevice(securityLevel);
1176 if (!dev) {
1177 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1178 }
1179
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001180 dev->importWrappedKey(
1181 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1182 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001183 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1184 cb->onFinished(rc,
1185 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001186 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001187
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001188 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001189}
1190
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001191Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1192 const String16& promptText,
1193 const ::std::vector<uint8_t>& extraData,
1194 const String16& locale, int32_t uiOptionsAsFlags,
1195 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001196 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1197 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001198}
1199
1200Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1201 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001202 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001203}
1204
David Zeuthen1a492312018-02-26 11:00:30 -05001205Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001206 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001207}
1208
1209/**
1210 * Get the effective target uid for a binder operation that takes an
1211 * optional uid as the target.
1212 */
1213uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1214 if (targetUid == UID_SELF) {
1215 return IPCThreadState::self()->getCallingUid();
1216 }
1217 return static_cast<uid_t>(targetUid);
1218}
1219
1220/**
1221 * Check if the caller of the current binder method has the required
1222 * permission and if acting on other uids the grants to do so.
1223 */
1224bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1225 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1226 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001227 const char* ssid = IPCThreadState::self()->getCallingSid();
1228 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001229 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1230 return false;
1231 }
1232 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1233 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1234 return false;
1235 }
1236 return true;
1237}
1238
1239/**
1240 * Check if the caller of the current binder method has the required
1241 * permission and the target uid is the caller or the caller is system.
1242 */
1243bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1244 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1245 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001246 const char* ssid = IPCThreadState::self()->getCallingSid();
1247 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001248 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1249 return false;
1250 }
1251 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1252}
1253
1254/**
1255 * Check if the caller of the current binder method has the required
1256 * permission or the target of the operation is the caller's uid. This is
1257 * for operation where the permission is only for cross-uid activity and all
1258 * uids are allowed to act on their own (ie: clearing all entries for a
1259 * given uid).
1260 */
1261bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1262 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1263 if (getEffectiveUid(targetUid) == callingUid) {
1264 return true;
1265 } else {
1266 return checkBinderPermission(permission, targetUid);
1267 }
1268}
1269
1270/**
1271 * Helper method to check that the caller has the required permission as
1272 * well as the keystore is in the unlocked state if checkUnlocked is true.
1273 *
1274 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1275 * otherwise the state of keystore when not unlocked and checkUnlocked is
1276 * true.
1277 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001278KeyStoreServiceReturnCode
1279KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1280 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001281 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001282 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001283 }
1284 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1285 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001286 // All State values coincide with ResponseCodes
1287 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001288 }
1289
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001290 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001291}
1292
1293bool KeyStoreService::isKeystoreUnlocked(State state) {
1294 switch (state) {
1295 case ::STATE_NO_ERROR:
1296 return true;
1297 case ::STATE_UNINITIALIZED:
1298 case ::STATE_LOCKED:
1299 return false;
1300 }
1301 return false;
1302}
1303
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001304/**
Shawn Willden0329a822017-12-04 13:55:14 -07001305 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1306 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001307 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001308bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1309 for (size_t i = 0; i < params.size(); ++i) {
1310 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001311 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001312 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001313 return false;
1314 default:
1315 break;
1316 }
1317 }
1318 return true;
1319}
1320
Brian Young9a947d52018-02-23 18:03:14 +00001321Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
1322 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001323 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Brian Young9a947d52018-02-23 18:03:14 +00001324 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001325
1326 return Status::ok();
1327}
1328
Shawn Willdene2a7b522017-04-11 09:27:40 -06001329} // namespace keystore