blob: 4e5bc48cd03916e0aa036e382bc7aac49b17d06e [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"
Hasini Gunasinghe8c8c2d42020-06-23 17:17:47 +000044#include "key_attestation_log_handler.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"
David Zeuthenf2a28672020-01-30 16:20:07 -050047#include <keystore/keystore_attestation_id.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;
David Zeuthen59102f32020-05-08 10:58:09 -040060using android::hardware::keymaster::V4_0::support::authToken2HidlVec;
61using android::hardware::keymaster::V4_0::support::serializeVerificationToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070062using android::security::keymaster::ExportResult;
63using android::security::keymaster::KeymasterArguments;
64using android::security::keymaster::KeymasterBlob;
65using android::security::keymaster::KeymasterCertificateChain;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070066using android::security::keymaster::operationFailed;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070067using android::security::keymaster::OperationResult;
David Zeuthenc6eb7cd2017-11-27 11:33:55 -050068using ConfirmationResponseCode = android::hardware::confirmationui::V1_0::ResponseCode;
David Zeuthen59102f32020-05-08 10:58:09 -040069using ::android::security::keystore::ICredstoreTokenCallback;
Rob Barnesbb6cabd2018-10-04 17:10:37 -060070using ::android::security::keystore::IKeystoreOperationResultCallback;
71using ::android::security::keystore::IKeystoreResponseCallback;
72using ::android::security::keystore::KeystoreResponse;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070073
Shawn Willdene2a7b522017-04-11 09:27:40 -060074constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
75const char* kTimestampFilePath = "timestamp";
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070076
Shawn Willdene2a7b522017-04-11 09:27:40 -060077bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070078 return params.end() !=
79 std::find_if(params.begin(), params.end(),
80 [&](const KeyParameter& param) { return param.tag == tag; });
Shawn Willdend5a24e62017-02-28 13:53:24 -070081}
82
Branden Archer70080742018-11-20 11:04:11 -080083#define AIDL_RETURN(rc) (*_aidl_return = KeyStoreServiceReturnCode(rc).getErrorCode(), Status::ok())
Rob Barnesbb6cabd2018-10-04 17:10:37 -060084
Shawn Willdene2a7b522017-04-11 09:27:40 -060085std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
86 struct stat sbuf;
87 if (stat(kTimestampFilePath, &sbuf) == 0) {
Yi Konge353f252018-07-30 01:38:39 -070088 double diff_secs = difftime(time(nullptr), sbuf.st_ctime);
Shawn Willdene2a7b522017-04-11 09:27:40 -060089 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
90 }
91
92 if (errno != ENOENT) {
93 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
94 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
95 }
96
97 int fd = creat(kTimestampFilePath, 0600);
98 if (fd < 0) {
99 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
100 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
101 }
102
103 if (close(fd)) {
104 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
105 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
106 }
107
108 return {ResponseCode::NO_ERROR, true};
109}
110
Eran Messeri03fc4c82018-08-16 18:53:15 +0100111using ::android::security::KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200112
113KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
114 KeyStoreServiceReturnCode responseCode;
115 bool factoryResetSinceIdRotation;
116 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
117
118 if (!responseCode.isOk()) return responseCode;
119 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
120
121 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
122 if (!asn1_attestation_id_result.isOk()) {
123 ALOGE("failed to gather attestation_id");
Shawn Willden6f7d27c2019-09-11 22:51:46 -0600124 // Couldn't get attestation ID; just use an empty one rather than failing.
125 asn1_attestation_id_result = std::vector<uint8_t>();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200126 }
127 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
128
129 /*
Eran Messeri03fc4c82018-08-16 18:53:15 +0100130 * The attestation application ID must not be longer than
131 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, error out if gather_attestation_application_id
132 * returned such an invalid vector.
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200133 */
134 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Eran Messeri03fc4c82018-08-16 18:53:15 +0100135 ALOGE("BUG: Gathered Attestation Application ID is too big (%d)",
136 static_cast<int32_t>(asn1_attestation_id.size()));
137 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200138 }
139
140 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
141
142 return ResponseCode::NO_ERROR;
143}
144
Shawn Willdene2a7b522017-04-11 09:27:40 -0600145} // anonymous namespace
146
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700147Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700148 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700149 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
150 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700151 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700152 *aidl_return = mKeyStore->getState(userId);
153 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700154}
155
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700156Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700157 uid_t targetUid = getEffectiveUid(uid);
158 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700159 // see keystore/keystore.h
160 return Status::fromServiceSpecificError(
161 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700162 }
163
164 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700165 ResponseCode rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700166 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700167 Blob charBlob;
168 LockedKeyBlobEntry lockedEntry;
169
170 std::tie(rc, keyBlob, charBlob, lockedEntry) =
171 mKeyStore->getKeyForName(name8, targetUid, TYPE_GENERIC);
172 if (rc != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700173 *item = ::std::vector<uint8_t>();
174 // Return empty array if key is not found
175 // TODO: consider having returned value nullable or parse exception on the client.
176 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700177 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100178 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700179 // The static_cast here is needed to prevent a move, forcing a deep copy.
180 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
181 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700182}
183
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700184Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
185 int targetUid, int32_t flags, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700186 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700187 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700188 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100189 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800190 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700191 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700192 }
193
194 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700195 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), targetUid);
196
197 if (!lockedEntry) {
198 ALOGE("failed to grab lock on blob entry %u_%s", targetUid, name8.string());
199 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_ALREADY_EXISTS);
200 return Status::ok();
201 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700202
Yi Konge353f252018-07-30 01:38:39 -0700203 Blob keyBlob(&item[0], item.size(), nullptr, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700204 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
205
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700206 *aidl_return = static_cast<int32_t>(mKeyStore->put(lockedEntry, keyBlob, {}));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700207 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700208}
209
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700210Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700211 targetUid = getEffectiveUid(targetUid);
212 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700213 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
214 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700215 }
216 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000217 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700218 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
219 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700220 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
221 return Status::ok();
222 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700223
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700224 ResponseCode result = mKeyStore->del(lockedEntry);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400225
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700226 *aidl_return = static_cast<int32_t>(result);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700227 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700228}
229
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700230Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700231 targetUid = getEffectiveUid(targetUid);
232 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700233 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
234 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700235 }
236
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700237 LockedKeyBlobEntry lockedEntry =
238 mKeyStore->getLockedBlobEntryIfExists(String8(name).string(), targetUid);
239 *aidl_return =
240 static_cast<int32_t>(lockedEntry ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700241 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700242}
243
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700244Status KeyStoreService::list(const String16& prefix, int32_t targetUid,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700245 ::std::vector<::android::String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700246 targetUid = getEffectiveUid(targetUid);
247 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700248 return Status::fromServiceSpecificError(
249 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700250 }
251 const String8 prefix8(prefix);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700252 const std::string stdPrefix(prefix8.string());
253
254 ResponseCode rc;
255 std::list<LockedKeyBlobEntry> internal_matches;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800256 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700257
Janis Danisevskis265435f2018-11-16 14:10:46 -0800258 std::tie(rc, internal_matches) =
259 LockedKeyBlobEntry::list(userDirName, [&](uid_t uid, const std::string& alias) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700260 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end());
261 return uid == static_cast<uid_t>(targetUid) &&
262 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end())
263 .first == stdPrefix.end();
264 });
265
266 if (rc != ResponseCode::NO_ERROR) {
267 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700268 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700269
270 for (LockedKeyBlobEntry& entry : internal_matches) {
271 matches->push_back(String16(entry->alias().substr(prefix8.size()).c_str()));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700272 }
273 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700274}
275
Rob Barneseb7f79b2018-11-08 15:44:10 -0700276/*
277 * This method will return the uids of all auth bound keys for the calling user.
278 * This is intended to be used for alerting the user about which apps will be affected
279 * if the password/pin is removed. Only allowed to be called by system.
280 * The output is bound by the initial size of uidsOut to be compatible with Java.
281 */
Rob Barnes5d59e632018-12-07 16:09:02 -0700282Status KeyStoreService::listUidsOfAuthBoundKeys(std::vector<std::string>* uidsOut,
Rob Barneseb7f79b2018-11-08 15:44:10 -0700283 int32_t* aidl_return) {
284 const int32_t callingUid = IPCThreadState::self()->getCallingUid();
285 const int32_t userId = get_user_id(callingUid);
286 const int32_t appId = get_app_id(callingUid);
287 if (appId != AID_SYSTEM) {
288 ALOGE("Permission listUidsOfAuthBoundKeys denied for aid %d", appId);
289 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
290 return Status::ok();
291 }
292
293 const String8 prefix8("");
294 auto userState = mKeyStore->getUserStateDB().getUserState(userId);
295 const std::string userDirName = userState->getUserDirName();
296 auto encryptionKey = userState->getEncryptionKey();
297 auto state = userState->getState();
298 // unlock the user state
299 userState = {};
300
301 ResponseCode rc;
302 std::list<LockedKeyBlobEntry> internal_matches;
303 std::tie(rc, internal_matches) =
304 LockedKeyBlobEntry::list(userDirName, [&](uid_t, const std::string&) {
305 // Need to filter on auth bound state, so just return true.
306 return true;
307 });
308 if (rc != ResponseCode::NO_ERROR) {
309 ALOGE("Error listing blob entries for user %d", userId);
310 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
311 }
312
Rob Barneseb7f79b2018-11-08 15:44:10 -0700313 for (LockedKeyBlobEntry& entry : internal_matches) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700314 // Need to store uids as a list of strings because integer list output
315 // parameters is not supported in aidl-cpp.
316 std::string entryUid = std::to_string(entry->uid());
317 if (std::find(uidsOut->begin(), uidsOut->end(), entryUid) != uidsOut->end()) {
Rob Barneseb7f79b2018-11-08 15:44:10 -0700318 // uid already in list, skip
319 continue;
320 }
321
322 auto [rc, blob, charBlob] = entry.readBlobs(encryptionKey, state);
323 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::LOCKED) {
324 ALOGE("Error reading blob for key %s", entry->alias().c_str());
325 continue;
326 }
327
328 if (blob && blob.isEncrypted()) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700329 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700330 } else if (charBlob) {
331 auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
332 if (!success) {
333 ALOGE("Error reading blob characteristics for key %s", entry->alias().c_str());
334 continue;
335 }
336 if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
337 swEnforced.Contains(TAG_USER_SECURE_ID)) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700338 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700339 }
340 }
341 }
342 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
343 return Status::ok();
344}
345
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700346Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
347 int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700348 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700349 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
350 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700351 }
352
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700353 if (password.size() == 0) {
354 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
355 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700356 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
357 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700358 } else {
Pavel Grafovf9b53eb2019-02-06 17:16:21 +0000359 const String8 password8(password);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700360 switch (mKeyStore->getState(userId)) {
361 case ::STATE_UNINITIALIZED: {
362 // generate master key, encrypt with password, write to file,
363 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700364 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
365 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700366 }
367 case ::STATE_NO_ERROR: {
368 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700369 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
370 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700371 }
372 case ::STATE_LOCKED: {
373 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
374 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700375 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
376 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700377 }
378 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700379 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
380 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700381 }
382}
383
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700384Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700385 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700386 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
387 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700388 }
389
390 // Sanity check that the new user has an empty keystore.
391 if (!mKeyStore->isEmpty(userId)) {
392 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
393 }
394 // Unconditionally clear the keystore, just to be safe.
395 mKeyStore->resetUser(userId, false);
396 if (parentId != -1) {
397 // This profile must share the same master key password as the parent profile. Because the
398 // password of the parent profile is not known here, the best we can do is copy the parent's
399 // master key and master key file. This makes this profile use the same master key as the
400 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700401 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
402 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700403 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700404 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
405 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700406 }
407}
408
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700409Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700410 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700411 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
412 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700413 }
414
415 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700416 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
417 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700418}
419
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700420Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700421 if (!checkBinderPermission(P_LOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700422 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
423 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700424 }
425
426 State state = mKeyStore->getState(userId);
427 if (state != ::STATE_NO_ERROR) {
428 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700429 *aidl_return = static_cast<int32_t>(ResponseCode(state));
430 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700431 }
432
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700433 mKeyStore->getEnforcementPolicy().set_device_locked(true, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700434 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700435 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
436 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700437}
438
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700439Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700440 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700441 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
442 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700443 }
444
445 State state = mKeyStore->getState(userId);
446 if (state != ::STATE_LOCKED) {
447 switch (state) {
448 case ::STATE_NO_ERROR:
449 ALOGI("calling unlock when already unlocked, ignoring.");
450 break;
451 case ::STATE_UNINITIALIZED:
452 ALOGE("unlock called on uninitialized keystore.");
453 break;
454 default:
455 ALOGE("unlock called on keystore in unknown state: %d", state);
456 break;
457 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700458 *aidl_return = static_cast<int32_t>(ResponseCode(state));
459 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700460 }
461
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700462 mKeyStore->getEnforcementPolicy().set_device_locked(false, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700463 const String8 password8(pw);
464 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700465 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
466 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700467}
468
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700469Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700470 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700471 *aidl_return = static_cast<int32_t>(false);
472 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700473 }
474
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700475 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
476 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700477}
478
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700479Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
480 ::android::String16* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700481 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700482 auto result =
483 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100484 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700485 *aidl_return = String16();
486 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700487 }
488
489 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700490 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
491 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700492 *aidl_return = String16();
493 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700494 }
495
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700496 *aidl_return = String16(mKeyStore->addGrant(lockedEntry, granteeUid).c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700497 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700498}
499
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700500Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700501 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700502 KeyStoreServiceReturnCode result =
503 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100504 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800505 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700506 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700507 }
508
509 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700510
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700511 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
512 if (!lockedEntry) {
513 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700514 }
515
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700516 *aidl_return = mKeyStore->removeGrant(lockedEntry, granteeUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700517 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700518}
519
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700520Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700521 uid_t targetUid = getEffectiveUid(uid);
522 if (!checkBinderPermission(P_GET, targetUid)) {
523 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700524 *time = -1L;
525 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700526 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700527 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700528
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700529 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
530 if (!lockedEntry) {
531 ALOGW("could not access key with alias %s for getmtime", name8.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700532 *time = -1L;
533 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700534 }
535
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700536 std::string filename = lockedEntry->getKeyBlobPath();
537
538 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700539 if (fd < 0) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700540 ALOGW("could not open %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700541 *time = -1L;
542 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700543 }
544
545 struct stat s;
546 int ret = fstat(fd, &s);
547 close(fd);
548 if (ret == -1) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700549 ALOGW("could not stat %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700550 *time = -1L;
551 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700552 }
553
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700554 *time = static_cast<int64_t>(s.st_mtime);
555 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700556}
557
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700558Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
559 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
560 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700561}
562
Janis Danisevskis265435f2018-11-16 14:10:46 -0800563Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700564 uid_t targetUid = getEffectiveUid(targetUid64);
565 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800566 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700567 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000568 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700569
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700570 mKeyStore->removeAllGrantsToUid(targetUid);
571
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700572 ResponseCode rc;
573 std::list<LockedKeyBlobEntry> entries;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800574 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700575
576 // list has a fence making sure no workers are modifying blob files before iterating the
577 // data base. All returned entries are locked.
578 std::tie(rc, entries) = LockedKeyBlobEntry::list(
Janis Danisevskis265435f2018-11-16 14:10:46 -0800579 userDirName, [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700580
581 if (rc != ResponseCode::NO_ERROR) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800582 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700583 }
584
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700585 for (LockedKeyBlobEntry& lockedEntry : entries) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100586 if (get_app_id(targetUid) == AID_SYSTEM) {
587 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700588 Blob charBlob;
589 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
590 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100591 // Do not clear keys critical to device encryption under system uid.
592 continue;
593 }
594 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700595 mKeyStore->del(lockedEntry);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700596 }
Janis Danisevskis265435f2018-11-16 14:10:46 -0800597 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700598}
599
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600600Status KeyStoreService::addRngEntropy(
601 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
602 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
Janis Danisevskisc1460142017-12-18 16:48:46 -0800603 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
604 if (!device) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600605 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800606 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700607
Janis Danisevskisa359c672019-03-14 17:15:06 -0700608 device->addRngEntropy(entropy, [device, cb](Return<ErrorCode> rc) {
609 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device, rc)));
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600610 });
611
612 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700613}
614
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600615Status KeyStoreService::generateKey(
616 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
617 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
618 int uid, int flags, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700619 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000620 auto logOnScopeExit = android::base::make_scope_guard([&] {
621 if (__android_log_security()) {
622 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600623 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000624 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
625 }
626 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100627 KeyStoreServiceReturnCode rc =
628 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
629 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600630 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700631 }
Rubin Xu67899de2017-04-21 19:15:13 +0100632 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
633 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600634 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100635 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700636
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700637 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Max Bires36ae17f2019-11-12 21:34:24 +0000638 if (!checkBinderPermission(P_GEN_UNIQUE_ID)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600639 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700640 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600641 }
642
Janis Danisevskisc1460142017-12-18 16:48:46 -0800643 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
644 auto dev = mKeyStore->getDevice(securityLevel);
645 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600646 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800647 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400648
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100649 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700650 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
651 if (!lockedEntry) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600652 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100653 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400654
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700655 logOnScopeExit.Disable();
656
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600657 dev->generateKey(
658 std::move(lockedEntry), params.getParameters(), entropy, flags,
659 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
660 if (__android_log_security()) {
661 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
662 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
663 }
664 cb->onFinished(rc,
665 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
666 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700667
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600668 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700669}
670
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700671Status KeyStoreService::getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600672 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700673 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
Janis Danisevskis64ec1fe2018-02-26 16:47:21 -0800674 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600675 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700676
677 uid_t targetUid = getEffectiveUid(uid);
678 uid_t callingUid = IPCThreadState::self()->getCallingUid();
679 if (!is_granted_to(callingUid, targetUid)) {
680 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
681 targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600682 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700683 }
684
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700685 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700686
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700687 ResponseCode rc;
688 Blob keyBlob;
689 Blob charBlob;
690 LockedKeyBlobEntry lockedEntry;
Janis Danisevskisd714a672017-09-01 14:31:36 -0700691
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700692 std::tie(rc, keyBlob, charBlob, lockedEntry) =
693 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
694
695 if (rc != ResponseCode::NO_ERROR) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600696 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700697 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100698
Janis Danisevskisc1460142017-12-18 16:48:46 -0800699 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700700 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600701 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100702 }
703
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700704 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
705 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
706 // from keymaster. It may also upgrade the key blob.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700707 dev->getKeyCharacteristics(
708 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
709 std::move(charBlob),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600710 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
711 cb->onFinished(rc,
712 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700713 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100714
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600715 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700716}
717
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600718Status KeyStoreService::importKey(
719 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
720 const String16& name, const KeymasterArguments& params, int32_t format,
721 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700722 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000723 auto logOnScopeExit = android::base::make_scope_guard([&] {
724 if (__android_log_security()) {
725 android_log_event_list(SEC_TAG_KEY_IMPORTED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600726 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000727 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
728 }
729 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100730 KeyStoreServiceReturnCode rc =
731 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
732 if (!rc.isOk()) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700733 LOG(ERROR) << "permissission denied";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600734 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700735 }
Rubin Xu67899de2017-04-21 19:15:13 +0100736 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
737 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600738 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100739 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700740
Janis Danisevskisc1460142017-12-18 16:48:46 -0800741 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
742 auto dev = mKeyStore->getDevice(securityLevel);
743 if (!dev) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700744 LOG(ERROR) << "importKey - cound not get keymaster device";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600745 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800746 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700747
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700748 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700749 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
750 if (!lockedEntry) {
751 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
752 << " already exists.";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600753 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400754 }
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700755
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700756 logOnScopeExit.Disable();
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700757
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600758 dev->importKey(
759 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
760 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
761 if (__android_log_security()) {
762 android_log_event_list(SEC_TAG_KEY_IMPORTED)
763 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
764 }
765 cb->onFinished(rc,
766 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
767 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400768
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600769 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700770}
771
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600772Status KeyStoreService::exportKey(
773 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
774 const String16& name, int32_t format,
775 const ::android::security::keymaster::KeymasterBlob& clientId,
776 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
777 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700778
779 uid_t targetUid = getEffectiveUid(uid);
780 uid_t callingUid = IPCThreadState::self()->getCallingUid();
781 if (!is_granted_to(callingUid, targetUid)) {
782 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600783 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700784 }
785
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700786 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700787
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700788 KeyStoreServiceReturnCode rc;
789 Blob keyBlob;
790 Blob charBlob;
791 LockedKeyBlobEntry lockedEntry;
792
793 std::tie(rc, keyBlob, charBlob, lockedEntry) =
794 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskis3cf85322018-11-19 13:37:49 -0800795 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600796 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700797 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100798
Janis Danisevskisc1460142017-12-18 16:48:46 -0800799 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100800
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700801 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600802 std::move(keyBlob), std::move(charBlob),
803 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
Ji Wang2c142312016-10-14 17:21:10 +0800804
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600805 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700806}
807
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600808Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
809 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700810 bool pruneable, const KeymasterArguments& params,
811 const ::std::vector<uint8_t>& entropy, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600812 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700813 uid_t callingUid = IPCThreadState::self()->getCallingUid();
814 uid_t targetUid = getEffectiveUid(uid);
815 if (!is_granted_to(callingUid, targetUid)) {
816 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600817 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700818 }
819 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
820 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600821 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700822 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700823 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600824 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700825 }
Shawn Willden0329a822017-12-04 13:55:14 -0700826
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700827 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700828 Blob keyBlob;
829 Blob charBlob;
830 LockedKeyBlobEntry lockedEntry;
831 ResponseCode rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100832
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700833 std::tie(rc, keyBlob, charBlob, lockedEntry) =
834 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
835
836 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600837 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700838 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600839 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700840
Janis Danisevskisc1460142017-12-18 16:48:46 -0800841 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700842 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100843
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700844 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
845 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600846 [this, cb, dev](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700847 if (result_.resultCode.isOk() ||
848 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700849 mKeyStore->addOperationDevice(result_.token, dev);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700850 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600851 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700852 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400853
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600854 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700855}
856
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600857Status KeyStoreService::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
858 const ::android::sp<::android::IBinder>& token,
859 const ::android::security::keymaster::KeymasterArguments& params,
860 const ::std::vector<uint8_t>& input, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700861 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600862 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700863 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700864
Janis Danisevskisbec89992019-08-14 13:42:19 -0700865 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700866 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600867 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700868 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700869
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600870 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700871 if (!result_.resultCode.isOk()) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700872 mKeyStore->removeOperationDevice(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100873 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600874 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700875 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100876
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600877 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700878}
879
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600880Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
881 const ::android::sp<::android::IBinder>& token,
882 const ::android::security::keymaster::KeymasterArguments& params,
Rob Barnes3af223f2019-11-14 14:50:30 -0700883 const ::std::vector<uint8_t>& input,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700884 const ::std::vector<uint8_t>& signature,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600885 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700886 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600887 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700888 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700889
Janis Danisevskisbec89992019-08-14 13:42:19 -0700890 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700891 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600892 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700893 }
894
Rob Barnes3af223f2019-11-14 14:50:30 -0700895 dev->finish(token, params.getParameters(), input, signature, entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600896 [this, cb, token](OperationResult result_) {
Janis Danisevskis8c4c1d62019-10-04 11:01:54 -0700897 mKeyStore->removeOperationDevice(token);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600898 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700899 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700900
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600901 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700902}
903
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600904Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
905 const ::android::sp<::android::IBinder>& token,
906 int32_t* _aidl_return) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700907 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700908 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600909 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700910 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100911
Janis Danisevskisbec89992019-08-14 13:42:19 -0700912 dev->abort(token, [this, cb, token](KeyStoreServiceReturnCode rc) {
913 mKeyStore->removeOperationDevice(token);
914 cb->onFinished(rc);
915 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700916
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600917 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700918}
919
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700920Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000921 int32_t* aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700922
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000923 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
924 // receive a HardwareAuthToken, rather than an opaque byte array.
925
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700926 if (!checkBinderPermission(P_ADD_AUTH)) {
927 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700928 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
929 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700930 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700931 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
Branden Archer70080742018-11-20 11:04:11 -0800932 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700933 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000934 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100935
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000936 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700937 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000938 if (authToken.version != 0) {
Branden Archer70080742018-11-20 11:04:11 -0800939 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700940 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000941 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100942
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700943 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
944 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700945 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
946 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700947}
948
David Zeuthen59102f32020-05-08 10:58:09 -0400949Status KeyStoreService::getTokensForCredstore(int64_t challenge, int64_t secureUserId,
950 int32_t authTokenMaxAgeMillis,
951 const ::android::sp<ICredstoreTokenCallback>& cb) {
David Zeuthenab3e5652019-10-28 13:32:48 -0400952 uid_t callingUid = IPCThreadState::self()->getCallingUid();
953 if (callingUid != AID_CREDSTORE) {
954 return Status::fromServiceSpecificError(static_cast<int32_t>(0));
955 }
956
957 auto [err, authToken] = mKeyStore->getAuthTokenTable().FindAuthorizationForCredstore(
958 challenge, secureUserId, authTokenMaxAgeMillis);
David Zeuthen59102f32020-05-08 10:58:09 -0400959 // It's entirely possible we couldn't find an authToken (e.g. no user auth
960 // happened within the requested deadline) and in that case, we just
961 // callback immediately signaling success but just not returning any tokens.
962 if (err != AuthTokenTable::OK) {
963 cb->onFinished(true, {} /* serializedAuthToken */, {} /* serializedVerificationToken */);
964 return Status::ok();
David Zeuthenab3e5652019-10-28 13:32:48 -0400965 }
David Zeuthen59102f32020-05-08 10:58:09 -0400966
967 // If we did find an authToken, get a verificationToken as well...
968 //
969 std::vector<uint8_t> serializedAuthToken = authToken2HidlVec(authToken);
970 std::vector<uint8_t> serializedVerificationToken;
971 std::shared_ptr<KeymasterWorker> dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
972 if (!dev) {
973 LOG(ERROR) << "Unable to get KM device for SecurityLevel::TRUSTED_ENVIRONMENT";
974 dev = mKeyStore->getDevice(SecurityLevel::SOFTWARE);
975 if (!dev) {
976 LOG(ERROR) << "Unable to get KM device for SecurityLevel::SOFTWARE";
977 cb->onFinished(false, {}, {});
978 return Status::fromServiceSpecificError(static_cast<int32_t>(0));
979 }
980 }
981
982 dev->verifyAuthorization(
983 challenge, {} /* params */, authToken,
984 [serializedAuthToken, cb](KeyStoreServiceReturnCode rc, HardwareAuthToken,
985 VerificationToken verificationToken) {
986 if (rc != ErrorCode::OK) {
987 LOG(ERROR) << "verifyAuthorization failed, rc=" << rc;
988 cb->onFinished(false, {}, {});
989 return;
990 }
991 std::optional<std::vector<uint8_t>> serializedVerificationToken =
992 serializeVerificationToken(verificationToken);
993 if (!serializedVerificationToken) {
994 LOG(ERROR) << "Error serializing verificationToken";
995 cb->onFinished(false, {}, {});
996 return;
997 }
998 cb->onFinished(true, serializedAuthToken, serializedVerificationToken.value());
999 });
1000
David Zeuthenab3e5652019-10-28 13:32:48 -04001001 return Status::ok();
1002}
1003
Dorin Drimus4b7a7fb2020-04-20 17:32:13 +02001004bool isDeviceIdAttestationTag(Tag tag) {
1005 switch (tag) {
1006 case Tag::ATTESTATION_ID_BRAND:
1007 case Tag::ATTESTATION_ID_DEVICE:
1008 case Tag::ATTESTATION_ID_MANUFACTURER:
1009 case Tag::ATTESTATION_ID_MODEL:
1010 case Tag::ATTESTATION_ID_PRODUCT:
1011 case Tag::ATTESTATION_ID_IMEI:
1012 case Tag::ATTESTATION_ID_MEID:
1013 case Tag::ATTESTATION_ID_SERIAL:
1014 return true;
1015 case Tag::INVALID:
1016 case Tag::PURPOSE:
1017 case Tag::ALGORITHM:
1018 case Tag::KEY_SIZE:
1019 case Tag::BLOCK_MODE:
1020 case Tag::DIGEST:
1021 case Tag::PADDING:
1022 case Tag::CALLER_NONCE:
1023 case Tag::MIN_MAC_LENGTH:
1024 case Tag::EC_CURVE:
1025 case Tag::RSA_PUBLIC_EXPONENT:
1026 case Tag::INCLUDE_UNIQUE_ID:
1027 case Tag::BLOB_USAGE_REQUIREMENTS:
1028 case Tag::BOOTLOADER_ONLY:
1029 case Tag::ROLLBACK_RESISTANCE:
1030 case Tag::HARDWARE_TYPE:
1031 case Tag::ACTIVE_DATETIME:
1032 case Tag::ORIGINATION_EXPIRE_DATETIME:
1033 case Tag::USAGE_EXPIRE_DATETIME:
1034 case Tag::MIN_SECONDS_BETWEEN_OPS:
1035 case Tag::MAX_USES_PER_BOOT:
1036 case Tag::USER_ID:
1037 case Tag::USER_SECURE_ID:
1038 case Tag::NO_AUTH_REQUIRED:
1039 case Tag::USER_AUTH_TYPE:
1040 case Tag::AUTH_TIMEOUT:
1041 case Tag::ALLOW_WHILE_ON_BODY:
1042 case Tag::TRUSTED_USER_PRESENCE_REQUIRED:
1043 case Tag::TRUSTED_CONFIRMATION_REQUIRED:
1044 case Tag::UNLOCKED_DEVICE_REQUIRED:
1045 case Tag::APPLICATION_ID:
1046 case Tag::APPLICATION_DATA:
1047 case Tag::CREATION_DATETIME:
1048 case Tag::ORIGIN:
1049 case Tag::ROOT_OF_TRUST:
1050 case Tag::OS_VERSION:
1051 case Tag::OS_PATCHLEVEL:
1052 case Tag::UNIQUE_ID:
1053 case Tag::ATTESTATION_CHALLENGE:
1054 case Tag::ATTESTATION_APPLICATION_ID:
1055 case Tag::VENDOR_PATCHLEVEL:
1056 case Tag::BOOT_PATCHLEVEL:
1057 case Tag::ASSOCIATED_DATA:
1058 case Tag::NONCE:
1059 case Tag::MAC_LENGTH:
1060 case Tag::RESET_SINCE_ID_ROTATION:
1061 case Tag::CONFIRMATION_TOKEN:
1062 return false;
1063 // no default, all values must be present in the switch, in this way the compiler ensures
1064 // that new values added in the Tag enum are also added here.
1065 }
1066}
1067
1068// These are attestation id tags that are not unique per device and don't require special permission
1069// to be attested. Any addition to this list needs privacy review and approval (PWG).
1070bool isDevicePropertyAttestationTag(Tag tag) {
1071 switch (tag) {
1072 case Tag::ATTESTATION_ID_BRAND:
1073 case Tag::ATTESTATION_ID_DEVICE:
1074 case Tag::ATTESTATION_ID_MANUFACTURER:
1075 case Tag::ATTESTATION_ID_MODEL:
1076 case Tag::ATTESTATION_ID_PRODUCT:
1077 return true;
1078 default:
1079 return false;
1080 }
1081}
1082
Eran Messerid9f8ae52018-10-24 13:54:00 +01001083bool isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -07001084 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001085 for (size_t i = 0; i < paramsVec.size(); ++i) {
Dorin Drimus4b7a7fb2020-04-20 17:32:13 +02001086 if (isDeviceIdAttestationTag(paramsVec[i].tag)) {
Eran Messerid9f8ae52018-10-24 13:54:00 +01001087 return true;
Dorin Drimus4b7a7fb2020-04-20 17:32:13 +02001088 }
1089 }
1090 return false;
1091}
1092
1093// Device properties can be attested safely without special permission
1094bool needsPermissionToAttestDeviceIds(const KeymasterArguments& params) {
1095 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
1096 for (size_t i = 0; i < paramsVec.size(); ++i) {
1097 if (isDeviceIdAttestationTag(paramsVec[i].tag) &&
1098 !isDevicePropertyAttestationTag(paramsVec[i].tag)) {
1099 return true;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001100 }
1101 }
Eran Messerid9f8ae52018-10-24 13:54:00 +01001102 return false;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001103}
1104
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001105Status KeyStoreService::attestKey(
1106 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1107 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001108 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1109 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001110 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001111 }
1112
Eran Messerie2c34152017-12-21 21:01:22 +00001113 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1114
Dorin Drimus2f43a6a2020-05-05 19:19:24 +02001115 if (needsPermissionToAttestDeviceIds(params) && (get_app_id(callingUid) != AID_SYSTEM)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001116 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001117 }
1118
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001119 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001120 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
Hasini Gunasinghe8c8c2d42020-06-23 17:17:47 +00001121
1122 auto logErrorOnReturn = android::base::make_scope_guard(
1123 [&] { logKeystoreKeyAttestationEvent(false /*wasSuccessful*/, rc.getErrorCode()); });
1124
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001125 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001126 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001127 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001128
Shawn Willden50eb1b22016-01-21 12:41:23 -07001129 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001130 Blob keyBlob;
1131 Blob charBlob;
1132 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001133
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001134 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1135 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1136
Janis Danisevskis9dff56c2019-07-10 14:08:06 -07001137 if (!rc.isOk()) {
1138 return AIDL_RETURN(rc);
1139 }
1140
Hasini Gunasinghe8c8c2d42020-06-23 17:17:47 +00001141 logErrorOnReturn.Disable();
1142
Janis Danisevskisc1460142017-12-18 16:48:46 -08001143 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001144 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001145 dev->attestKey(
1146 std::move(hidlKey), mutableParams.hidl_data(),
Janis Danisevskisa359c672019-03-14 17:15:06 -07001147 [dev, cb](Return<void> rc,
1148 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001149 auto& [ret, certChain] = hidlResult;
1150 if (!rc.isOk()) {
Hasini Gunasinghe8c8c2d42020-06-23 17:17:47 +00001151 logKeystoreKeyAttestationEvent(false /*wasSuccessful*/,
1152 static_cast<int32_t>(ResponseCode::SYSTEM_ERROR));
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001153 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1154 } else if (ret != ErrorCode::OK) {
Hasini Gunasinghe8c8c2d42020-06-23 17:17:47 +00001155 KeyStoreServiceReturnCode ksrc(ret);
1156 logKeystoreKeyAttestationEvent(false /*wasSuccessful*/, ksrc.getErrorCode());
Janis Danisevskisa359c672019-03-14 17:15:06 -07001157 dev->logIfKeymasterVendorError(ret);
Hasini Gunasinghe8c8c2d42020-06-23 17:17:47 +00001158 cb->onFinished(ksrc, {});
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001159 } else {
Hasini Gunasinghe8c8c2d42020-06-23 17:17:47 +00001160 KeyStoreServiceReturnCode ksrc(ret);
1161 logKeystoreKeyAttestationEvent(true /*wasSuccessful*/, ksrc.getErrorCode());
1162 cb->onFinished(ksrc, KeymasterCertificateChain(std::move(certChain)));
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001163 }
1164 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001165
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001166 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001167}
1168
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001169// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1170// It should never be redefined by a build system though.
1171#ifndef CAPTURE_MOVE
1172#define CAPTURE_MOVE(x) x = std::move(x)
1173#endif
1174
1175Status KeyStoreService::attestDeviceIds(
1176 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1177 const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001178 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001179
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001180 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001181 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001182 }
1183
1184 if (!isDeviceIdAttestationRequested(params)) {
1185 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001186 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001187 }
1188
1189 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Dorin Drimus4b7a7fb2020-04-20 17:32:13 +02001190
1191 // Request special permission only for unique ids
1192 if (needsPermissionToAttestDeviceIds(params)) {
1193 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1194 if (binder == nullptr) {
1195 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
1196 }
1197
1198 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1199 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1200 IPCThreadState::self()->getCallingPid(), callingUid)) {
1201 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
1202 }
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001203 }
1204
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001205 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001206 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1207 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001208 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001209 }
1210
1211 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001212 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001213
Shawn Willden70c1a782018-07-11 15:13:20 -06001214 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001215 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001216 }
1217
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001218
1219 AuthorizationSet keyCharacteristics;
1220 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1221 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1222 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1223 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1224 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001225
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001226 std::promise<KeyStoreServiceReturnCode> resultPromise;
1227 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001228
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001229 dev->generateKey(
1230 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001231 [cb, dev, CAPTURE_MOVE(mutableParams)](
1232 Return<void> rc,
1233 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001234 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1235 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1236 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001237 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001238 return;
1239 }
1240 if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001241 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001242 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001243 return;
1244 }
1245 dev->attestKey(
1246 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001247 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001248 hidlKeyBlob](Return<void> rc,
1249 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1250 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001251 // schedule temp key for deletion
Janis Danisevskisa359c672019-03-14 17:15:06 -07001252 dev->deleteKey(std::move(hidlKeyBlob), [dev](Return<ErrorCode> rc) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001253 // log error but don't return an error
Janis Danisevskisa359c672019-03-14 17:15:06 -07001254 KS_HANDLE_HIDL_ERROR(dev, rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001255 });
1256 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001257 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001258 return;
1259 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001260 if (ret == ErrorCode::OK) {
1261 cb->onFinished(
1262 KeyStoreServiceReturnCode(ret),
1263 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1264 } else {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001265 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001266 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001267 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001268 });
1269 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001270
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001271 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001272}
1273
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001274Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001275 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001276 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001277 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1278 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001279}
1280
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001281Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001282 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001283 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1284 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1285 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001286 int32_t* _aidl_return) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001287
1288 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1289
1290 if (!checkBinderPermission(P_INSERT, callingUid)) {
1291 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1292 }
1293
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001294 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001295
1296 KeyStoreServiceReturnCode rc;
1297 Blob wrappingKeyBlob;
1298 Blob wrappingCharBlob;
1299 LockedKeyBlobEntry wrappingLockedEntry;
1300
1301 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1302 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
Branden Archerd166a882018-11-20 10:56:48 -08001303 if (!rc.isOk()) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001304 return AIDL_RETURN(rc);
1305 }
1306
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001307 String8 wrappedKeyName8(wrappedKeyAlias);
1308 auto wrappedLockedEntry =
1309 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1310 if (!wrappedLockedEntry) {
1311 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1312 }
1313
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001314 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1315 auto dev = mKeyStore->getDevice(securityLevel);
1316 if (!dev) {
1317 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1318 }
1319
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001320 dev->importWrappedKey(
1321 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1322 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001323 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1324 cb->onFinished(rc,
1325 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001326 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001327
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001328 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001329}
1330
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001331Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1332 const String16& promptText,
1333 const ::std::vector<uint8_t>& extraData,
1334 const String16& locale, int32_t uiOptionsAsFlags,
1335 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001336 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1337 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001338}
1339
1340Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1341 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001342 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001343}
1344
David Zeuthen1a492312018-02-26 11:00:30 -05001345Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001346 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001347}
1348
1349/**
1350 * Get the effective target uid for a binder operation that takes an
1351 * optional uid as the target.
1352 */
1353uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1354 if (targetUid == UID_SELF) {
1355 return IPCThreadState::self()->getCallingUid();
1356 }
1357 return static_cast<uid_t>(targetUid);
1358}
1359
1360/**
1361 * Check if the caller of the current binder method has the required
1362 * permission and if acting on other uids the grants to do so.
1363 */
1364bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1365 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1366 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001367 const char* ssid = IPCThreadState::self()->getCallingSid();
1368 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001369 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1370 return false;
1371 }
1372 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1373 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1374 return false;
1375 }
1376 return true;
1377}
1378
1379/**
1380 * Check if the caller of the current binder method has the required
1381 * permission and the target uid is the caller or the caller is system.
1382 */
1383bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1384 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1385 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001386 const char* ssid = IPCThreadState::self()->getCallingSid();
1387 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001388 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1389 return false;
1390 }
1391 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1392}
1393
1394/**
1395 * Check if the caller of the current binder method has the required
1396 * permission or the target of the operation is the caller's uid. This is
1397 * for operation where the permission is only for cross-uid activity and all
1398 * uids are allowed to act on their own (ie: clearing all entries for a
1399 * given uid).
1400 */
1401bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1402 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1403 if (getEffectiveUid(targetUid) == callingUid) {
1404 return true;
1405 } else {
1406 return checkBinderPermission(permission, targetUid);
1407 }
1408}
1409
1410/**
1411 * Helper method to check that the caller has the required permission as
1412 * well as the keystore is in the unlocked state if checkUnlocked is true.
1413 *
1414 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1415 * otherwise the state of keystore when not unlocked and checkUnlocked is
1416 * true.
1417 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001418KeyStoreServiceReturnCode
1419KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1420 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001421 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001422 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001423 }
1424 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1425 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001426 // All State values coincide with ResponseCodes
1427 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001428 }
1429
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001430 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001431}
1432
1433bool KeyStoreService::isKeystoreUnlocked(State state) {
1434 switch (state) {
1435 case ::STATE_NO_ERROR:
1436 return true;
1437 case ::STATE_UNINITIALIZED:
1438 case ::STATE_LOCKED:
1439 return false;
1440 }
1441 return false;
1442}
1443
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001444/**
Shawn Willden0329a822017-12-04 13:55:14 -07001445 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1446 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001447 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001448bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1449 for (size_t i = 0; i < params.size(); ++i) {
1450 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001451 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001452 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001453 return false;
1454 default:
1455 break;
1456 }
1457 }
1458 return true;
1459}
1460
Brian Young9a947d52018-02-23 18:03:14 +00001461Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
Janis Danisevskis1642dc02020-01-21 14:33:30 -08001462 int32_t* _aidl_return) {
Janis Danisevskis1642dc02020-01-21 14:33:30 -08001463 if (isShowing) {
1464 if (!checkBinderPermission(P_LOCK, UID_SELF)) {
1465 LOG(WARNING) << "onKeyguardVisibilityChanged called with isShowing == true but "
1466 "without LOCK permission";
1467 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1468 }
1469 } else {
1470 if (!checkBinderPermission(P_UNLOCK, UID_SELF)) {
1471 LOG(WARNING) << "onKeyguardVisibilityChanged called with isShowing == false but "
1472 "without UNLOCK permission";
1473 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1474 }
1475 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001476 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Janis Danisevskis1642dc02020-01-21 14:33:30 -08001477 return AIDL_RETURN(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001478}
1479
Shawn Willdene2a7b522017-04-11 09:27:40 -06001480} // namespace keystore