blob: 8501cdf81f7666c471ff7ff2badeee447a8ee1d0 [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"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010044#include "keystore_keymaster_enforcement.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070045#include "keystore_utils.h"
David Zeuthenf2a28672020-01-30 16:20:07 -050046#include <keystore/keystore_attestation_id.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;
David Zeuthen59102f32020-05-08 10:58:09 -040059using android::hardware::keymaster::V4_0::support::authToken2HidlVec;
60using android::hardware::keymaster::V4_0::support::serializeVerificationToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070061using android::security::keymaster::ExportResult;
62using android::security::keymaster::KeymasterArguments;
63using android::security::keymaster::KeymasterBlob;
64using android::security::keymaster::KeymasterCertificateChain;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070065using android::security::keymaster::operationFailed;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070066using android::security::keymaster::OperationResult;
David Zeuthenc6eb7cd2017-11-27 11:33:55 -050067using ConfirmationResponseCode = android::hardware::confirmationui::V1_0::ResponseCode;
David Zeuthen59102f32020-05-08 10:58:09 -040068using ::android::security::keystore::ICredstoreTokenCallback;
Rob Barnesbb6cabd2018-10-04 17:10:37 -060069using ::android::security::keystore::IKeystoreOperationResultCallback;
70using ::android::security::keystore::IKeystoreResponseCallback;
71using ::android::security::keystore::KeystoreResponse;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070072
Shawn Willdene2a7b522017-04-11 09:27:40 -060073constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
74const char* kTimestampFilePath = "timestamp";
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070075
Shawn Willdene2a7b522017-04-11 09:27:40 -060076bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070077 return params.end() !=
78 std::find_if(params.begin(), params.end(),
79 [&](const KeyParameter& param) { return param.tag == tag; });
Shawn Willdend5a24e62017-02-28 13:53:24 -070080}
81
Branden Archer70080742018-11-20 11:04:11 -080082#define AIDL_RETURN(rc) (*_aidl_return = KeyStoreServiceReturnCode(rc).getErrorCode(), Status::ok())
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");
Shawn Willden6f7d27c2019-09-11 22:51:46 -0600123 // Couldn't get attestation ID; just use an empty one rather than failing.
124 asn1_attestation_id_result = std::vector<uint8_t>();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200125 }
126 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
127
128 /*
Eran Messeri03fc4c82018-08-16 18:53:15 +0100129 * The attestation application ID must not be longer than
130 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, error out if gather_attestation_application_id
131 * returned such an invalid vector.
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200132 */
133 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Eran Messeri03fc4c82018-08-16 18:53:15 +0100134 ALOGE("BUG: Gathered Attestation Application ID is too big (%d)",
135 static_cast<int32_t>(asn1_attestation_id.size()));
136 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200137 }
138
139 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
140
141 return ResponseCode::NO_ERROR;
142}
143
Shawn Willdene2a7b522017-04-11 09:27:40 -0600144} // anonymous namespace
145
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700146Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
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) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700156 uid_t targetUid = getEffectiveUid(uid);
157 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700158 // see keystore/keystore.h
159 return Status::fromServiceSpecificError(
160 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700161 }
162
163 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700164 ResponseCode rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700165 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700166 Blob charBlob;
167 LockedKeyBlobEntry lockedEntry;
168
169 std::tie(rc, keyBlob, charBlob, lockedEntry) =
170 mKeyStore->getKeyForName(name8, targetUid, TYPE_GENERIC);
171 if (rc != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700172 *item = ::std::vector<uint8_t>();
173 // Return empty array if key is not found
174 // TODO: consider having returned value nullable or parse exception on the client.
175 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700176 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100177 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700178 // The static_cast here is needed to prevent a move, forcing a deep copy.
179 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
180 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700181}
182
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700183Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
184 int targetUid, int32_t flags, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700185 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700186 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700187 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100188 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800189 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700190 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700191 }
192
193 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700194 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), targetUid);
195
196 if (!lockedEntry) {
197 ALOGE("failed to grab lock on blob entry %u_%s", targetUid, name8.string());
198 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_ALREADY_EXISTS);
199 return Status::ok();
200 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700201
Yi Konge353f252018-07-30 01:38:39 -0700202 Blob keyBlob(&item[0], item.size(), nullptr, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700203 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
204
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700205 *aidl_return = static_cast<int32_t>(mKeyStore->put(lockedEntry, keyBlob, {}));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700206 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700207}
208
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700209Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700210 targetUid = getEffectiveUid(targetUid);
211 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700212 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
213 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700214 }
215 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000216 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700217 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
218 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700219 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
220 return Status::ok();
221 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700222
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700223 ResponseCode result = mKeyStore->del(lockedEntry);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400224
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700225 *aidl_return = static_cast<int32_t>(result);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700226 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700227}
228
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700229Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700230 targetUid = getEffectiveUid(targetUid);
231 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700232 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
233 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700234 }
235
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700236 LockedKeyBlobEntry lockedEntry =
237 mKeyStore->getLockedBlobEntryIfExists(String8(name).string(), targetUid);
238 *aidl_return =
239 static_cast<int32_t>(lockedEntry ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700240 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700241}
242
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700243Status KeyStoreService::list(const String16& prefix, int32_t targetUid,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700244 ::std::vector<::android::String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700245 targetUid = getEffectiveUid(targetUid);
246 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700247 return Status::fromServiceSpecificError(
248 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700249 }
250 const String8 prefix8(prefix);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700251 const std::string stdPrefix(prefix8.string());
252
253 ResponseCode rc;
254 std::list<LockedKeyBlobEntry> internal_matches;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800255 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700256
Janis Danisevskis265435f2018-11-16 14:10:46 -0800257 std::tie(rc, internal_matches) =
258 LockedKeyBlobEntry::list(userDirName, [&](uid_t uid, const std::string& alias) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700259 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end());
260 return uid == static_cast<uid_t>(targetUid) &&
261 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end())
262 .first == stdPrefix.end();
263 });
264
265 if (rc != ResponseCode::NO_ERROR) {
266 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700267 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700268
269 for (LockedKeyBlobEntry& entry : internal_matches) {
270 matches->push_back(String16(entry->alias().substr(prefix8.size()).c_str()));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700271 }
272 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700273}
274
Rob Barneseb7f79b2018-11-08 15:44:10 -0700275/*
276 * This method will return the uids of all auth bound keys for the calling user.
277 * This is intended to be used for alerting the user about which apps will be affected
278 * if the password/pin is removed. Only allowed to be called by system.
279 * The output is bound by the initial size of uidsOut to be compatible with Java.
280 */
Rob Barnes5d59e632018-12-07 16:09:02 -0700281Status KeyStoreService::listUidsOfAuthBoundKeys(std::vector<std::string>* uidsOut,
Rob Barneseb7f79b2018-11-08 15:44:10 -0700282 int32_t* aidl_return) {
283 const int32_t callingUid = IPCThreadState::self()->getCallingUid();
284 const int32_t userId = get_user_id(callingUid);
285 const int32_t appId = get_app_id(callingUid);
286 if (appId != AID_SYSTEM) {
287 ALOGE("Permission listUidsOfAuthBoundKeys denied for aid %d", appId);
288 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
289 return Status::ok();
290 }
291
292 const String8 prefix8("");
293 auto userState = mKeyStore->getUserStateDB().getUserState(userId);
294 const std::string userDirName = userState->getUserDirName();
295 auto encryptionKey = userState->getEncryptionKey();
296 auto state = userState->getState();
297 // unlock the user state
298 userState = {};
299
300 ResponseCode rc;
301 std::list<LockedKeyBlobEntry> internal_matches;
302 std::tie(rc, internal_matches) =
303 LockedKeyBlobEntry::list(userDirName, [&](uid_t, const std::string&) {
304 // Need to filter on auth bound state, so just return true.
305 return true;
306 });
307 if (rc != ResponseCode::NO_ERROR) {
308 ALOGE("Error listing blob entries for user %d", userId);
309 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
310 }
311
Rob Barneseb7f79b2018-11-08 15:44:10 -0700312 for (LockedKeyBlobEntry& entry : internal_matches) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700313 // Need to store uids as a list of strings because integer list output
314 // parameters is not supported in aidl-cpp.
315 std::string entryUid = std::to_string(entry->uid());
316 if (std::find(uidsOut->begin(), uidsOut->end(), entryUid) != uidsOut->end()) {
Rob Barneseb7f79b2018-11-08 15:44:10 -0700317 // uid already in list, skip
318 continue;
319 }
320
321 auto [rc, blob, charBlob] = entry.readBlobs(encryptionKey, state);
322 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::LOCKED) {
323 ALOGE("Error reading blob for key %s", entry->alias().c_str());
324 continue;
325 }
326
327 if (blob && blob.isEncrypted()) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700328 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700329 } else if (charBlob) {
330 auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
331 if (!success) {
332 ALOGE("Error reading blob characteristics for key %s", entry->alias().c_str());
333 continue;
334 }
335 if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
336 swEnforced.Contains(TAG_USER_SECURE_ID)) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700337 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700338 }
339 }
340 }
341 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
342 return Status::ok();
343}
344
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700345Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
346 int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700347 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700348 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
349 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700350 }
351
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700352 if (password.size() == 0) {
353 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
354 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700355 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
356 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700357 } else {
Pavel Grafovf9b53eb2019-02-06 17:16:21 +0000358 const String8 password8(password);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700359 switch (mKeyStore->getState(userId)) {
360 case ::STATE_UNINITIALIZED: {
361 // generate master key, encrypt with password, write to file,
362 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700363 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
364 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700365 }
366 case ::STATE_NO_ERROR: {
367 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700368 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
369 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700370 }
371 case ::STATE_LOCKED: {
372 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
373 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700374 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
375 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700376 }
377 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700378 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
379 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700380 }
381}
382
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700383Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700384 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700385 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
386 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700387 }
388
389 // Sanity check that the new user has an empty keystore.
390 if (!mKeyStore->isEmpty(userId)) {
391 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
392 }
393 // Unconditionally clear the keystore, just to be safe.
394 mKeyStore->resetUser(userId, false);
395 if (parentId != -1) {
396 // This profile must share the same master key password as the parent profile. Because the
397 // password of the parent profile is not known here, the best we can do is copy the parent's
398 // master key and master key file. This makes this profile use the same master key as the
399 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700400 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
401 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700402 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700403 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
404 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700405 }
406}
407
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700408Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
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 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700415 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
416 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700417}
418
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700419Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700420 if (!checkBinderPermission(P_LOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700421 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
422 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700423 }
424
425 State state = mKeyStore->getState(userId);
426 if (state != ::STATE_NO_ERROR) {
427 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700428 *aidl_return = static_cast<int32_t>(ResponseCode(state));
429 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700430 }
431
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700432 mKeyStore->getEnforcementPolicy().set_device_locked(true, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700433 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700434 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
435 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700436}
437
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700438Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700439 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700440 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
441 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700442 }
443
444 State state = mKeyStore->getState(userId);
445 if (state != ::STATE_LOCKED) {
446 switch (state) {
447 case ::STATE_NO_ERROR:
448 ALOGI("calling unlock when already unlocked, ignoring.");
449 break;
450 case ::STATE_UNINITIALIZED:
451 ALOGE("unlock called on uninitialized keystore.");
452 break;
453 default:
454 ALOGE("unlock called on keystore in unknown state: %d", state);
455 break;
456 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700457 *aidl_return = static_cast<int32_t>(ResponseCode(state));
458 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700459 }
460
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700461 mKeyStore->getEnforcementPolicy().set_device_locked(false, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700462 const String8 password8(pw);
463 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700464 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
465 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700466}
467
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700468Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700469 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700470 *aidl_return = static_cast<int32_t>(false);
471 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700472 }
473
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700474 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
475 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700476}
477
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700478Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
479 ::android::String16* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700480 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700481 auto result =
482 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100483 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700484 *aidl_return = String16();
485 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700486 }
487
488 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700489 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
490 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700491 *aidl_return = String16();
492 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700493 }
494
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700495 *aidl_return = String16(mKeyStore->addGrant(lockedEntry, granteeUid).c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700496 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700497}
498
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700499Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700500 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700501 KeyStoreServiceReturnCode result =
502 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100503 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800504 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700505 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700506 }
507
508 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700509
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700510 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
511 if (!lockedEntry) {
512 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700513 }
514
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700515 *aidl_return = mKeyStore->removeGrant(lockedEntry, granteeUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700516 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700517}
518
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700519Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700520 uid_t targetUid = getEffectiveUid(uid);
521 if (!checkBinderPermission(P_GET, targetUid)) {
522 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700523 *time = -1L;
524 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700525 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700526 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700527
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700528 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
529 if (!lockedEntry) {
530 ALOGW("could not access key with alias %s for getmtime", name8.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700531 *time = -1L;
532 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700533 }
534
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700535 std::string filename = lockedEntry->getKeyBlobPath();
536
537 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700538 if (fd < 0) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700539 ALOGW("could not open %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700540 *time = -1L;
541 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700542 }
543
544 struct stat s;
545 int ret = fstat(fd, &s);
546 close(fd);
547 if (ret == -1) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700548 ALOGW("could not stat %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700549 *time = -1L;
550 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700551 }
552
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700553 *time = static_cast<int64_t>(s.st_mtime);
554 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700555}
556
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700557Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
558 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
559 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700560}
561
Janis Danisevskis265435f2018-11-16 14:10:46 -0800562Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700563 uid_t targetUid = getEffectiveUid(targetUid64);
564 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800565 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700566 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000567 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700568
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700569 mKeyStore->removeAllGrantsToUid(targetUid);
570
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700571 ResponseCode rc;
572 std::list<LockedKeyBlobEntry> entries;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800573 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700574
575 // list has a fence making sure no workers are modifying blob files before iterating the
576 // data base. All returned entries are locked.
577 std::tie(rc, entries) = LockedKeyBlobEntry::list(
Janis Danisevskis265435f2018-11-16 14:10:46 -0800578 userDirName, [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700579
580 if (rc != ResponseCode::NO_ERROR) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800581 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700582 }
583
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700584 for (LockedKeyBlobEntry& lockedEntry : entries) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100585 if (get_app_id(targetUid) == AID_SYSTEM) {
586 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700587 Blob charBlob;
588 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
589 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100590 // Do not clear keys critical to device encryption under system uid.
591 continue;
592 }
593 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700594 mKeyStore->del(lockedEntry);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700595 }
Janis Danisevskis265435f2018-11-16 14:10:46 -0800596 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700597}
598
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600599Status KeyStoreService::addRngEntropy(
600 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
601 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
Janis Danisevskisc1460142017-12-18 16:48:46 -0800602 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
603 if (!device) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600604 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800605 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700606
Janis Danisevskisa359c672019-03-14 17:15:06 -0700607 device->addRngEntropy(entropy, [device, cb](Return<ErrorCode> rc) {
608 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device, rc)));
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600609 });
610
611 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700612}
613
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600614Status KeyStoreService::generateKey(
615 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
616 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
617 int uid, int flags, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700618 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000619 auto logOnScopeExit = android::base::make_scope_guard([&] {
620 if (__android_log_security()) {
621 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600622 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000623 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
624 }
625 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100626 KeyStoreServiceReturnCode rc =
627 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
628 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600629 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700630 }
Rubin Xu67899de2017-04-21 19:15:13 +0100631 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
632 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600633 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100634 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700635
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700636 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Max Bires36ae17f2019-11-12 21:34:24 +0000637 if (!checkBinderPermission(P_GEN_UNIQUE_ID)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600638 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700639 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600640 }
641
Janis Danisevskisc1460142017-12-18 16:48:46 -0800642 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
643 auto dev = mKeyStore->getDevice(securityLevel);
644 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600645 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800646 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400647
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100648 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700649 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
650 if (!lockedEntry) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600651 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100652 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400653
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700654 logOnScopeExit.Disable();
655
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600656 dev->generateKey(
657 std::move(lockedEntry), params.getParameters(), entropy, flags,
658 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
659 if (__android_log_security()) {
660 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
661 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
662 }
663 cb->onFinished(rc,
664 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
665 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700666
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600667 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700668}
669
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700670Status KeyStoreService::getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600671 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700672 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
Janis Danisevskis64ec1fe2018-02-26 16:47:21 -0800673 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600674 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700675
676 uid_t targetUid = getEffectiveUid(uid);
677 uid_t callingUid = IPCThreadState::self()->getCallingUid();
678 if (!is_granted_to(callingUid, targetUid)) {
679 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
680 targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600681 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700682 }
683
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700684 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700685
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700686 ResponseCode rc;
687 Blob keyBlob;
688 Blob charBlob;
689 LockedKeyBlobEntry lockedEntry;
Janis Danisevskisd714a672017-09-01 14:31:36 -0700690
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700691 std::tie(rc, keyBlob, charBlob, lockedEntry) =
692 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
693
694 if (rc != ResponseCode::NO_ERROR) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600695 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700696 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100697
Janis Danisevskisc1460142017-12-18 16:48:46 -0800698 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700699 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600700 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100701 }
702
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700703 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
704 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
705 // from keymaster. It may also upgrade the key blob.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700706 dev->getKeyCharacteristics(
707 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
708 std::move(charBlob),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600709 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
710 cb->onFinished(rc,
711 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700712 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100713
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600714 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700715}
716
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600717Status KeyStoreService::importKey(
718 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
719 const String16& name, const KeymasterArguments& params, int32_t format,
720 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700721 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000722 auto logOnScopeExit = android::base::make_scope_guard([&] {
723 if (__android_log_security()) {
724 android_log_event_list(SEC_TAG_KEY_IMPORTED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600725 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000726 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
727 }
728 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100729 KeyStoreServiceReturnCode rc =
730 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
731 if (!rc.isOk()) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700732 LOG(ERROR) << "permissission denied";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600733 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700734 }
Rubin Xu67899de2017-04-21 19:15:13 +0100735 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
736 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600737 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100738 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700739
Janis Danisevskisc1460142017-12-18 16:48:46 -0800740 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
741 auto dev = mKeyStore->getDevice(securityLevel);
742 if (!dev) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700743 LOG(ERROR) << "importKey - cound not get keymaster device";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600744 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800745 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700746
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700747 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700748 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
749 if (!lockedEntry) {
750 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
751 << " already exists.";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600752 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400753 }
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700754
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700755 logOnScopeExit.Disable();
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700756
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600757 dev->importKey(
758 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
759 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
760 if (__android_log_security()) {
761 android_log_event_list(SEC_TAG_KEY_IMPORTED)
762 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
763 }
764 cb->onFinished(rc,
765 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
766 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400767
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600768 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700769}
770
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600771Status KeyStoreService::exportKey(
772 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
773 const String16& name, int32_t format,
774 const ::android::security::keymaster::KeymasterBlob& clientId,
775 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
776 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700777
778 uid_t targetUid = getEffectiveUid(uid);
779 uid_t callingUid = IPCThreadState::self()->getCallingUid();
780 if (!is_granted_to(callingUid, targetUid)) {
781 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600782 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700783 }
784
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700785 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700786
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700787 KeyStoreServiceReturnCode rc;
788 Blob keyBlob;
789 Blob charBlob;
790 LockedKeyBlobEntry lockedEntry;
791
792 std::tie(rc, keyBlob, charBlob, lockedEntry) =
793 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskis3cf85322018-11-19 13:37:49 -0800794 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600795 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700796 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100797
Janis Danisevskisc1460142017-12-18 16:48:46 -0800798 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100799
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700800 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600801 std::move(keyBlob), std::move(charBlob),
802 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
Ji Wang2c142312016-10-14 17:21:10 +0800803
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600804 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700805}
806
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600807Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
808 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700809 bool pruneable, const KeymasterArguments& params,
810 const ::std::vector<uint8_t>& entropy, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600811 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700812 uid_t callingUid = IPCThreadState::self()->getCallingUid();
813 uid_t targetUid = getEffectiveUid(uid);
814 if (!is_granted_to(callingUid, targetUid)) {
815 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600816 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700817 }
818 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
819 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600820 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700821 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700822 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600823 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700824 }
Shawn Willden0329a822017-12-04 13:55:14 -0700825
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700826 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700827 Blob keyBlob;
828 Blob charBlob;
829 LockedKeyBlobEntry lockedEntry;
830 ResponseCode rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100831
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700832 std::tie(rc, keyBlob, charBlob, lockedEntry) =
833 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
834
835 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600836 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700837 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600838 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700839
Janis Danisevskisc1460142017-12-18 16:48:46 -0800840 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700841 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100842
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700843 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
844 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600845 [this, cb, dev](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700846 if (result_.resultCode.isOk() ||
847 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700848 mKeyStore->addOperationDevice(result_.token, dev);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700849 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600850 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700851 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400852
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600853 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700854}
855
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600856Status KeyStoreService::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
857 const ::android::sp<::android::IBinder>& token,
858 const ::android::security::keymaster::KeymasterArguments& params,
859 const ::std::vector<uint8_t>& input, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700860 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600861 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700862 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700863
Janis Danisevskisbec89992019-08-14 13:42:19 -0700864 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700865 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600866 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700867 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700868
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600869 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700870 if (!result_.resultCode.isOk()) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700871 mKeyStore->removeOperationDevice(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100872 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600873 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700874 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100875
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600876 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700877}
878
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600879Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
880 const ::android::sp<::android::IBinder>& token,
881 const ::android::security::keymaster::KeymasterArguments& params,
Rob Barnes3af223f2019-11-14 14:50:30 -0700882 const ::std::vector<uint8_t>& input,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700883 const ::std::vector<uint8_t>& signature,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600884 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700885 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600886 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700887 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700888
Janis Danisevskisbec89992019-08-14 13:42:19 -0700889 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700890 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600891 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700892 }
893
Rob Barnes3af223f2019-11-14 14:50:30 -0700894 dev->finish(token, params.getParameters(), input, signature, entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600895 [this, cb, token](OperationResult result_) {
Janis Danisevskis8c4c1d62019-10-04 11:01:54 -0700896 mKeyStore->removeOperationDevice(token);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600897 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700898 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700899
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600900 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700901}
902
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600903Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
904 const ::android::sp<::android::IBinder>& token,
905 int32_t* _aidl_return) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700906 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700907 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600908 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700909 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100910
Janis Danisevskisbec89992019-08-14 13:42:19 -0700911 dev->abort(token, [this, cb, token](KeyStoreServiceReturnCode rc) {
912 mKeyStore->removeOperationDevice(token);
913 cb->onFinished(rc);
914 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700915
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600916 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700917}
918
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700919Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000920 int32_t* aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700921
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000922 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
923 // receive a HardwareAuthToken, rather than an opaque byte array.
924
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700925 if (!checkBinderPermission(P_ADD_AUTH)) {
926 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700927 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
928 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700929 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700930 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
Branden Archer70080742018-11-20 11:04:11 -0800931 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700932 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000933 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100934
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000935 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700936 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000937 if (authToken.version != 0) {
Branden Archer70080742018-11-20 11:04:11 -0800938 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700939 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000940 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100941
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700942 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
943 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700944 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
945 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700946}
947
David Zeuthen59102f32020-05-08 10:58:09 -0400948Status KeyStoreService::getTokensForCredstore(int64_t challenge, int64_t secureUserId,
949 int32_t authTokenMaxAgeMillis,
950 const ::android::sp<ICredstoreTokenCallback>& cb) {
David Zeuthenab3e5652019-10-28 13:32:48 -0400951 uid_t callingUid = IPCThreadState::self()->getCallingUid();
952 if (callingUid != AID_CREDSTORE) {
953 return Status::fromServiceSpecificError(static_cast<int32_t>(0));
954 }
955
956 auto [err, authToken] = mKeyStore->getAuthTokenTable().FindAuthorizationForCredstore(
957 challenge, secureUserId, authTokenMaxAgeMillis);
David Zeuthen59102f32020-05-08 10:58:09 -0400958 // It's entirely possible we couldn't find an authToken (e.g. no user auth
959 // happened within the requested deadline) and in that case, we just
960 // callback immediately signaling success but just not returning any tokens.
961 if (err != AuthTokenTable::OK) {
962 cb->onFinished(true, {} /* serializedAuthToken */, {} /* serializedVerificationToken */);
963 return Status::ok();
David Zeuthenab3e5652019-10-28 13:32:48 -0400964 }
David Zeuthen59102f32020-05-08 10:58:09 -0400965
966 // If we did find an authToken, get a verificationToken as well...
967 //
968 std::vector<uint8_t> serializedAuthToken = authToken2HidlVec(authToken);
969 std::vector<uint8_t> serializedVerificationToken;
970 std::shared_ptr<KeymasterWorker> dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
971 if (!dev) {
972 LOG(ERROR) << "Unable to get KM device for SecurityLevel::TRUSTED_ENVIRONMENT";
973 dev = mKeyStore->getDevice(SecurityLevel::SOFTWARE);
974 if (!dev) {
975 LOG(ERROR) << "Unable to get KM device for SecurityLevel::SOFTWARE";
976 cb->onFinished(false, {}, {});
977 return Status::fromServiceSpecificError(static_cast<int32_t>(0));
978 }
979 }
980
981 dev->verifyAuthorization(
982 challenge, {} /* params */, authToken,
983 [serializedAuthToken, cb](KeyStoreServiceReturnCode rc, HardwareAuthToken,
984 VerificationToken verificationToken) {
985 if (rc != ErrorCode::OK) {
986 LOG(ERROR) << "verifyAuthorization failed, rc=" << rc;
987 cb->onFinished(false, {}, {});
988 return;
989 }
990 std::optional<std::vector<uint8_t>> serializedVerificationToken =
991 serializeVerificationToken(verificationToken);
992 if (!serializedVerificationToken) {
993 LOG(ERROR) << "Error serializing verificationToken";
994 cb->onFinished(false, {}, {});
995 return;
996 }
997 cb->onFinished(true, serializedAuthToken, serializedVerificationToken.value());
998 });
999
David Zeuthenab3e5652019-10-28 13:32:48 -04001000 return Status::ok();
1001}
1002
Dorin Drimus4b7a7fb2020-04-20 17:32:13 +02001003bool isDeviceIdAttestationTag(Tag tag) {
1004 switch (tag) {
1005 case Tag::ATTESTATION_ID_BRAND:
1006 case Tag::ATTESTATION_ID_DEVICE:
1007 case Tag::ATTESTATION_ID_MANUFACTURER:
1008 case Tag::ATTESTATION_ID_MODEL:
1009 case Tag::ATTESTATION_ID_PRODUCT:
1010 case Tag::ATTESTATION_ID_IMEI:
1011 case Tag::ATTESTATION_ID_MEID:
1012 case Tag::ATTESTATION_ID_SERIAL:
1013 return true;
1014 case Tag::INVALID:
1015 case Tag::PURPOSE:
1016 case Tag::ALGORITHM:
1017 case Tag::KEY_SIZE:
1018 case Tag::BLOCK_MODE:
1019 case Tag::DIGEST:
1020 case Tag::PADDING:
1021 case Tag::CALLER_NONCE:
1022 case Tag::MIN_MAC_LENGTH:
1023 case Tag::EC_CURVE:
1024 case Tag::RSA_PUBLIC_EXPONENT:
1025 case Tag::INCLUDE_UNIQUE_ID:
1026 case Tag::BLOB_USAGE_REQUIREMENTS:
1027 case Tag::BOOTLOADER_ONLY:
1028 case Tag::ROLLBACK_RESISTANCE:
1029 case Tag::HARDWARE_TYPE:
1030 case Tag::ACTIVE_DATETIME:
1031 case Tag::ORIGINATION_EXPIRE_DATETIME:
1032 case Tag::USAGE_EXPIRE_DATETIME:
1033 case Tag::MIN_SECONDS_BETWEEN_OPS:
1034 case Tag::MAX_USES_PER_BOOT:
1035 case Tag::USER_ID:
1036 case Tag::USER_SECURE_ID:
1037 case Tag::NO_AUTH_REQUIRED:
1038 case Tag::USER_AUTH_TYPE:
1039 case Tag::AUTH_TIMEOUT:
1040 case Tag::ALLOW_WHILE_ON_BODY:
1041 case Tag::TRUSTED_USER_PRESENCE_REQUIRED:
1042 case Tag::TRUSTED_CONFIRMATION_REQUIRED:
1043 case Tag::UNLOCKED_DEVICE_REQUIRED:
1044 case Tag::APPLICATION_ID:
1045 case Tag::APPLICATION_DATA:
1046 case Tag::CREATION_DATETIME:
1047 case Tag::ORIGIN:
1048 case Tag::ROOT_OF_TRUST:
1049 case Tag::OS_VERSION:
1050 case Tag::OS_PATCHLEVEL:
1051 case Tag::UNIQUE_ID:
1052 case Tag::ATTESTATION_CHALLENGE:
1053 case Tag::ATTESTATION_APPLICATION_ID:
1054 case Tag::VENDOR_PATCHLEVEL:
1055 case Tag::BOOT_PATCHLEVEL:
1056 case Tag::ASSOCIATED_DATA:
1057 case Tag::NONCE:
1058 case Tag::MAC_LENGTH:
1059 case Tag::RESET_SINCE_ID_ROTATION:
1060 case Tag::CONFIRMATION_TOKEN:
1061 return false;
1062 // no default, all values must be present in the switch, in this way the compiler ensures
1063 // that new values added in the Tag enum are also added here.
1064 }
1065}
1066
1067// These are attestation id tags that are not unique per device and don't require special permission
1068// to be attested. Any addition to this list needs privacy review and approval (PWG).
1069bool isDevicePropertyAttestationTag(Tag tag) {
1070 switch (tag) {
1071 case Tag::ATTESTATION_ID_BRAND:
1072 case Tag::ATTESTATION_ID_DEVICE:
1073 case Tag::ATTESTATION_ID_MANUFACTURER:
1074 case Tag::ATTESTATION_ID_MODEL:
1075 case Tag::ATTESTATION_ID_PRODUCT:
1076 return true;
1077 default:
1078 return false;
1079 }
1080}
1081
Eran Messerid9f8ae52018-10-24 13:54:00 +01001082bool isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -07001083 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001084 for (size_t i = 0; i < paramsVec.size(); ++i) {
Dorin Drimus4b7a7fb2020-04-20 17:32:13 +02001085 if (isDeviceIdAttestationTag(paramsVec[i].tag)) {
Eran Messerid9f8ae52018-10-24 13:54:00 +01001086 return true;
Dorin Drimus4b7a7fb2020-04-20 17:32:13 +02001087 }
1088 }
1089 return false;
1090}
1091
1092// Device properties can be attested safely without special permission
1093bool needsPermissionToAttestDeviceIds(const KeymasterArguments& params) {
1094 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
1095 for (size_t i = 0; i < paramsVec.size(); ++i) {
1096 if (isDeviceIdAttestationTag(paramsVec[i].tag) &&
1097 !isDevicePropertyAttestationTag(paramsVec[i].tag)) {
1098 return true;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001099 }
1100 }
Eran Messerid9f8ae52018-10-24 13:54:00 +01001101 return false;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001102}
1103
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001104Status KeyStoreService::attestKey(
1105 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1106 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001107 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1108 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001109 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001110 }
1111
Eran Messerie2c34152017-12-21 21:01:22 +00001112 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1113
Dorin Drimus2f43a6a2020-05-05 19:19:24 +02001114 if (needsPermissionToAttestDeviceIds(params) && (get_app_id(callingUid) != AID_SYSTEM)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001115 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001116 }
1117
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001118 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001119 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1120 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001121 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001122 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001123
Shawn Willden50eb1b22016-01-21 12:41:23 -07001124 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001125 Blob keyBlob;
1126 Blob charBlob;
1127 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001128
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001129 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1130 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1131
Janis Danisevskis9dff56c2019-07-10 14:08:06 -07001132 if (!rc.isOk()) {
1133 return AIDL_RETURN(rc);
1134 }
1135
Janis Danisevskisc1460142017-12-18 16:48:46 -08001136 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001137 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001138 dev->attestKey(
1139 std::move(hidlKey), mutableParams.hidl_data(),
Janis Danisevskisa359c672019-03-14 17:15:06 -07001140 [dev, cb](Return<void> rc,
1141 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001142 auto& [ret, certChain] = hidlResult;
1143 if (!rc.isOk()) {
1144 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1145 } else if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001146 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001147 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1148 } else {
1149 cb->onFinished(KeyStoreServiceReturnCode(ret),
1150 KeymasterCertificateChain(std::move(certChain)));
1151 }
1152 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001153
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001154 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001155}
1156
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001157// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1158// It should never be redefined by a build system though.
1159#ifndef CAPTURE_MOVE
1160#define CAPTURE_MOVE(x) x = std::move(x)
1161#endif
1162
1163Status KeyStoreService::attestDeviceIds(
1164 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1165 const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001166 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001167
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001168 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001169 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001170 }
1171
1172 if (!isDeviceIdAttestationRequested(params)) {
1173 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001174 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001175 }
1176
1177 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Dorin Drimus4b7a7fb2020-04-20 17:32:13 +02001178
1179 // Request special permission only for unique ids
1180 if (needsPermissionToAttestDeviceIds(params)) {
1181 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1182 if (binder == nullptr) {
1183 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
1184 }
1185
1186 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1187 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1188 IPCThreadState::self()->getCallingPid(), callingUid)) {
1189 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
1190 }
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001191 }
1192
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001193 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001194 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1195 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001196 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001197 }
1198
1199 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001200 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001201
Shawn Willden70c1a782018-07-11 15:13:20 -06001202 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001203 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001204 }
1205
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001206
1207 AuthorizationSet keyCharacteristics;
1208 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1209 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1210 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1211 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1212 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001213
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001214 std::promise<KeyStoreServiceReturnCode> resultPromise;
1215 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001216
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001217 dev->generateKey(
1218 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001219 [cb, dev, CAPTURE_MOVE(mutableParams)](
1220 Return<void> rc,
1221 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001222 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1223 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1224 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001225 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001226 return;
1227 }
1228 if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001229 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001230 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001231 return;
1232 }
1233 dev->attestKey(
1234 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001235 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001236 hidlKeyBlob](Return<void> rc,
1237 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1238 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001239 // schedule temp key for deletion
Janis Danisevskisa359c672019-03-14 17:15:06 -07001240 dev->deleteKey(std::move(hidlKeyBlob), [dev](Return<ErrorCode> rc) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001241 // log error but don't return an error
Janis Danisevskisa359c672019-03-14 17:15:06 -07001242 KS_HANDLE_HIDL_ERROR(dev, rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001243 });
1244 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001245 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001246 return;
1247 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001248 if (ret == ErrorCode::OK) {
1249 cb->onFinished(
1250 KeyStoreServiceReturnCode(ret),
1251 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1252 } else {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001253 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001254 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001255 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001256 });
1257 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001258
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001259 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001260}
1261
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001262Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001263 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001264 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001265 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1266 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001267}
1268
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001269Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001270 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001271 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1272 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1273 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001274 int32_t* _aidl_return) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001275
1276 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1277
1278 if (!checkBinderPermission(P_INSERT, callingUid)) {
1279 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1280 }
1281
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001282 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001283
1284 KeyStoreServiceReturnCode rc;
1285 Blob wrappingKeyBlob;
1286 Blob wrappingCharBlob;
1287 LockedKeyBlobEntry wrappingLockedEntry;
1288
1289 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1290 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
Branden Archerd166a882018-11-20 10:56:48 -08001291 if (!rc.isOk()) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001292 return AIDL_RETURN(rc);
1293 }
1294
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001295 String8 wrappedKeyName8(wrappedKeyAlias);
1296 auto wrappedLockedEntry =
1297 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1298 if (!wrappedLockedEntry) {
1299 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1300 }
1301
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001302 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1303 auto dev = mKeyStore->getDevice(securityLevel);
1304 if (!dev) {
1305 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1306 }
1307
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001308 dev->importWrappedKey(
1309 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1310 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001311 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1312 cb->onFinished(rc,
1313 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001314 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001315
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001316 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001317}
1318
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001319Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1320 const String16& promptText,
1321 const ::std::vector<uint8_t>& extraData,
1322 const String16& locale, int32_t uiOptionsAsFlags,
1323 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001324 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1325 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001326}
1327
1328Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1329 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001330 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001331}
1332
David Zeuthen1a492312018-02-26 11:00:30 -05001333Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001334 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001335}
1336
1337/**
1338 * Get the effective target uid for a binder operation that takes an
1339 * optional uid as the target.
1340 */
1341uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1342 if (targetUid == UID_SELF) {
1343 return IPCThreadState::self()->getCallingUid();
1344 }
1345 return static_cast<uid_t>(targetUid);
1346}
1347
1348/**
1349 * Check if the caller of the current binder method has the required
1350 * permission and if acting on other uids the grants to do so.
1351 */
1352bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1353 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1354 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001355 const char* ssid = IPCThreadState::self()->getCallingSid();
1356 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001357 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1358 return false;
1359 }
1360 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1361 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1362 return false;
1363 }
1364 return true;
1365}
1366
1367/**
1368 * Check if the caller of the current binder method has the required
1369 * permission and the target uid is the caller or the caller is system.
1370 */
1371bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1372 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1373 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001374 const char* ssid = IPCThreadState::self()->getCallingSid();
1375 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001376 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1377 return false;
1378 }
1379 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1380}
1381
1382/**
1383 * Check if the caller of the current binder method has the required
1384 * permission or the target of the operation is the caller's uid. This is
1385 * for operation where the permission is only for cross-uid activity and all
1386 * uids are allowed to act on their own (ie: clearing all entries for a
1387 * given uid).
1388 */
1389bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1390 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1391 if (getEffectiveUid(targetUid) == callingUid) {
1392 return true;
1393 } else {
1394 return checkBinderPermission(permission, targetUid);
1395 }
1396}
1397
1398/**
1399 * Helper method to check that the caller has the required permission as
1400 * well as the keystore is in the unlocked state if checkUnlocked is true.
1401 *
1402 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1403 * otherwise the state of keystore when not unlocked and checkUnlocked is
1404 * true.
1405 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001406KeyStoreServiceReturnCode
1407KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1408 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001409 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001410 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001411 }
1412 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1413 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001414 // All State values coincide with ResponseCodes
1415 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001416 }
1417
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001418 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001419}
1420
1421bool KeyStoreService::isKeystoreUnlocked(State state) {
1422 switch (state) {
1423 case ::STATE_NO_ERROR:
1424 return true;
1425 case ::STATE_UNINITIALIZED:
1426 case ::STATE_LOCKED:
1427 return false;
1428 }
1429 return false;
1430}
1431
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001432/**
Shawn Willden0329a822017-12-04 13:55:14 -07001433 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1434 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001435 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001436bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1437 for (size_t i = 0; i < params.size(); ++i) {
1438 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001439 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001440 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001441 return false;
1442 default:
1443 break;
1444 }
1445 }
1446 return true;
1447}
1448
Brian Young9a947d52018-02-23 18:03:14 +00001449Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
Janis Danisevskis1642dc02020-01-21 14:33:30 -08001450 int32_t* _aidl_return) {
Janis Danisevskis1642dc02020-01-21 14:33:30 -08001451 if (isShowing) {
1452 if (!checkBinderPermission(P_LOCK, UID_SELF)) {
1453 LOG(WARNING) << "onKeyguardVisibilityChanged called with isShowing == true but "
1454 "without LOCK permission";
1455 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1456 }
1457 } else {
1458 if (!checkBinderPermission(P_UNLOCK, UID_SELF)) {
1459 LOG(WARNING) << "onKeyguardVisibilityChanged called with isShowing == false but "
1460 "without UNLOCK permission";
1461 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1462 }
1463 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001464 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Janis Danisevskis1642dc02020-01-21 14:33:30 -08001465 return AIDL_RETURN(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001466}
1467
Shawn Willdene2a7b522017-04-11 09:27:40 -06001468} // namespace keystore