blob: 5bc5a78d38dce5f5f9a0e89a7ecc75f603c8eaa3 [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>
David Zeuthenab3e5652019-10-28 13:32:48 -040041#include <keymasterV4_0/keymaster_utils.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070042
43#include "defaults.h"
Max Bires33aac2d2018-02-23 10:53:10 -080044#include "key_proto_handler.h"
Janis Danisevskis18f27ad2016-06-01 13:57:40 -070045#include "keystore_attestation_id.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010046#include "keystore_keymaster_enforcement.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070047#include "keystore_utils.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010048#include <keystore/keystore_hidl_support.h>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070049#include <keystore/keystore_return_types.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070050
Janis Danisevskis8f737ad2017-11-21 12:30:15 -080051#include <hardware/hw_auth_token.h>
52
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010053namespace keystore {
Shawn Willdend5a24e62017-02-28 13:53:24 -070054
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010055using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070056
Shawn Willdene2a7b522017-04-11 09:27:40 -060057namespace {
58
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070059using ::android::binder::Status;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070060using android::security::keymaster::ExportResult;
61using android::security::keymaster::KeymasterArguments;
62using android::security::keymaster::KeymasterBlob;
63using android::security::keymaster::KeymasterCertificateChain;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070064using android::security::keymaster::operationFailed;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070065using android::security::keymaster::OperationResult;
David Zeuthenc6eb7cd2017-11-27 11:33:55 -050066using ConfirmationResponseCode = android::hardware::confirmationui::V1_0::ResponseCode;
Rob Barnesbb6cabd2018-10-04 17:10:37 -060067using ::android::security::keystore::IKeystoreOperationResultCallback;
68using ::android::security::keystore::IKeystoreResponseCallback;
69using ::android::security::keystore::KeystoreResponse;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070070
Shawn Willdene2a7b522017-04-11 09:27:40 -060071constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
72const char* kTimestampFilePath = "timestamp";
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070073
Shawn Willdene2a7b522017-04-11 09:27:40 -060074bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070075 return params.end() !=
76 std::find_if(params.begin(), params.end(),
77 [&](const KeyParameter& param) { return param.tag == tag; });
Shawn Willdend5a24e62017-02-28 13:53:24 -070078}
79
Branden Archer70080742018-11-20 11:04:11 -080080#define AIDL_RETURN(rc) (*_aidl_return = KeyStoreServiceReturnCode(rc).getErrorCode(), Status::ok())
Rob Barnesbb6cabd2018-10-04 17:10:37 -060081
Shawn Willdene2a7b522017-04-11 09:27:40 -060082std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
83 struct stat sbuf;
84 if (stat(kTimestampFilePath, &sbuf) == 0) {
Yi Konge353f252018-07-30 01:38:39 -070085 double diff_secs = difftime(time(nullptr), sbuf.st_ctime);
Shawn Willdene2a7b522017-04-11 09:27:40 -060086 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
87 }
88
89 if (errno != ENOENT) {
90 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
91 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
92 }
93
94 int fd = creat(kTimestampFilePath, 0600);
95 if (fd < 0) {
96 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
97 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
98 }
99
100 if (close(fd)) {
101 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
102 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
103 }
104
105 return {ResponseCode::NO_ERROR, true};
106}
107
Eran Messeri03fc4c82018-08-16 18:53:15 +0100108using ::android::security::KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200109
110KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
111 KeyStoreServiceReturnCode responseCode;
112 bool factoryResetSinceIdRotation;
113 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
114
115 if (!responseCode.isOk()) return responseCode;
116 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
117
118 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
119 if (!asn1_attestation_id_result.isOk()) {
120 ALOGE("failed to gather attestation_id");
Shawn Willden6f7d27c2019-09-11 22:51:46 -0600121 // Couldn't get attestation ID; just use an empty one rather than failing.
122 asn1_attestation_id_result = std::vector<uint8_t>();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200123 }
124 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
125
126 /*
Eran Messeri03fc4c82018-08-16 18:53:15 +0100127 * The attestation application ID must not be longer than
128 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, error out if gather_attestation_application_id
129 * returned such an invalid vector.
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200130 */
131 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Eran Messeri03fc4c82018-08-16 18:53:15 +0100132 ALOGE("BUG: Gathered Attestation Application ID is too big (%d)",
133 static_cast<int32_t>(asn1_attestation_id.size()));
134 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200135 }
136
137 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
138
139 return ResponseCode::NO_ERROR;
140}
141
Shawn Willdene2a7b522017-04-11 09:27:40 -0600142} // anonymous namespace
143
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700144Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700145 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700146 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
147 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700148 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700149 *aidl_return = mKeyStore->getState(userId);
150 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700151}
152
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700153Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700154 uid_t targetUid = getEffectiveUid(uid);
155 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700156 // see keystore/keystore.h
157 return Status::fromServiceSpecificError(
158 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700159 }
160
161 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700162 ResponseCode rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700163 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700164 Blob charBlob;
165 LockedKeyBlobEntry lockedEntry;
166
167 std::tie(rc, keyBlob, charBlob, lockedEntry) =
168 mKeyStore->getKeyForName(name8, targetUid, TYPE_GENERIC);
169 if (rc != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700170 *item = ::std::vector<uint8_t>();
171 // Return empty array if key is not found
172 // TODO: consider having returned value nullable or parse exception on the client.
173 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700174 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100175 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700176 // The static_cast here is needed to prevent a move, forcing a deep copy.
177 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
178 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700179}
180
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700181Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
182 int targetUid, int32_t flags, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700183 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700184 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700185 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100186 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800187 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700188 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700189 }
190
191 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700192 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), targetUid);
193
194 if (!lockedEntry) {
195 ALOGE("failed to grab lock on blob entry %u_%s", targetUid, name8.string());
196 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_ALREADY_EXISTS);
197 return Status::ok();
198 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700199
Yi Konge353f252018-07-30 01:38:39 -0700200 Blob keyBlob(&item[0], item.size(), nullptr, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700201 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
202
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700203 *aidl_return = static_cast<int32_t>(mKeyStore->put(lockedEntry, keyBlob, {}));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700204 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700205}
206
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700207Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700208 targetUid = getEffectiveUid(targetUid);
209 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700210 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
211 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700212 }
213 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000214 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700215 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
216 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700217 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
218 return Status::ok();
219 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700220
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700221 ResponseCode result = mKeyStore->del(lockedEntry);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400222
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700223 *aidl_return = static_cast<int32_t>(result);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700224 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700225}
226
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700227Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700228 targetUid = getEffectiveUid(targetUid);
229 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700230 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
231 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700232 }
233
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700234 LockedKeyBlobEntry lockedEntry =
235 mKeyStore->getLockedBlobEntryIfExists(String8(name).string(), targetUid);
236 *aidl_return =
237 static_cast<int32_t>(lockedEntry ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700238 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700239}
240
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700241Status KeyStoreService::list(const String16& prefix, int32_t targetUid,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700242 ::std::vector<::android::String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700243 targetUid = getEffectiveUid(targetUid);
244 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700245 return Status::fromServiceSpecificError(
246 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700247 }
248 const String8 prefix8(prefix);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700249 const std::string stdPrefix(prefix8.string());
250
251 ResponseCode rc;
252 std::list<LockedKeyBlobEntry> internal_matches;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800253 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700254
Janis Danisevskis265435f2018-11-16 14:10:46 -0800255 std::tie(rc, internal_matches) =
256 LockedKeyBlobEntry::list(userDirName, [&](uid_t uid, const std::string& alias) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700257 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end());
258 return uid == static_cast<uid_t>(targetUid) &&
259 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end())
260 .first == stdPrefix.end();
261 });
262
263 if (rc != ResponseCode::NO_ERROR) {
264 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700265 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700266
267 for (LockedKeyBlobEntry& entry : internal_matches) {
268 matches->push_back(String16(entry->alias().substr(prefix8.size()).c_str()));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700269 }
270 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700271}
272
Rob Barneseb7f79b2018-11-08 15:44:10 -0700273/*
274 * This method will return the uids of all auth bound keys for the calling user.
275 * This is intended to be used for alerting the user about which apps will be affected
276 * if the password/pin is removed. Only allowed to be called by system.
277 * The output is bound by the initial size of uidsOut to be compatible with Java.
278 */
Rob Barnes5d59e632018-12-07 16:09:02 -0700279Status KeyStoreService::listUidsOfAuthBoundKeys(std::vector<std::string>* uidsOut,
Rob Barneseb7f79b2018-11-08 15:44:10 -0700280 int32_t* aidl_return) {
281 const int32_t callingUid = IPCThreadState::self()->getCallingUid();
282 const int32_t userId = get_user_id(callingUid);
283 const int32_t appId = get_app_id(callingUid);
284 if (appId != AID_SYSTEM) {
285 ALOGE("Permission listUidsOfAuthBoundKeys denied for aid %d", appId);
286 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
287 return Status::ok();
288 }
289
290 const String8 prefix8("");
291 auto userState = mKeyStore->getUserStateDB().getUserState(userId);
292 const std::string userDirName = userState->getUserDirName();
293 auto encryptionKey = userState->getEncryptionKey();
294 auto state = userState->getState();
295 // unlock the user state
296 userState = {};
297
298 ResponseCode rc;
299 std::list<LockedKeyBlobEntry> internal_matches;
300 std::tie(rc, internal_matches) =
301 LockedKeyBlobEntry::list(userDirName, [&](uid_t, const std::string&) {
302 // Need to filter on auth bound state, so just return true.
303 return true;
304 });
305 if (rc != ResponseCode::NO_ERROR) {
306 ALOGE("Error listing blob entries for user %d", userId);
307 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
308 }
309
Rob Barneseb7f79b2018-11-08 15:44:10 -0700310 for (LockedKeyBlobEntry& entry : internal_matches) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700311 // Need to store uids as a list of strings because integer list output
312 // parameters is not supported in aidl-cpp.
313 std::string entryUid = std::to_string(entry->uid());
314 if (std::find(uidsOut->begin(), uidsOut->end(), entryUid) != uidsOut->end()) {
Rob Barneseb7f79b2018-11-08 15:44:10 -0700315 // uid already in list, skip
316 continue;
317 }
318
319 auto [rc, blob, charBlob] = entry.readBlobs(encryptionKey, state);
320 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::LOCKED) {
321 ALOGE("Error reading blob for key %s", entry->alias().c_str());
322 continue;
323 }
324
325 if (blob && blob.isEncrypted()) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700326 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700327 } else if (charBlob) {
328 auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
329 if (!success) {
330 ALOGE("Error reading blob characteristics for key %s", entry->alias().c_str());
331 continue;
332 }
333 if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
334 swEnforced.Contains(TAG_USER_SECURE_ID)) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700335 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700336 }
337 }
338 }
339 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
340 return Status::ok();
341}
342
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700343Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
344 int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700345 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700346 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
347 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700348 }
349
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700350 if (password.size() == 0) {
351 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
352 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700353 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
354 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700355 } else {
Pavel Grafovf9b53eb2019-02-06 17:16:21 +0000356 const String8 password8(password);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700357 switch (mKeyStore->getState(userId)) {
358 case ::STATE_UNINITIALIZED: {
359 // generate master key, encrypt with password, write to file,
360 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700361 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
362 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700363 }
364 case ::STATE_NO_ERROR: {
365 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700366 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
367 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700368 }
369 case ::STATE_LOCKED: {
370 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
371 mKeyStore->resetUser(userId, true);
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 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700376 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
377 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700378 }
379}
380
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700381Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700382 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700383 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
384 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700385 }
386
387 // Sanity check that the new user has an empty keystore.
388 if (!mKeyStore->isEmpty(userId)) {
389 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
390 }
391 // Unconditionally clear the keystore, just to be safe.
392 mKeyStore->resetUser(userId, false);
393 if (parentId != -1) {
394 // This profile must share the same master key password as the parent profile. Because the
395 // password of the parent profile is not known here, the best we can do is copy the parent's
396 // master key and master key file. This makes this profile use the same master key as the
397 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700398 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
399 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700400 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700401 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
402 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700403 }
404}
405
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700406Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700407 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700408 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
409 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700410 }
411
412 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700413 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
414 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700415}
416
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700417Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700418 if (!checkBinderPermission(P_LOCK)) {
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 State state = mKeyStore->getState(userId);
424 if (state != ::STATE_NO_ERROR) {
425 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700426 *aidl_return = static_cast<int32_t>(ResponseCode(state));
427 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700428 }
429
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700430 mKeyStore->getEnforcementPolicy().set_device_locked(true, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700431 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700432 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
433 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700434}
435
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700436Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700437 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700438 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
439 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700440 }
441
442 State state = mKeyStore->getState(userId);
443 if (state != ::STATE_LOCKED) {
444 switch (state) {
445 case ::STATE_NO_ERROR:
446 ALOGI("calling unlock when already unlocked, ignoring.");
447 break;
448 case ::STATE_UNINITIALIZED:
449 ALOGE("unlock called on uninitialized keystore.");
450 break;
451 default:
452 ALOGE("unlock called on keystore in unknown state: %d", state);
453 break;
454 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700455 *aidl_return = static_cast<int32_t>(ResponseCode(state));
456 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700457 }
458
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700459 mKeyStore->getEnforcementPolicy().set_device_locked(false, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700460 const String8 password8(pw);
461 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700462 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
463 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700464}
465
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700466Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700467 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700468 *aidl_return = static_cast<int32_t>(false);
469 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700470 }
471
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700472 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
473 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700474}
475
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700476Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
477 ::android::String16* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700478 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700479 auto result =
480 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100481 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700482 *aidl_return = String16();
483 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700484 }
485
486 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700487 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
488 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700489 *aidl_return = String16();
490 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700491 }
492
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700493 *aidl_return = String16(mKeyStore->addGrant(lockedEntry, granteeUid).c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700494 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700495}
496
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700497Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700498 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700499 KeyStoreServiceReturnCode result =
500 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100501 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800502 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700503 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700504 }
505
506 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700507
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700508 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
509 if (!lockedEntry) {
510 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700511 }
512
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700513 *aidl_return = mKeyStore->removeGrant(lockedEntry, granteeUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700514 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700515}
516
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700517Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700518 uid_t targetUid = getEffectiveUid(uid);
519 if (!checkBinderPermission(P_GET, targetUid)) {
520 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700521 *time = -1L;
522 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700523 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700524 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700525
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700526 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
527 if (!lockedEntry) {
528 ALOGW("could not access key with alias %s for getmtime", name8.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700529 *time = -1L;
530 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700531 }
532
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700533 std::string filename = lockedEntry->getKeyBlobPath();
534
535 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700536 if (fd < 0) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700537 ALOGW("could not open %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700538 *time = -1L;
539 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700540 }
541
542 struct stat s;
543 int ret = fstat(fd, &s);
544 close(fd);
545 if (ret == -1) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700546 ALOGW("could not stat %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700547 *time = -1L;
548 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700549 }
550
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700551 *time = static_cast<int64_t>(s.st_mtime);
552 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700553}
554
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700555Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
556 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
557 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700558}
559
Janis Danisevskis265435f2018-11-16 14:10:46 -0800560Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700561 uid_t targetUid = getEffectiveUid(targetUid64);
562 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800563 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700564 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000565 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700566
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700567 mKeyStore->removeAllGrantsToUid(targetUid);
568
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700569 ResponseCode rc;
570 std::list<LockedKeyBlobEntry> entries;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800571 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700572
573 // list has a fence making sure no workers are modifying blob files before iterating the
574 // data base. All returned entries are locked.
575 std::tie(rc, entries) = LockedKeyBlobEntry::list(
Janis Danisevskis265435f2018-11-16 14:10:46 -0800576 userDirName, [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700577
578 if (rc != ResponseCode::NO_ERROR) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800579 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700580 }
581
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700582 for (LockedKeyBlobEntry& lockedEntry : entries) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100583 if (get_app_id(targetUid) == AID_SYSTEM) {
584 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700585 Blob charBlob;
586 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
587 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100588 // Do not clear keys critical to device encryption under system uid.
589 continue;
590 }
591 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700592 mKeyStore->del(lockedEntry);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700593 }
Janis Danisevskis265435f2018-11-16 14:10:46 -0800594 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700595}
596
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600597Status KeyStoreService::addRngEntropy(
598 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
599 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
Janis Danisevskisc1460142017-12-18 16:48:46 -0800600 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
601 if (!device) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600602 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800603 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700604
Janis Danisevskisa359c672019-03-14 17:15:06 -0700605 device->addRngEntropy(entropy, [device, cb](Return<ErrorCode> rc) {
606 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device, rc)));
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600607 });
608
609 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700610}
611
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600612Status KeyStoreService::generateKey(
613 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
614 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
615 int uid, int flags, int32_t* _aidl_return) {
Max Biresef4f0672017-11-29 14:38:48 -0800616 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
617 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700618 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000619 auto logOnScopeExit = android::base::make_scope_guard([&] {
620 if (__android_log_security()) {
621 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600622 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000623 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
624 }
625 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100626 KeyStoreServiceReturnCode rc =
627 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
628 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600629 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700630 }
Rubin Xu67899de2017-04-21 19:15:13 +0100631 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
632 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600633 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100634 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700635
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700636 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700637 // TODO(jbires): remove uid checking upon implementation of b/25646100
Max Bires670467d2017-12-12 11:16:43 -0800638 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Biresef4f0672017-11-29 14:38:48 -0800639 originalUid != IPCThreadState::self()->getCallingUid()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600640 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700641 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600642 }
643
Janis Danisevskisc1460142017-12-18 16:48:46 -0800644 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
645 auto dev = mKeyStore->getDevice(securityLevel);
646 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600647 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800648 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400649
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100650 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700651 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
652 if (!lockedEntry) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600653 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100654 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400655
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700656 logOnScopeExit.Disable();
657
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600658 dev->generateKey(
659 std::move(lockedEntry), params.getParameters(), entropy, flags,
660 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
661 if (__android_log_security()) {
662 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
663 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
664 }
665 cb->onFinished(rc,
666 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
667 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700668
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600669 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700670}
671
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700672Status KeyStoreService::getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600673 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700674 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
Janis Danisevskis64ec1fe2018-02-26 16:47:21 -0800675 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600676 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700677
678 uid_t targetUid = getEffectiveUid(uid);
679 uid_t callingUid = IPCThreadState::self()->getCallingUid();
680 if (!is_granted_to(callingUid, targetUid)) {
681 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
682 targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600683 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700684 }
685
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700686 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700687
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700688 ResponseCode rc;
689 Blob keyBlob;
690 Blob charBlob;
691 LockedKeyBlobEntry lockedEntry;
Janis Danisevskisd714a672017-09-01 14:31:36 -0700692
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700693 std::tie(rc, keyBlob, charBlob, lockedEntry) =
694 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
695
696 if (rc != ResponseCode::NO_ERROR) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600697 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700698 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100699
Janis Danisevskisc1460142017-12-18 16:48:46 -0800700 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700701 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600702 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100703 }
704
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700705 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
706 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
707 // from keymaster. It may also upgrade the key blob.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700708 dev->getKeyCharacteristics(
709 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
710 std::move(charBlob),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600711 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
712 cb->onFinished(rc,
713 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700714 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100715
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600716 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700717}
718
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600719Status KeyStoreService::importKey(
720 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
721 const String16& name, const KeymasterArguments& params, int32_t format,
722 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700723 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000724 auto logOnScopeExit = android::base::make_scope_guard([&] {
725 if (__android_log_security()) {
726 android_log_event_list(SEC_TAG_KEY_IMPORTED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600727 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000728 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
729 }
730 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100731 KeyStoreServiceReturnCode rc =
732 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
733 if (!rc.isOk()) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700734 LOG(ERROR) << "permissission denied";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600735 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700736 }
Rubin Xu67899de2017-04-21 19:15:13 +0100737 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
738 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600739 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100740 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700741
Janis Danisevskisc1460142017-12-18 16:48:46 -0800742 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
743 auto dev = mKeyStore->getDevice(securityLevel);
744 if (!dev) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700745 LOG(ERROR) << "importKey - cound not get keymaster device";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600746 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800747 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700748
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700749 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700750 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
751 if (!lockedEntry) {
752 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
753 << " already exists.";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600754 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400755 }
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700756
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700757 logOnScopeExit.Disable();
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700758
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600759 dev->importKey(
760 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
761 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
762 if (__android_log_security()) {
763 android_log_event_list(SEC_TAG_KEY_IMPORTED)
764 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
765 }
766 cb->onFinished(rc,
767 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
768 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400769
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600770 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700771}
772
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600773Status KeyStoreService::exportKey(
774 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
775 const String16& name, int32_t format,
776 const ::android::security::keymaster::KeymasterBlob& clientId,
777 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
778 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700779
780 uid_t targetUid = getEffectiveUid(uid);
781 uid_t callingUid = IPCThreadState::self()->getCallingUid();
782 if (!is_granted_to(callingUid, targetUid)) {
783 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600784 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700785 }
786
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700787 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700788
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700789 KeyStoreServiceReturnCode rc;
790 Blob keyBlob;
791 Blob charBlob;
792 LockedKeyBlobEntry lockedEntry;
793
794 std::tie(rc, keyBlob, charBlob, lockedEntry) =
795 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskis3cf85322018-11-19 13:37:49 -0800796 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600797 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700798 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100799
Janis Danisevskisc1460142017-12-18 16:48:46 -0800800 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100801
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700802 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600803 std::move(keyBlob), std::move(charBlob),
804 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
Ji Wang2c142312016-10-14 17:21:10 +0800805
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600806 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700807}
808
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600809Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
810 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700811 bool pruneable, const KeymasterArguments& params,
812 const ::std::vector<uint8_t>& entropy, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600813 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700814 uid_t callingUid = IPCThreadState::self()->getCallingUid();
815 uid_t targetUid = getEffectiveUid(uid);
816 if (!is_granted_to(callingUid, targetUid)) {
817 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600818 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700819 }
820 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
821 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600822 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700823 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700824 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600825 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700826 }
Shawn Willden0329a822017-12-04 13:55:14 -0700827
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700828 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700829 Blob keyBlob;
830 Blob charBlob;
831 LockedKeyBlobEntry lockedEntry;
832 ResponseCode rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100833
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700834 std::tie(rc, keyBlob, charBlob, lockedEntry) =
835 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
836
837 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600838 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700839 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600840 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700841
Janis Danisevskisc1460142017-12-18 16:48:46 -0800842 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700843 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100844
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700845 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
846 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600847 [this, cb, dev](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700848 if (result_.resultCode.isOk() ||
849 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700850 mKeyStore->addOperationDevice(result_.token, dev);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700851 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600852 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700853 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400854
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600855 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700856}
857
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600858Status KeyStoreService::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
859 const ::android::sp<::android::IBinder>& token,
860 const ::android::security::keymaster::KeymasterArguments& params,
861 const ::std::vector<uint8_t>& input, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700862 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600863 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700864 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700865
Janis Danisevskisbec89992019-08-14 13:42:19 -0700866 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700867 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600868 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700869 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700870
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600871 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700872 if (!result_.resultCode.isOk()) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700873 mKeyStore->removeOperationDevice(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100874 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600875 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700876 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100877
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600878 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700879}
880
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600881Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
882 const ::android::sp<::android::IBinder>& token,
883 const ::android::security::keymaster::KeymasterArguments& params,
Rob Barnes3af223f2019-11-14 14:50:30 -0700884 const ::std::vector<uint8_t>& input,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700885 const ::std::vector<uint8_t>& signature,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600886 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700887 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600888 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700889 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700890
Janis Danisevskisbec89992019-08-14 13:42:19 -0700891 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700892 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600893 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700894 }
895
Rob Barnes3af223f2019-11-14 14:50:30 -0700896 dev->finish(token, params.getParameters(), input, signature, entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600897 [this, cb, token](OperationResult result_) {
Janis Danisevskis8c4c1d62019-10-04 11:01:54 -0700898 mKeyStore->removeOperationDevice(token);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600899 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700900 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700901
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::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
906 const ::android::sp<::android::IBinder>& token,
907 int32_t* _aidl_return) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700908 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700909 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600910 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700911 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100912
Janis Danisevskisbec89992019-08-14 13:42:19 -0700913 dev->abort(token, [this, cb, token](KeyStoreServiceReturnCode rc) {
914 mKeyStore->removeOperationDevice(token);
915 cb->onFinished(rc);
916 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700917
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600918 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700919}
920
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700921Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000922 int32_t* aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700923
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000924 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
925 // receive a HardwareAuthToken, rather than an opaque byte array.
926
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700927 if (!checkBinderPermission(P_ADD_AUTH)) {
928 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700929 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
930 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700931 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700932 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
Branden Archer70080742018-11-20 11:04:11 -0800933 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700934 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000935 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100936
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000937 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700938 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000939 if (authToken.version != 0) {
Branden Archer70080742018-11-20 11:04:11 -0800940 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700941 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000942 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100943
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700944 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
945 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700946 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
947 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700948}
949
David Zeuthenab3e5652019-10-28 13:32:48 -0400950Status KeyStoreService::getAuthTokenForCredstore(int64_t challenge, int64_t secureUserId,
951 int32_t authTokenMaxAgeMillis,
952 std::vector<uint8_t>* _aidl_return) {
953 uid_t callingUid = IPCThreadState::self()->getCallingUid();
954 if (callingUid != AID_CREDSTORE) {
955 return Status::fromServiceSpecificError(static_cast<int32_t>(0));
956 }
957
958 auto [err, authToken] = mKeyStore->getAuthTokenTable().FindAuthorizationForCredstore(
959 challenge, secureUserId, authTokenMaxAgeMillis);
960 std::vector<uint8_t> ret;
961 if (err == AuthTokenTable::OK) {
962 ret = android::hardware::keymaster::V4_0::support::authToken2HidlVec(authToken);
963 }
964 *_aidl_return = ret;
965 return Status::ok();
966}
967
Eran Messerid9f8ae52018-10-24 13:54:00 +0100968bool isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -0700969 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700970 for (size_t i = 0; i < paramsVec.size(); ++i) {
971 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -0600972 case Tag::ATTESTATION_ID_BRAND:
973 case Tag::ATTESTATION_ID_DEVICE:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600974 case Tag::ATTESTATION_ID_MANUFACTURER:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600975 case Tag::ATTESTATION_ID_MODEL:
976 case Tag::ATTESTATION_ID_PRODUCT:
Rubin Xu1a203e32018-05-08 14:25:21 +0100977 case Tag::ATTESTATION_ID_IMEI:
978 case Tag::ATTESTATION_ID_MEID:
979 case Tag::ATTESTATION_ID_SERIAL:
Eran Messerid9f8ae52018-10-24 13:54:00 +0100980 return true;
Rubin Xu1a203e32018-05-08 14:25:21 +0100981 default:
982 continue;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100983 }
984 }
Eran Messerid9f8ae52018-10-24 13:54:00 +0100985 return false;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100986}
987
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600988Status KeyStoreService::attestKey(
989 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
990 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700991 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
992 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600993 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -0700994 }
995
Eran Messerie2c34152017-12-21 21:01:22 +0000996 uid_t callingUid = IPCThreadState::self()->getCallingUid();
997
Eran Messerid9f8ae52018-10-24 13:54:00 +0100998 if (isDeviceIdAttestationRequested(params) && (get_app_id(callingUid) != AID_SYSTEM)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600999 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001000 }
1001
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001002 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001003 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1004 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001005 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001006 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001007
Shawn Willden50eb1b22016-01-21 12:41:23 -07001008 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001009 Blob keyBlob;
1010 Blob charBlob;
1011 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001012
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001013 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1014 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1015
Janis Danisevskis9dff56c2019-07-10 14:08:06 -07001016 if (!rc.isOk()) {
1017 return AIDL_RETURN(rc);
1018 }
1019
Janis Danisevskisc1460142017-12-18 16:48:46 -08001020 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001021 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001022 dev->attestKey(
1023 std::move(hidlKey), mutableParams.hidl_data(),
Janis Danisevskisa359c672019-03-14 17:15:06 -07001024 [dev, cb](Return<void> rc,
1025 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001026 auto& [ret, certChain] = hidlResult;
1027 if (!rc.isOk()) {
1028 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1029 } else if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001030 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001031 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1032 } else {
1033 cb->onFinished(KeyStoreServiceReturnCode(ret),
1034 KeymasterCertificateChain(std::move(certChain)));
1035 }
1036 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001037
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001038 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001039}
1040
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001041// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1042// It should never be redefined by a build system though.
1043#ifndef CAPTURE_MOVE
1044#define CAPTURE_MOVE(x) x = std::move(x)
1045#endif
1046
1047Status KeyStoreService::attestDeviceIds(
1048 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1049 const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001050 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001051
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001052 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001053 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001054 }
1055
1056 if (!isDeviceIdAttestationRequested(params)) {
1057 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001058 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001059 }
1060
1061 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1062 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
Yi Konge353f252018-07-30 01:38:39 -07001063 if (binder == nullptr) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001064 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001065 }
1066 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1067 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1068 IPCThreadState::self()->getCallingPid(), callingUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001069 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001070 }
1071
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001072 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001073 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1074 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001075 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001076 }
1077
1078 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001079 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001080
Shawn Willden70c1a782018-07-11 15:13:20 -06001081 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001082 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001083 }
1084
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001085
1086 AuthorizationSet keyCharacteristics;
1087 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1088 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1089 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1090 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1091 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001092
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001093 std::promise<KeyStoreServiceReturnCode> resultPromise;
1094 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001095
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001096 dev->generateKey(
1097 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001098 [cb, dev, CAPTURE_MOVE(mutableParams)](
1099 Return<void> rc,
1100 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001101 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1102 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1103 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001104 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001105 return;
1106 }
1107 if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001108 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001109 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001110 return;
1111 }
1112 dev->attestKey(
1113 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001114 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001115 hidlKeyBlob](Return<void> rc,
1116 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1117 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001118 // schedule temp key for deletion
Janis Danisevskisa359c672019-03-14 17:15:06 -07001119 dev->deleteKey(std::move(hidlKeyBlob), [dev](Return<ErrorCode> rc) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001120 // log error but don't return an error
Janis Danisevskisa359c672019-03-14 17:15:06 -07001121 KS_HANDLE_HIDL_ERROR(dev, rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001122 });
1123 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001124 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001125 return;
1126 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001127 if (ret == ErrorCode::OK) {
1128 cb->onFinished(
1129 KeyStoreServiceReturnCode(ret),
1130 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1131 } else {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001132 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001133 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001134 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001135 });
1136 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001137
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001138 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001139}
1140
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001141Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001142 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001143 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001144 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1145 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001146}
1147
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001148Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001149 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001150 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1151 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1152 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001153 int32_t* _aidl_return) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001154
1155 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1156
1157 if (!checkBinderPermission(P_INSERT, callingUid)) {
1158 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1159 }
1160
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001161 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001162
1163 KeyStoreServiceReturnCode rc;
1164 Blob wrappingKeyBlob;
1165 Blob wrappingCharBlob;
1166 LockedKeyBlobEntry wrappingLockedEntry;
1167
1168 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1169 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
Branden Archerd166a882018-11-20 10:56:48 -08001170 if (!rc.isOk()) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001171 return AIDL_RETURN(rc);
1172 }
1173
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001174 String8 wrappedKeyName8(wrappedKeyAlias);
1175 auto wrappedLockedEntry =
1176 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1177 if (!wrappedLockedEntry) {
1178 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1179 }
1180
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001181 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1182 auto dev = mKeyStore->getDevice(securityLevel);
1183 if (!dev) {
1184 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1185 }
1186
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001187 dev->importWrappedKey(
1188 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1189 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001190 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1191 cb->onFinished(rc,
1192 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001193 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001194
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001195 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001196}
1197
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001198Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1199 const String16& promptText,
1200 const ::std::vector<uint8_t>& extraData,
1201 const String16& locale, int32_t uiOptionsAsFlags,
1202 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001203 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1204 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001205}
1206
1207Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1208 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001209 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001210}
1211
David Zeuthen1a492312018-02-26 11:00:30 -05001212Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001213 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001214}
1215
1216/**
1217 * Get the effective target uid for a binder operation that takes an
1218 * optional uid as the target.
1219 */
1220uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1221 if (targetUid == UID_SELF) {
1222 return IPCThreadState::self()->getCallingUid();
1223 }
1224 return static_cast<uid_t>(targetUid);
1225}
1226
1227/**
1228 * Check if the caller of the current binder method has the required
1229 * permission and if acting on other uids the grants to do so.
1230 */
1231bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1232 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1233 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001234 const char* ssid = IPCThreadState::self()->getCallingSid();
1235 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001236 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1237 return false;
1238 }
1239 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1240 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1241 return false;
1242 }
1243 return true;
1244}
1245
1246/**
1247 * Check if the caller of the current binder method has the required
1248 * permission and the target uid is the caller or the caller is system.
1249 */
1250bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1251 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1252 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001253 const char* ssid = IPCThreadState::self()->getCallingSid();
1254 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001255 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1256 return false;
1257 }
1258 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1259}
1260
1261/**
1262 * Check if the caller of the current binder method has the required
1263 * permission or the target of the operation is the caller's uid. This is
1264 * for operation where the permission is only for cross-uid activity and all
1265 * uids are allowed to act on their own (ie: clearing all entries for a
1266 * given uid).
1267 */
1268bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1269 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1270 if (getEffectiveUid(targetUid) == callingUid) {
1271 return true;
1272 } else {
1273 return checkBinderPermission(permission, targetUid);
1274 }
1275}
1276
1277/**
1278 * Helper method to check that the caller has the required permission as
1279 * well as the keystore is in the unlocked state if checkUnlocked is true.
1280 *
1281 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1282 * otherwise the state of keystore when not unlocked and checkUnlocked is
1283 * true.
1284 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001285KeyStoreServiceReturnCode
1286KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1287 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001288 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001289 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001290 }
1291 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1292 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001293 // All State values coincide with ResponseCodes
1294 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001295 }
1296
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001297 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001298}
1299
1300bool KeyStoreService::isKeystoreUnlocked(State state) {
1301 switch (state) {
1302 case ::STATE_NO_ERROR:
1303 return true;
1304 case ::STATE_UNINITIALIZED:
1305 case ::STATE_LOCKED:
1306 return false;
1307 }
1308 return false;
1309}
1310
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001311/**
Shawn Willden0329a822017-12-04 13:55:14 -07001312 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1313 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001314 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001315bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1316 for (size_t i = 0; i < params.size(); ++i) {
1317 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001318 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001319 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001320 return false;
1321 default:
1322 break;
1323 }
1324 }
1325 return true;
1326}
1327
Brian Young9a947d52018-02-23 18:03:14 +00001328Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
1329 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001330 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Brian Young9a947d52018-02-23 18:03:14 +00001331 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001332
1333 return Status::ok();
1334}
1335
Shawn Willdene2a7b522017-04-11 09:27:40 -06001336} // namespace keystore