blob: 279df2d8779a44736dc1ef971471f209a6ba36f2 [file] [log] [blame]
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Janis Danisevskis011675d2016-09-01 11:41:29 +010017#define LOG_TAG "keystore"
18
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070019#include "key_store_service.h"
20
21#include <fcntl.h>
22#include <sys/stat.h>
23
Janis Danisevskis7612fd42016-09-01 11:50:02 +010024#include <algorithm>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070025#include <atomic>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070026#include <sstream>
27
Pavel Grafovff311b42018-01-24 20:34:37 +000028#include <android-base/scopeguard.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010029#include <binder/IInterface.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070030#include <binder/IPCThreadState.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010031#include <binder/IPermissionController.h>
32#include <binder/IServiceManager.h>
Brian Claire Young3133c452018-08-31 13:56:49 -070033#include <cutils/multiuser.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000034#include <log/log_event_list.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070035
36#include <private/android_filesystem_config.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000037#include <private/android_logger.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070038
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070039#include <android/hardware/confirmationui/1.0/IConfirmationUI.h>
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010040#include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070041
42#include "defaults.h"
Max Bires33aac2d2018-02-23 10:53:10 -080043#include "key_proto_handler.h"
Janis Danisevskis18f27ad2016-06-01 13:57:40 -070044#include "keystore_attestation_id.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010045#include "keystore_keymaster_enforcement.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070046#include "keystore_utils.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010047#include <keystore/keystore_hidl_support.h>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070048#include <keystore/keystore_return_types.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070049
Janis Danisevskis8f737ad2017-11-21 12:30:15 -080050#include <hardware/hw_auth_token.h>
51
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010052namespace keystore {
Shawn Willdend5a24e62017-02-28 13:53:24 -070053
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010054using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070055
Shawn Willdene2a7b522017-04-11 09:27:40 -060056namespace {
57
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070058using ::android::binder::Status;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070059using android::security::keymaster::ExportResult;
60using android::security::keymaster::KeymasterArguments;
61using android::security::keymaster::KeymasterBlob;
62using android::security::keymaster::KeymasterCertificateChain;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070063using android::security::keymaster::operationFailed;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070064using android::security::keymaster::OperationResult;
David Zeuthenc6eb7cd2017-11-27 11:33:55 -050065using ConfirmationResponseCode = android::hardware::confirmationui::V1_0::ResponseCode;
Rob Barnesbb6cabd2018-10-04 17:10:37 -060066using ::android::security::keystore::IKeystoreOperationResultCallback;
67using ::android::security::keystore::IKeystoreResponseCallback;
68using ::android::security::keystore::KeystoreResponse;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070069
Shawn Willdene2a7b522017-04-11 09:27:40 -060070constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
71const char* kTimestampFilePath = "timestamp";
Rubin Xu1a203e32018-05-08 14:25:21 +010072const int ID_ATTESTATION_REQUEST_GENERIC_INFO = 1 << 0;
73const int ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID = 1 << 1;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070074
Shawn Willdene2a7b522017-04-11 09:27:40 -060075bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070076 return params.end() !=
77 std::find_if(params.begin(), params.end(),
78 [&](const KeyParameter& param) { return param.tag == tag; });
Shawn Willdend5a24e62017-02-28 13:53:24 -070079}
80
Branden Archer70080742018-11-20 11:04:11 -080081#define AIDL_RETURN(rc) (*_aidl_return = KeyStoreServiceReturnCode(rc).getErrorCode(), Status::ok())
Janis Danisevskisb50236a2019-03-25 10:26:30 -070082#define KEYSTORE_SERVICE_LOCK std::lock_guard<std::mutex> keystore_lock(keystoreServiceMutex_)
Rob Barnesbb6cabd2018-10-04 17:10:37 -060083
Shawn Willdene2a7b522017-04-11 09:27:40 -060084std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
85 struct stat sbuf;
86 if (stat(kTimestampFilePath, &sbuf) == 0) {
Yi Konge353f252018-07-30 01:38:39 -070087 double diff_secs = difftime(time(nullptr), sbuf.st_ctime);
Shawn Willdene2a7b522017-04-11 09:27:40 -060088 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
89 }
90
91 if (errno != ENOENT) {
92 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
93 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
94 }
95
96 int fd = creat(kTimestampFilePath, 0600);
97 if (fd < 0) {
98 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
99 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
100 }
101
102 if (close(fd)) {
103 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
104 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
105 }
106
107 return {ResponseCode::NO_ERROR, true};
108}
109
Eran Messeri03fc4c82018-08-16 18:53:15 +0100110using ::android::security::KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200111
112KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
113 KeyStoreServiceReturnCode responseCode;
114 bool factoryResetSinceIdRotation;
115 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
116
117 if (!responseCode.isOk()) return responseCode;
118 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
119
120 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
121 if (!asn1_attestation_id_result.isOk()) {
122 ALOGE("failed to gather attestation_id");
123 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
124 }
125 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
126
127 /*
Eran Messeri03fc4c82018-08-16 18:53:15 +0100128 * The attestation application ID must not be longer than
129 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, error out if gather_attestation_application_id
130 * returned such an invalid vector.
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200131 */
132 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Eran Messeri03fc4c82018-08-16 18:53:15 +0100133 ALOGE("BUG: Gathered Attestation Application ID is too big (%d)",
134 static_cast<int32_t>(asn1_attestation_id.size()));
135 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200136 }
137
138 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
139
140 return ResponseCode::NO_ERROR;
141}
142
Shawn Willdene2a7b522017-04-11 09:27:40 -0600143} // anonymous namespace
144
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700145Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700146 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700147 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700148 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
149 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700150 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700151 *aidl_return = mKeyStore->getState(userId);
152 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700153}
154
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700155Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700156 KEYSTORE_SERVICE_LOCK;
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) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700186 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700187 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700188 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700189 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100190 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800191 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700192 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700193 }
194
195 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700196 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), targetUid);
197
198 if (!lockedEntry) {
199 ALOGE("failed to grab lock on blob entry %u_%s", targetUid, name8.string());
200 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_ALREADY_EXISTS);
201 return Status::ok();
202 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700203
Yi Konge353f252018-07-30 01:38:39 -0700204 Blob keyBlob(&item[0], item.size(), nullptr, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700205 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
206
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700207 *aidl_return = static_cast<int32_t>(mKeyStore->put(lockedEntry, keyBlob, {}));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700208 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700209}
210
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700211Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700212 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700213 targetUid = getEffectiveUid(targetUid);
214 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700215 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
216 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700217 }
218 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000219 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700220 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
221 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700222 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
223 return Status::ok();
224 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700225
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700226 ResponseCode result = mKeyStore->del(lockedEntry);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400227
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700228 *aidl_return = static_cast<int32_t>(result);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700229 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700230}
231
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700232Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700233 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700234 targetUid = getEffectiveUid(targetUid);
235 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700236 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
237 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700238 }
239
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700240 LockedKeyBlobEntry lockedEntry =
241 mKeyStore->getLockedBlobEntryIfExists(String8(name).string(), targetUid);
242 *aidl_return =
243 static_cast<int32_t>(lockedEntry ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700244 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700245}
246
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700247Status KeyStoreService::list(const String16& prefix, int32_t targetUid,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700248 ::std::vector<::android::String16>* matches) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700249 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700250 targetUid = getEffectiveUid(targetUid);
251 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700252 return Status::fromServiceSpecificError(
253 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700254 }
255 const String8 prefix8(prefix);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700256 const std::string stdPrefix(prefix8.string());
257
258 ResponseCode rc;
259 std::list<LockedKeyBlobEntry> internal_matches;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800260 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700261
Janis Danisevskis265435f2018-11-16 14:10:46 -0800262 std::tie(rc, internal_matches) =
263 LockedKeyBlobEntry::list(userDirName, [&](uid_t uid, const std::string& alias) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700264 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end());
265 return uid == static_cast<uid_t>(targetUid) &&
266 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end())
267 .first == stdPrefix.end();
268 });
269
270 if (rc != ResponseCode::NO_ERROR) {
271 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700272 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700273
274 for (LockedKeyBlobEntry& entry : internal_matches) {
275 matches->push_back(String16(entry->alias().substr(prefix8.size()).c_str()));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700276 }
277 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700278}
279
Rob Barneseb7f79b2018-11-08 15:44:10 -0700280/*
281 * This method will return the uids of all auth bound keys for the calling user.
282 * This is intended to be used for alerting the user about which apps will be affected
283 * if the password/pin is removed. Only allowed to be called by system.
284 * The output is bound by the initial size of uidsOut to be compatible with Java.
285 */
Rob Barnes5d59e632018-12-07 16:09:02 -0700286Status KeyStoreService::listUidsOfAuthBoundKeys(std::vector<std::string>* uidsOut,
Rob Barneseb7f79b2018-11-08 15:44:10 -0700287 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700288 KEYSTORE_SERVICE_LOCK;
Rob Barneseb7f79b2018-11-08 15:44:10 -0700289 const int32_t callingUid = IPCThreadState::self()->getCallingUid();
290 const int32_t userId = get_user_id(callingUid);
291 const int32_t appId = get_app_id(callingUid);
292 if (appId != AID_SYSTEM) {
293 ALOGE("Permission listUidsOfAuthBoundKeys denied for aid %d", appId);
294 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
295 return Status::ok();
296 }
297
298 const String8 prefix8("");
299 auto userState = mKeyStore->getUserStateDB().getUserState(userId);
300 const std::string userDirName = userState->getUserDirName();
301 auto encryptionKey = userState->getEncryptionKey();
302 auto state = userState->getState();
303 // unlock the user state
304 userState = {};
305
306 ResponseCode rc;
307 std::list<LockedKeyBlobEntry> internal_matches;
308 std::tie(rc, internal_matches) =
309 LockedKeyBlobEntry::list(userDirName, [&](uid_t, const std::string&) {
310 // Need to filter on auth bound state, so just return true.
311 return true;
312 });
313 if (rc != ResponseCode::NO_ERROR) {
314 ALOGE("Error listing blob entries for user %d", userId);
315 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
316 }
317
Rob Barneseb7f79b2018-11-08 15:44:10 -0700318 for (LockedKeyBlobEntry& entry : internal_matches) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700319 // Need to store uids as a list of strings because integer list output
320 // parameters is not supported in aidl-cpp.
321 std::string entryUid = std::to_string(entry->uid());
322 if (std::find(uidsOut->begin(), uidsOut->end(), entryUid) != uidsOut->end()) {
Rob Barneseb7f79b2018-11-08 15:44:10 -0700323 // uid already in list, skip
324 continue;
325 }
326
327 auto [rc, blob, charBlob] = entry.readBlobs(encryptionKey, state);
328 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::LOCKED) {
329 ALOGE("Error reading blob for key %s", entry->alias().c_str());
330 continue;
331 }
332
333 if (blob && blob.isEncrypted()) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700334 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700335 } else if (charBlob) {
336 auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
337 if (!success) {
338 ALOGE("Error reading blob characteristics for key %s", entry->alias().c_str());
339 continue;
340 }
341 if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
342 swEnforced.Contains(TAG_USER_SECURE_ID)) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700343 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700344 }
345 }
346 }
347 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
348 return Status::ok();
349}
350
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700351Status KeyStoreService::reset(int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700352 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700353 if (!checkBinderPermission(P_RESET)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700354 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
355 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700356 }
357
358 uid_t callingUid = IPCThreadState::self()->getCallingUid();
359 mKeyStore->resetUser(get_user_id(callingUid), false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700360 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
361 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700362}
363
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700364Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
365 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700366 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700367 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700368 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
369 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700370 }
371
372 const String8 password8(password);
373 // Flush the auth token table to prevent stale tokens from sticking
374 // around.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700375 mKeyStore->getAuthTokenTable().Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700376
377 if (password.size() == 0) {
378 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
379 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700380 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
381 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700382 } else {
383 switch (mKeyStore->getState(userId)) {
384 case ::STATE_UNINITIALIZED: {
385 // generate master key, encrypt with password, write to file,
386 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700387 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
388 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700389 }
390 case ::STATE_NO_ERROR: {
391 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700392 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
393 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700394 }
395 case ::STATE_LOCKED: {
396 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
397 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700398 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
399 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700400 }
401 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700402 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
403 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700404 }
405}
406
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700407Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700408 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700409 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700410 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
411 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700412 }
413
414 // Sanity check that the new user has an empty keystore.
415 if (!mKeyStore->isEmpty(userId)) {
416 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
417 }
418 // Unconditionally clear the keystore, just to be safe.
419 mKeyStore->resetUser(userId, false);
420 if (parentId != -1) {
421 // This profile must share the same master key password as the parent profile. Because the
422 // password of the parent profile is not known here, the best we can do is copy the parent's
423 // master key and master key file. This makes this profile use the same master key as the
424 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700425 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
426 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700427 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700428 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
429 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700430 }
431}
432
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700433Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700434 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700435 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700436 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
437 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700438 }
439
440 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700441 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
442 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700443}
444
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700445Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700446 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700447 if (!checkBinderPermission(P_LOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700448 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
449 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700450 }
451
452 State state = mKeyStore->getState(userId);
453 if (state != ::STATE_NO_ERROR) {
454 ALOGD("calling lock in state: %d", state);
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(true, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700460 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700461 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
462 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700463}
464
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700465Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700466 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700467 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700468 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
469 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700470 }
471
472 State state = mKeyStore->getState(userId);
473 if (state != ::STATE_LOCKED) {
474 switch (state) {
475 case ::STATE_NO_ERROR:
476 ALOGI("calling unlock when already unlocked, ignoring.");
477 break;
478 case ::STATE_UNINITIALIZED:
479 ALOGE("unlock called on uninitialized keystore.");
480 break;
481 default:
482 ALOGE("unlock called on keystore in unknown state: %d", state);
483 break;
484 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700485 *aidl_return = static_cast<int32_t>(ResponseCode(state));
486 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700487 }
488
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700489 mKeyStore->getEnforcementPolicy().set_device_locked(false, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700490 const String8 password8(pw);
491 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700492 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
493 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700494}
495
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700496Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700497 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700498 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700499 *aidl_return = static_cast<int32_t>(false);
500 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700501 }
502
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700503 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
504 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700505}
506
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700507Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
508 ::android::String16* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700509 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700510 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700511 auto result =
512 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100513 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700514 *aidl_return = String16();
515 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700516 }
517
518 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700519 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
520 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700521 *aidl_return = String16();
522 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700523 }
524
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700525 *aidl_return = String16(mKeyStore->addGrant(lockedEntry, granteeUid).c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700526 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700527}
528
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700529Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700530 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700531 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700532 KeyStoreServiceReturnCode result =
533 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100534 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800535 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700536 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700537 }
538
539 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700540
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700541 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
542 if (!lockedEntry) {
543 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700544 }
545
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700546 *aidl_return = mKeyStore->removeGrant(lockedEntry, granteeUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700547 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700548}
549
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700550Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700551 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700552 uid_t targetUid = getEffectiveUid(uid);
553 if (!checkBinderPermission(P_GET, targetUid)) {
554 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700555 *time = -1L;
556 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700557 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700558 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700559
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700560 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
561 if (!lockedEntry) {
562 ALOGW("could not access key with alias %s for getmtime", name8.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700563 *time = -1L;
564 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700565 }
566
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700567 std::string filename = lockedEntry->getKeyBlobPath();
568
569 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700570 if (fd < 0) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700571 ALOGW("could not open %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700572 *time = -1L;
573 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700574 }
575
576 struct stat s;
577 int ret = fstat(fd, &s);
578 close(fd);
579 if (ret == -1) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700580 ALOGW("could not stat %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700581 *time = -1L;
582 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700583 }
584
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700585 *time = static_cast<int64_t>(s.st_mtime);
586 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700587}
588
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700589Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700590 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700591 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
592 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700593}
594
Janis Danisevskis265435f2018-11-16 14:10:46 -0800595Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700596 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700597 uid_t targetUid = getEffectiveUid(targetUid64);
598 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800599 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700600 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000601 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700602
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700603 mKeyStore->removeAllGrantsToUid(targetUid);
604
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700605 ResponseCode rc;
606 std::list<LockedKeyBlobEntry> entries;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800607 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700608
609 // list has a fence making sure no workers are modifying blob files before iterating the
610 // data base. All returned entries are locked.
611 std::tie(rc, entries) = LockedKeyBlobEntry::list(
Janis Danisevskis265435f2018-11-16 14:10:46 -0800612 userDirName, [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700613
614 if (rc != ResponseCode::NO_ERROR) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800615 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700616 }
617
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700618 for (LockedKeyBlobEntry& lockedEntry : entries) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100619 if (get_app_id(targetUid) == AID_SYSTEM) {
620 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700621 Blob charBlob;
622 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
623 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100624 // Do not clear keys critical to device encryption under system uid.
625 continue;
626 }
627 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700628 mKeyStore->del(lockedEntry);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700629 }
Janis Danisevskis265435f2018-11-16 14:10:46 -0800630 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700631}
632
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600633Status KeyStoreService::addRngEntropy(
634 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
635 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700636 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisc1460142017-12-18 16:48:46 -0800637 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
638 if (!device) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600639 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800640 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700641
Janis Danisevskis37896102019-03-14 17:15:06 -0700642 device->addRngEntropy(entropy, [device, cb](Return<ErrorCode> rc) {
643 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device, rc)));
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600644 });
645
646 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700647}
648
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600649Status KeyStoreService::generateKey(
650 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
651 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
652 int uid, int flags, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700653 KEYSTORE_SERVICE_LOCK;
Max Biresef4f0672017-11-29 14:38:48 -0800654 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
655 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700656 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000657 auto logOnScopeExit = android::base::make_scope_guard([&] {
658 if (__android_log_security()) {
659 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600660 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000661 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
662 }
663 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100664 KeyStoreServiceReturnCode rc =
665 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
666 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600667 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700668 }
Rubin Xu67899de2017-04-21 19:15:13 +0100669 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
670 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600671 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100672 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700673
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700674 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700675 // TODO(jbires): remove uid checking upon implementation of b/25646100
Max Bires670467d2017-12-12 11:16:43 -0800676 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Biresef4f0672017-11-29 14:38:48 -0800677 originalUid != IPCThreadState::self()->getCallingUid()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600678 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700679 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600680 }
681
Janis Danisevskisc1460142017-12-18 16:48:46 -0800682 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
683 auto dev = mKeyStore->getDevice(securityLevel);
684 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600685 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800686 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400687
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100688 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700689 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
690 if (!lockedEntry) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600691 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100692 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400693
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700694 logOnScopeExit.Disable();
695
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600696 dev->generateKey(
697 std::move(lockedEntry), params.getParameters(), entropy, flags,
698 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
699 if (__android_log_security()) {
700 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
701 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
702 }
703 cb->onFinished(rc,
704 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
705 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700706
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600707 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700708}
709
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700710Status KeyStoreService::getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600711 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700712 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
Janis Danisevskis64ec1fe2018-02-26 16:47:21 -0800713 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600714 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700715 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700716
717 uid_t targetUid = getEffectiveUid(uid);
718 uid_t callingUid = IPCThreadState::self()->getCallingUid();
719 if (!is_granted_to(callingUid, targetUid)) {
720 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
721 targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600722 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700723 }
724
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700725 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700726
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700727 ResponseCode rc;
728 Blob keyBlob;
729 Blob charBlob;
730 LockedKeyBlobEntry lockedEntry;
Janis Danisevskisd714a672017-09-01 14:31:36 -0700731
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700732 std::tie(rc, keyBlob, charBlob, lockedEntry) =
733 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
734
735 if (rc != ResponseCode::NO_ERROR) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600736 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700737 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100738
Janis Danisevskisc1460142017-12-18 16:48:46 -0800739 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700740 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600741 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100742 }
743
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700744 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
745 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
746 // from keymaster. It may also upgrade the key blob.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700747 dev->getKeyCharacteristics(
748 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
749 std::move(charBlob),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600750 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
751 cb->onFinished(rc,
752 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700753 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100754
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600755 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700756}
757
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600758Status KeyStoreService::importKey(
759 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
760 const String16& name, const KeymasterArguments& params, int32_t format,
761 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700762 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700763 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000764 auto logOnScopeExit = android::base::make_scope_guard([&] {
765 if (__android_log_security()) {
766 android_log_event_list(SEC_TAG_KEY_IMPORTED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600767 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000768 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
769 }
770 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100771 KeyStoreServiceReturnCode rc =
772 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
773 if (!rc.isOk()) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700774 LOG(ERROR) << "permissission denied";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600775 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700776 }
Rubin Xu67899de2017-04-21 19:15:13 +0100777 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
778 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600779 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100780 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700781
Janis Danisevskisc1460142017-12-18 16:48:46 -0800782 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
783 auto dev = mKeyStore->getDevice(securityLevel);
784 if (!dev) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700785 LOG(ERROR) << "importKey - cound not get keymaster device";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600786 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800787 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700788
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700789 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700790 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
791 if (!lockedEntry) {
792 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
793 << " already exists.";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600794 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400795 }
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700796
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700797 logOnScopeExit.Disable();
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700798
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600799 dev->importKey(
800 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
801 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
802 if (__android_log_security()) {
803 android_log_event_list(SEC_TAG_KEY_IMPORTED)
804 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
805 }
806 cb->onFinished(rc,
807 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
808 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400809
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600810 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700811}
812
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600813Status KeyStoreService::exportKey(
814 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
815 const String16& name, int32_t format,
816 const ::android::security::keymaster::KeymasterBlob& clientId,
817 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
818 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700819 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700820
821 uid_t targetUid = getEffectiveUid(uid);
822 uid_t callingUid = IPCThreadState::self()->getCallingUid();
823 if (!is_granted_to(callingUid, targetUid)) {
824 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600825 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700826 }
827
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700828 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700829
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700830 KeyStoreServiceReturnCode rc;
831 Blob keyBlob;
832 Blob charBlob;
833 LockedKeyBlobEntry lockedEntry;
834
835 std::tie(rc, keyBlob, charBlob, lockedEntry) =
836 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskis3cf85322018-11-19 13:37:49 -0800837 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600838 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700839 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100840
Janis Danisevskisc1460142017-12-18 16:48:46 -0800841 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100842
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700843 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600844 std::move(keyBlob), std::move(charBlob),
845 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
Ji Wang2c142312016-10-14 17:21:10 +0800846
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600847 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700848}
849
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600850Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
851 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700852 bool pruneable, const KeymasterArguments& params,
853 const ::std::vector<uint8_t>& entropy, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600854 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700855 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700856 uid_t callingUid = IPCThreadState::self()->getCallingUid();
857 uid_t targetUid = getEffectiveUid(uid);
858 if (!is_granted_to(callingUid, targetUid)) {
859 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600860 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700861 }
862 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
863 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600864 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700865 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700866 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600867 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700868 }
Shawn Willden0329a822017-12-04 13:55:14 -0700869
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700870 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700871 Blob keyBlob;
872 Blob charBlob;
873 LockedKeyBlobEntry lockedEntry;
874 ResponseCode rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100875
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700876 std::tie(rc, keyBlob, charBlob, lockedEntry) =
877 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
878
879 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600880 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700881 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600882 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700883
Janis Danisevskisc1460142017-12-18 16:48:46 -0800884 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700885 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100886
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700887 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
888 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600889 [this, cb, dev](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700890 if (result_.resultCode.isOk() ||
891 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
892 addOperationDevice(result_.token, dev);
893 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600894 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700895 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400896
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600897 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700898}
899
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600900Status KeyStoreService::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
901 const ::android::sp<::android::IBinder>& token,
902 const ::android::security::keymaster::KeymasterArguments& params,
903 const ::std::vector<uint8_t>& input, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700904 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700905 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600906 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700907 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700908
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700909 auto dev = getOperationDevice(token);
910 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600911 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700912 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700913
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600914 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700915 if (!result_.resultCode.isOk()) {
916 removeOperationDevice(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100917 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600918 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700919 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100920
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600921 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700922}
923
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600924Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
925 const ::android::sp<::android::IBinder>& token,
926 const ::android::security::keymaster::KeymasterArguments& params,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700927 const ::std::vector<uint8_t>& signature,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600928 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700929 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700930 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600931 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700932 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700933
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700934 auto dev = getOperationDevice(token);
935 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600936 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700937 }
938
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700939 dev->finish(token, params.getParameters(), {}, signature, entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600940 [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700941 if (!result_.resultCode.isOk()) {
942 removeOperationDevice(token);
943 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600944 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700945 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700946
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600947 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700948}
949
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600950Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
951 const ::android::sp<::android::IBinder>& token,
952 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700953 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700954 auto dev = getOperationDevice(token);
955 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600956 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700957 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100958
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600959 dev->abort(token, [cb](KeyStoreServiceReturnCode rc) { cb->onFinished(rc); });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700960
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600961 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700962}
963
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700964Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000965 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -0700966 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700967
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000968 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
969 // receive a HardwareAuthToken, rather than an opaque byte array.
970
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700971 if (!checkBinderPermission(P_ADD_AUTH)) {
972 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700973 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
974 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700975 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700976 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
Branden Archer70080742018-11-20 11:04:11 -0800977 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700978 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000979 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100980
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000981 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700982 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000983 if (authToken.version != 0) {
Branden Archer70080742018-11-20 11:04:11 -0800984 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700985 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000986 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100987
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700988 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
989 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700990 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
991 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700992}
993
Rubin Xu1a203e32018-05-08 14:25:21 +0100994int isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -0700995 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Rubin Xu1a203e32018-05-08 14:25:21 +0100996 int result = 0;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700997 for (size_t i = 0; i < paramsVec.size(); ++i) {
998 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -0600999 case Tag::ATTESTATION_ID_BRAND:
1000 case Tag::ATTESTATION_ID_DEVICE:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001001 case Tag::ATTESTATION_ID_MANUFACTURER:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001002 case Tag::ATTESTATION_ID_MODEL:
1003 case Tag::ATTESTATION_ID_PRODUCT:
Rubin Xu1a203e32018-05-08 14:25:21 +01001004 result |= ID_ATTESTATION_REQUEST_GENERIC_INFO;
Shawn Willdene2a7b522017-04-11 09:27:40 -06001005 break;
Rubin Xu1a203e32018-05-08 14:25:21 +01001006 case Tag::ATTESTATION_ID_IMEI:
1007 case Tag::ATTESTATION_ID_MEID:
1008 case Tag::ATTESTATION_ID_SERIAL:
1009 result |= ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID;
1010 break;
1011 default:
1012 continue;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001013 }
1014 }
Rubin Xu1a203e32018-05-08 14:25:21 +01001015 return result;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001016}
1017
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001018Status KeyStoreService::attestKey(
1019 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1020 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001021 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001022 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1023 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001024 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001025 }
1026
Eran Messerie2c34152017-12-21 21:01:22 +00001027 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1028
Rubin Xu1a203e32018-05-08 14:25:21 +01001029 int needsIdAttestation = isDeviceIdAttestationRequested(params);
1030 bool needsUniqueIdAttestation = needsIdAttestation & ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID;
1031 bool isPrimaryUserSystemUid = (callingUid == AID_SYSTEM);
1032 bool isSomeUserSystemUid = (get_app_id(callingUid) == AID_SYSTEM);
1033 // Allow system context from any user to request attestation with basic device information,
1034 // while only allow system context from user 0 (device owner) to request attestation with
1035 // unique device ID.
1036 if ((needsIdAttestation && !isSomeUserSystemUid) ||
1037 (needsUniqueIdAttestation && !isPrimaryUserSystemUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001038 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001039 }
1040
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001041 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001042 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1043 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001044 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001045 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001046
Shawn Willden50eb1b22016-01-21 12:41:23 -07001047 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001048 Blob keyBlob;
1049 Blob charBlob;
1050 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001051
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001052 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1053 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1054
Janis Danisevskis9dff56c2019-07-10 14:08:06 -07001055 if (!rc.isOk()) {
1056 return AIDL_RETURN(rc);
1057 }
1058
Janis Danisevskisc1460142017-12-18 16:48:46 -08001059 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001060 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001061 dev->attestKey(
1062 std::move(hidlKey), mutableParams.hidl_data(),
Janis Danisevskis37896102019-03-14 17:15:06 -07001063 [dev, cb](Return<void> rc,
1064 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001065 auto& [ret, certChain] = hidlResult;
1066 if (!rc.isOk()) {
1067 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1068 } else if (ret != ErrorCode::OK) {
Janis Danisevskis37896102019-03-14 17:15:06 -07001069 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001070 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1071 } else {
1072 cb->onFinished(KeyStoreServiceReturnCode(ret),
1073 KeymasterCertificateChain(std::move(certChain)));
1074 }
1075 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001076
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001077 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001078}
1079
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001080// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1081// It should never be redefined by a build system though.
1082#ifndef CAPTURE_MOVE
1083#define CAPTURE_MOVE(x) x = std::move(x)
1084#endif
1085
1086Status KeyStoreService::attestDeviceIds(
1087 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1088 const KeymasterArguments& params, int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001089 KEYSTORE_SERVICE_LOCK;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001090 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001091
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001092 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001093 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001094 }
1095
1096 if (!isDeviceIdAttestationRequested(params)) {
1097 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001098 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001099 }
1100
1101 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1102 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
Yi Konge353f252018-07-30 01:38:39 -07001103 if (binder == nullptr) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001104 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001105 }
1106 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1107 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1108 IPCThreadState::self()->getCallingPid(), callingUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001109 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001110 }
1111
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001112 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001113 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1114 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001115 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001116 }
1117
1118 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001119 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001120
Shawn Willden70c1a782018-07-11 15:13:20 -06001121 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001122 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001123 }
1124
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001125
1126 AuthorizationSet keyCharacteristics;
1127 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1128 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1129 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1130 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1131 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001132
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001133 std::promise<KeyStoreServiceReturnCode> resultPromise;
1134 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001135
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001136 dev->generateKey(
1137 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001138 [cb, dev, CAPTURE_MOVE(mutableParams)](
1139 Return<void> rc,
1140 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001141 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1142 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1143 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001144 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001145 return;
1146 }
1147 if (ret != ErrorCode::OK) {
Janis Danisevskis37896102019-03-14 17:15:06 -07001148 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001149 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001150 return;
1151 }
1152 dev->attestKey(
1153 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001154 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001155 hidlKeyBlob](Return<void> rc,
1156 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1157 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001158 // schedule temp key for deletion
Janis Danisevskis37896102019-03-14 17:15:06 -07001159 dev->deleteKey(std::move(hidlKeyBlob), [dev](Return<ErrorCode> rc) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001160 // log error but don't return an error
Janis Danisevskis37896102019-03-14 17:15:06 -07001161 KS_HANDLE_HIDL_ERROR(dev, rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001162 });
1163 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001164 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001165 return;
1166 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001167 if (ret == ErrorCode::OK) {
1168 cb->onFinished(
1169 KeyStoreServiceReturnCode(ret),
1170 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1171 } else {
Janis Danisevskis37896102019-03-14 17:15:06 -07001172 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001173 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001174 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001175 });
1176 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001177
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001178 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001179}
1180
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001181Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001182 KEYSTORE_SERVICE_LOCK;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001183 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001184 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001185 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1186 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001187}
1188
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001189Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001190 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001191 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1192 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1193 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001194 int32_t* _aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001195 KEYSTORE_SERVICE_LOCK;
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001196
1197 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1198
1199 if (!checkBinderPermission(P_INSERT, callingUid)) {
1200 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1201 }
1202
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001203 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001204
1205 KeyStoreServiceReturnCode rc;
1206 Blob wrappingKeyBlob;
1207 Blob wrappingCharBlob;
1208 LockedKeyBlobEntry wrappingLockedEntry;
1209
1210 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1211 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
Branden Archerd166a882018-11-20 10:56:48 -08001212 if (!rc.isOk()) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001213 return AIDL_RETURN(rc);
1214 }
1215
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001216 String8 wrappedKeyName8(wrappedKeyAlias);
1217 auto wrappedLockedEntry =
1218 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1219 if (!wrappedLockedEntry) {
1220 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1221 }
1222
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001223 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1224 auto dev = mKeyStore->getDevice(securityLevel);
1225 if (!dev) {
1226 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1227 }
1228
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001229 dev->importWrappedKey(
1230 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1231 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001232 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1233 cb->onFinished(rc,
1234 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001235 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001236
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001237 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001238}
1239
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001240Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1241 const String16& promptText,
1242 const ::std::vector<uint8_t>& extraData,
1243 const String16& locale, int32_t uiOptionsAsFlags,
1244 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001245 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001246 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1247 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001248}
1249
1250Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1251 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001252 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001253 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001254}
1255
David Zeuthen1a492312018-02-26 11:00:30 -05001256Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001257 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001258 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001259}
1260
1261/**
1262 * Get the effective target uid for a binder operation that takes an
1263 * optional uid as the target.
1264 */
1265uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1266 if (targetUid == UID_SELF) {
1267 return IPCThreadState::self()->getCallingUid();
1268 }
1269 return static_cast<uid_t>(targetUid);
1270}
1271
1272/**
1273 * Check if the caller of the current binder method has the required
1274 * permission and if acting on other uids the grants to do so.
1275 */
1276bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1277 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1278 pid_t spid = IPCThreadState::self()->getCallingPid();
1279 if (!has_permission(callingUid, permission, spid)) {
1280 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1281 return false;
1282 }
1283 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1284 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1285 return false;
1286 }
1287 return true;
1288}
1289
1290/**
1291 * Check if the caller of the current binder method has the required
1292 * permission and the target uid is the caller or the caller is system.
1293 */
1294bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1295 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1296 pid_t spid = IPCThreadState::self()->getCallingPid();
1297 if (!has_permission(callingUid, permission, spid)) {
1298 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1299 return false;
1300 }
1301 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1302}
1303
1304/**
1305 * Check if the caller of the current binder method has the required
1306 * permission or the target of the operation is the caller's uid. This is
1307 * for operation where the permission is only for cross-uid activity and all
1308 * uids are allowed to act on their own (ie: clearing all entries for a
1309 * given uid).
1310 */
1311bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1312 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1313 if (getEffectiveUid(targetUid) == callingUid) {
1314 return true;
1315 } else {
1316 return checkBinderPermission(permission, targetUid);
1317 }
1318}
1319
1320/**
1321 * Helper method to check that the caller has the required permission as
1322 * well as the keystore is in the unlocked state if checkUnlocked is true.
1323 *
1324 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1325 * otherwise the state of keystore when not unlocked and checkUnlocked is
1326 * true.
1327 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001328KeyStoreServiceReturnCode
1329KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1330 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001331 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001332 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001333 }
1334 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1335 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001336 // All State values coincide with ResponseCodes
1337 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001338 }
1339
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001340 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001341}
1342
1343bool KeyStoreService::isKeystoreUnlocked(State state) {
1344 switch (state) {
1345 case ::STATE_NO_ERROR:
1346 return true;
1347 case ::STATE_UNINITIALIZED:
1348 case ::STATE_LOCKED:
1349 return false;
1350 }
1351 return false;
1352}
1353
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001354/**
Shawn Willden0329a822017-12-04 13:55:14 -07001355 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1356 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001357 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001358bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1359 for (size_t i = 0; i < params.size(); ++i) {
1360 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001361 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001362 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001363 return false;
1364 default:
1365 break;
1366 }
1367 }
1368 return true;
1369}
1370
Brian Young9a947d52018-02-23 18:03:14 +00001371Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
1372 int32_t* aidl_return) {
Janis Danisevskisb50236a2019-03-25 10:26:30 -07001373 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001374 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Brian Young9a947d52018-02-23 18:03:14 +00001375 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001376
1377 return Status::ok();
1378}
1379
Shawn Willdene2a7b522017-04-11 09:27:40 -06001380} // namespace keystore