blob: 666b48a5a5a77459cbcda9ec8bee27571274a03a [file] [log] [blame]
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Janis Danisevskis011675d2016-09-01 11:41:29 +010017#define LOG_TAG "keystore"
18
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070019#include "key_store_service.h"
20
21#include <fcntl.h>
22#include <sys/stat.h>
23
Janis Danisevskis7612fd42016-09-01 11:50:02 +010024#include <algorithm>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070025#include <atomic>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070026#include <sstream>
27
Pavel Grafovff311b42018-01-24 20:34:37 +000028#include <android-base/scopeguard.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010029#include <binder/IInterface.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070030#include <binder/IPCThreadState.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010031#include <binder/IPermissionController.h>
32#include <binder/IServiceManager.h>
Brian Claire Young3133c452018-08-31 13:56:49 -070033#include <cutils/multiuser.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000034#include <log/log_event_list.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070035
36#include <private/android_filesystem_config.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000037#include <private/android_logger.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070038
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070039#include <android/hardware/confirmationui/1.0/IConfirmationUI.h>
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010040#include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
David Zeuthenab3e5652019-10-28 13:32:48 -040041#include <keymasterV4_0/keymaster_utils.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070042
43#include "defaults.h"
Max Bires33aac2d2018-02-23 10:53:10 -080044#include "key_proto_handler.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010045#include "keystore_keymaster_enforcement.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070046#include "keystore_utils.h"
David Zeuthenf2a28672020-01-30 16:20:07 -050047#include <keystore/keystore_attestation_id.h>
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010048#include <keystore/keystore_hidl_support.h>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070049#include <keystore/keystore_return_types.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070050
Janis Danisevskis8f737ad2017-11-21 12:30:15 -080051#include <hardware/hw_auth_token.h>
52
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010053namespace keystore {
Shawn Willdend5a24e62017-02-28 13:53:24 -070054
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010055using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070056
Shawn Willdene2a7b522017-04-11 09:27:40 -060057namespace {
58
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070059using ::android::binder::Status;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070060using android::security::keymaster::ExportResult;
61using android::security::keymaster::KeymasterArguments;
62using android::security::keymaster::KeymasterBlob;
63using android::security::keymaster::KeymasterCertificateChain;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070064using android::security::keymaster::operationFailed;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070065using android::security::keymaster::OperationResult;
David Zeuthenc6eb7cd2017-11-27 11:33:55 -050066using ConfirmationResponseCode = android::hardware::confirmationui::V1_0::ResponseCode;
Rob Barnesbb6cabd2018-10-04 17:10:37 -060067using ::android::security::keystore::IKeystoreOperationResultCallback;
68using ::android::security::keystore::IKeystoreResponseCallback;
69using ::android::security::keystore::KeystoreResponse;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070070
Shawn Willdene2a7b522017-04-11 09:27:40 -060071constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
72const char* kTimestampFilePath = "timestamp";
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070073
Shawn Willdene2a7b522017-04-11 09:27:40 -060074bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070075 return params.end() !=
76 std::find_if(params.begin(), params.end(),
77 [&](const KeyParameter& param) { return param.tag == tag; });
Shawn Willdend5a24e62017-02-28 13:53:24 -070078}
79
Branden Archer70080742018-11-20 11:04:11 -080080#define AIDL_RETURN(rc) (*_aidl_return = KeyStoreServiceReturnCode(rc).getErrorCode(), Status::ok())
Rob Barnesbb6cabd2018-10-04 17:10:37 -060081
Shawn Willdene2a7b522017-04-11 09:27:40 -060082std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
83 struct stat sbuf;
84 if (stat(kTimestampFilePath, &sbuf) == 0) {
Yi Konge353f252018-07-30 01:38:39 -070085 double diff_secs = difftime(time(nullptr), sbuf.st_ctime);
Shawn Willdene2a7b522017-04-11 09:27:40 -060086 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
87 }
88
89 if (errno != ENOENT) {
90 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
91 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
92 }
93
94 int fd = creat(kTimestampFilePath, 0600);
95 if (fd < 0) {
96 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
97 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
98 }
99
100 if (close(fd)) {
101 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
102 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
103 }
104
105 return {ResponseCode::NO_ERROR, true};
106}
107
Eran Messeri03fc4c82018-08-16 18:53:15 +0100108using ::android::security::KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200109
110KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
111 KeyStoreServiceReturnCode responseCode;
112 bool factoryResetSinceIdRotation;
113 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
114
115 if (!responseCode.isOk()) return responseCode;
116 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
117
118 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
119 if (!asn1_attestation_id_result.isOk()) {
120 ALOGE("failed to gather attestation_id");
Shawn Willden6f7d27c2019-09-11 22:51:46 -0600121 // Couldn't get attestation ID; just use an empty one rather than failing.
122 asn1_attestation_id_result = std::vector<uint8_t>();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200123 }
124 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
125
126 /*
Eran Messeri03fc4c82018-08-16 18:53:15 +0100127 * The attestation application ID must not be longer than
128 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, error out if gather_attestation_application_id
129 * returned such an invalid vector.
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200130 */
131 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Eran Messeri03fc4c82018-08-16 18:53:15 +0100132 ALOGE("BUG: Gathered Attestation Application ID is too big (%d)",
133 static_cast<int32_t>(asn1_attestation_id.size()));
134 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200135 }
136
137 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
138
139 return ResponseCode::NO_ERROR;
140}
141
Shawn Willdene2a7b522017-04-11 09:27:40 -0600142} // anonymous namespace
143
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700144Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700145 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700146 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
147 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700148 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700149 *aidl_return = mKeyStore->getState(userId);
150 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700151}
152
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700153Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700154 uid_t targetUid = getEffectiveUid(uid);
155 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700156 // see keystore/keystore.h
157 return Status::fromServiceSpecificError(
158 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700159 }
160
161 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700162 ResponseCode rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700163 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700164 Blob charBlob;
165 LockedKeyBlobEntry lockedEntry;
166
167 std::tie(rc, keyBlob, charBlob, lockedEntry) =
168 mKeyStore->getKeyForName(name8, targetUid, TYPE_GENERIC);
169 if (rc != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700170 *item = ::std::vector<uint8_t>();
171 // Return empty array if key is not found
172 // TODO: consider having returned value nullable or parse exception on the client.
173 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700174 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100175 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700176 // The static_cast here is needed to prevent a move, forcing a deep copy.
177 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
178 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700179}
180
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700181Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
182 int targetUid, int32_t flags, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700183 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700184 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700185 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100186 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800187 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700188 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700189 }
190
191 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700192 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), targetUid);
193
194 if (!lockedEntry) {
195 ALOGE("failed to grab lock on blob entry %u_%s", targetUid, name8.string());
196 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_ALREADY_EXISTS);
197 return Status::ok();
198 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700199
Yi Konge353f252018-07-30 01:38:39 -0700200 Blob keyBlob(&item[0], item.size(), nullptr, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700201 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
202
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700203 *aidl_return = static_cast<int32_t>(mKeyStore->put(lockedEntry, keyBlob, {}));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700204 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700205}
206
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700207Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700208 targetUid = getEffectiveUid(targetUid);
209 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700210 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
211 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700212 }
213 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000214 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700215 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
216 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700217 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
218 return Status::ok();
219 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700220
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700221 ResponseCode result = mKeyStore->del(lockedEntry);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400222
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700223 *aidl_return = static_cast<int32_t>(result);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700224 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700225}
226
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700227Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700228 targetUid = getEffectiveUid(targetUid);
229 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700230 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
231 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700232 }
233
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700234 LockedKeyBlobEntry lockedEntry =
235 mKeyStore->getLockedBlobEntryIfExists(String8(name).string(), targetUid);
236 *aidl_return =
237 static_cast<int32_t>(lockedEntry ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700238 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700239}
240
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700241Status KeyStoreService::list(const String16& prefix, int32_t targetUid,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700242 ::std::vector<::android::String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700243 targetUid = getEffectiveUid(targetUid);
244 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700245 return Status::fromServiceSpecificError(
246 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700247 }
248 const String8 prefix8(prefix);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700249 const std::string stdPrefix(prefix8.string());
250
251 ResponseCode rc;
252 std::list<LockedKeyBlobEntry> internal_matches;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800253 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700254
Janis Danisevskis265435f2018-11-16 14:10:46 -0800255 std::tie(rc, internal_matches) =
256 LockedKeyBlobEntry::list(userDirName, [&](uid_t uid, const std::string& alias) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700257 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end());
258 return uid == static_cast<uid_t>(targetUid) &&
259 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end())
260 .first == stdPrefix.end();
261 });
262
263 if (rc != ResponseCode::NO_ERROR) {
264 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700265 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700266
267 for (LockedKeyBlobEntry& entry : internal_matches) {
268 matches->push_back(String16(entry->alias().substr(prefix8.size()).c_str()));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700269 }
270 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700271}
272
Rob Barneseb7f79b2018-11-08 15:44:10 -0700273/*
274 * This method will return the uids of all auth bound keys for the calling user.
275 * This is intended to be used for alerting the user about which apps will be affected
276 * if the password/pin is removed. Only allowed to be called by system.
277 * The output is bound by the initial size of uidsOut to be compatible with Java.
278 */
Rob Barnes5d59e632018-12-07 16:09:02 -0700279Status KeyStoreService::listUidsOfAuthBoundKeys(std::vector<std::string>* uidsOut,
Rob Barneseb7f79b2018-11-08 15:44:10 -0700280 int32_t* aidl_return) {
281 const int32_t callingUid = IPCThreadState::self()->getCallingUid();
282 const int32_t userId = get_user_id(callingUid);
283 const int32_t appId = get_app_id(callingUid);
284 if (appId != AID_SYSTEM) {
285 ALOGE("Permission listUidsOfAuthBoundKeys denied for aid %d", appId);
286 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
287 return Status::ok();
288 }
289
290 const String8 prefix8("");
291 auto userState = mKeyStore->getUserStateDB().getUserState(userId);
292 const std::string userDirName = userState->getUserDirName();
293 auto encryptionKey = userState->getEncryptionKey();
294 auto state = userState->getState();
295 // unlock the user state
296 userState = {};
297
298 ResponseCode rc;
299 std::list<LockedKeyBlobEntry> internal_matches;
300 std::tie(rc, internal_matches) =
301 LockedKeyBlobEntry::list(userDirName, [&](uid_t, const std::string&) {
302 // Need to filter on auth bound state, so just return true.
303 return true;
304 });
305 if (rc != ResponseCode::NO_ERROR) {
306 ALOGE("Error listing blob entries for user %d", userId);
307 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
308 }
309
Rob Barneseb7f79b2018-11-08 15:44:10 -0700310 for (LockedKeyBlobEntry& entry : internal_matches) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700311 // Need to store uids as a list of strings because integer list output
312 // parameters is not supported in aidl-cpp.
313 std::string entryUid = std::to_string(entry->uid());
314 if (std::find(uidsOut->begin(), uidsOut->end(), entryUid) != uidsOut->end()) {
Rob Barneseb7f79b2018-11-08 15:44:10 -0700315 // uid already in list, skip
316 continue;
317 }
318
319 auto [rc, blob, charBlob] = entry.readBlobs(encryptionKey, state);
320 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::LOCKED) {
321 ALOGE("Error reading blob for key %s", entry->alias().c_str());
322 continue;
323 }
324
325 if (blob && blob.isEncrypted()) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700326 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700327 } else if (charBlob) {
328 auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
329 if (!success) {
330 ALOGE("Error reading blob characteristics for key %s", entry->alias().c_str());
331 continue;
332 }
333 if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
334 swEnforced.Contains(TAG_USER_SECURE_ID)) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700335 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700336 }
337 }
338 }
339 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
340 return Status::ok();
341}
342
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700343Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
344 int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700345 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700346 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
347 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700348 }
349
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700350 if (password.size() == 0) {
351 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
352 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700353 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
354 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700355 } else {
Pavel Grafovf9b53eb2019-02-06 17:16:21 +0000356 const String8 password8(password);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700357 switch (mKeyStore->getState(userId)) {
358 case ::STATE_UNINITIALIZED: {
359 // generate master key, encrypt with password, write to file,
360 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700361 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
362 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700363 }
364 case ::STATE_NO_ERROR: {
365 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700366 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
367 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700368 }
369 case ::STATE_LOCKED: {
370 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
371 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700372 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
373 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700374 }
375 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700376 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
377 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700378 }
379}
380
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700381Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700382 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700383 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
384 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700385 }
386
387 // Sanity check that the new user has an empty keystore.
388 if (!mKeyStore->isEmpty(userId)) {
389 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
390 }
391 // Unconditionally clear the keystore, just to be safe.
392 mKeyStore->resetUser(userId, false);
393 if (parentId != -1) {
394 // This profile must share the same master key password as the parent profile. Because the
395 // password of the parent profile is not known here, the best we can do is copy the parent's
396 // master key and master key file. This makes this profile use the same master key as the
397 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700398 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
399 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700400 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700401 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
402 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700403 }
404}
405
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700406Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700407 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700408 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
409 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700410 }
411
412 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700413 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
414 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700415}
416
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700417Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700418 if (!checkBinderPermission(P_LOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700419 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
420 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700421 }
422
423 State state = mKeyStore->getState(userId);
424 if (state != ::STATE_NO_ERROR) {
425 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700426 *aidl_return = static_cast<int32_t>(ResponseCode(state));
427 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700428 }
429
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700430 mKeyStore->getEnforcementPolicy().set_device_locked(true, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700431 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700432 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
433 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700434}
435
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700436Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700437 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700438 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
439 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700440 }
441
442 State state = mKeyStore->getState(userId);
443 if (state != ::STATE_LOCKED) {
444 switch (state) {
445 case ::STATE_NO_ERROR:
446 ALOGI("calling unlock when already unlocked, ignoring.");
447 break;
448 case ::STATE_UNINITIALIZED:
449 ALOGE("unlock called on uninitialized keystore.");
450 break;
451 default:
452 ALOGE("unlock called on keystore in unknown state: %d", state);
453 break;
454 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700455 *aidl_return = static_cast<int32_t>(ResponseCode(state));
456 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700457 }
458
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700459 mKeyStore->getEnforcementPolicy().set_device_locked(false, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700460 const String8 password8(pw);
461 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700462 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
463 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700464}
465
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700466Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700467 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700468 *aidl_return = static_cast<int32_t>(false);
469 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700470 }
471
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700472 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
473 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700474}
475
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700476Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
477 ::android::String16* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700478 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700479 auto result =
480 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100481 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700482 *aidl_return = String16();
483 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700484 }
485
486 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700487 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
488 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700489 *aidl_return = String16();
490 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700491 }
492
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700493 *aidl_return = String16(mKeyStore->addGrant(lockedEntry, granteeUid).c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700494 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700495}
496
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700497Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700498 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700499 KeyStoreServiceReturnCode result =
500 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100501 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800502 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700503 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700504 }
505
506 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700507
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700508 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
509 if (!lockedEntry) {
510 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700511 }
512
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700513 *aidl_return = mKeyStore->removeGrant(lockedEntry, granteeUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700514 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700515}
516
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700517Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700518 uid_t targetUid = getEffectiveUid(uid);
519 if (!checkBinderPermission(P_GET, targetUid)) {
520 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700521 *time = -1L;
522 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700523 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700524 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700525
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700526 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
527 if (!lockedEntry) {
528 ALOGW("could not access key with alias %s for getmtime", name8.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700529 *time = -1L;
530 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700531 }
532
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700533 std::string filename = lockedEntry->getKeyBlobPath();
534
535 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700536 if (fd < 0) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700537 ALOGW("could not open %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700538 *time = -1L;
539 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700540 }
541
542 struct stat s;
543 int ret = fstat(fd, &s);
544 close(fd);
545 if (ret == -1) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700546 ALOGW("could not stat %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700547 *time = -1L;
548 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700549 }
550
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700551 *time = static_cast<int64_t>(s.st_mtime);
552 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700553}
554
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700555Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
556 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
557 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700558}
559
Janis Danisevskis265435f2018-11-16 14:10:46 -0800560Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700561 uid_t targetUid = getEffectiveUid(targetUid64);
562 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800563 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700564 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000565 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700566
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700567 mKeyStore->removeAllGrantsToUid(targetUid);
568
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700569 ResponseCode rc;
570 std::list<LockedKeyBlobEntry> entries;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800571 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700572
573 // list has a fence making sure no workers are modifying blob files before iterating the
574 // data base. All returned entries are locked.
575 std::tie(rc, entries) = LockedKeyBlobEntry::list(
Janis Danisevskis265435f2018-11-16 14:10:46 -0800576 userDirName, [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700577
578 if (rc != ResponseCode::NO_ERROR) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800579 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700580 }
581
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700582 for (LockedKeyBlobEntry& lockedEntry : entries) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100583 if (get_app_id(targetUid) == AID_SYSTEM) {
584 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700585 Blob charBlob;
586 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
587 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100588 // Do not clear keys critical to device encryption under system uid.
589 continue;
590 }
591 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700592 mKeyStore->del(lockedEntry);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700593 }
Janis Danisevskis265435f2018-11-16 14:10:46 -0800594 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700595}
596
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600597Status KeyStoreService::addRngEntropy(
598 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
599 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
Janis Danisevskisc1460142017-12-18 16:48:46 -0800600 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
601 if (!device) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600602 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800603 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700604
Janis Danisevskisa359c672019-03-14 17:15:06 -0700605 device->addRngEntropy(entropy, [device, cb](Return<ErrorCode> rc) {
606 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device, rc)));
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600607 });
608
609 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700610}
611
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600612Status KeyStoreService::generateKey(
613 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
614 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
615 int uid, int flags, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700616 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000617 auto logOnScopeExit = android::base::make_scope_guard([&] {
618 if (__android_log_security()) {
619 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600620 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000621 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
622 }
623 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100624 KeyStoreServiceReturnCode rc =
625 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
626 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600627 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700628 }
Rubin Xu67899de2017-04-21 19:15:13 +0100629 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
630 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600631 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100632 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700633
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700634 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Max Bires36ae17f2019-11-12 21:34:24 +0000635 if (!checkBinderPermission(P_GEN_UNIQUE_ID)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600636 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700637 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600638 }
639
Janis Danisevskisc1460142017-12-18 16:48:46 -0800640 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
641 auto dev = mKeyStore->getDevice(securityLevel);
642 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600643 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800644 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400645
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100646 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700647 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
648 if (!lockedEntry) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600649 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100650 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400651
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700652 logOnScopeExit.Disable();
653
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600654 dev->generateKey(
655 std::move(lockedEntry), params.getParameters(), entropy, flags,
656 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
657 if (__android_log_security()) {
658 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
659 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
660 }
661 cb->onFinished(rc,
662 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
663 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700664
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600665 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700666}
667
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700668Status KeyStoreService::getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600669 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700670 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
Janis Danisevskis64ec1fe2018-02-26 16:47:21 -0800671 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600672 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700673
674 uid_t targetUid = getEffectiveUid(uid);
675 uid_t callingUid = IPCThreadState::self()->getCallingUid();
676 if (!is_granted_to(callingUid, targetUid)) {
677 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
678 targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600679 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700680 }
681
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700682 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700683
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700684 ResponseCode rc;
685 Blob keyBlob;
686 Blob charBlob;
687 LockedKeyBlobEntry lockedEntry;
Janis Danisevskisd714a672017-09-01 14:31:36 -0700688
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700689 std::tie(rc, keyBlob, charBlob, lockedEntry) =
690 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
691
692 if (rc != ResponseCode::NO_ERROR) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600693 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700694 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100695
Janis Danisevskisc1460142017-12-18 16:48:46 -0800696 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700697 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600698 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100699 }
700
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700701 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
702 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
703 // from keymaster. It may also upgrade the key blob.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700704 dev->getKeyCharacteristics(
705 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
706 std::move(charBlob),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600707 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
708 cb->onFinished(rc,
709 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700710 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100711
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600712 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700713}
714
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600715Status KeyStoreService::importKey(
716 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
717 const String16& name, const KeymasterArguments& params, int32_t format,
718 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700719 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000720 auto logOnScopeExit = android::base::make_scope_guard([&] {
721 if (__android_log_security()) {
722 android_log_event_list(SEC_TAG_KEY_IMPORTED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600723 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000724 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
725 }
726 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100727 KeyStoreServiceReturnCode rc =
728 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
729 if (!rc.isOk()) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700730 LOG(ERROR) << "permissission denied";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600731 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700732 }
Rubin Xu67899de2017-04-21 19:15:13 +0100733 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
734 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600735 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100736 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700737
Janis Danisevskisc1460142017-12-18 16:48:46 -0800738 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
739 auto dev = mKeyStore->getDevice(securityLevel);
740 if (!dev) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700741 LOG(ERROR) << "importKey - cound not get keymaster device";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600742 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800743 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700744
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700745 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700746 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
747 if (!lockedEntry) {
748 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
749 << " already exists.";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600750 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400751 }
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700752
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700753 logOnScopeExit.Disable();
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700754
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600755 dev->importKey(
756 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
757 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
758 if (__android_log_security()) {
759 android_log_event_list(SEC_TAG_KEY_IMPORTED)
760 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
761 }
762 cb->onFinished(rc,
763 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
764 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400765
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600766 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700767}
768
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600769Status KeyStoreService::exportKey(
770 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
771 const String16& name, int32_t format,
772 const ::android::security::keymaster::KeymasterBlob& clientId,
773 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
774 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700775
776 uid_t targetUid = getEffectiveUid(uid);
777 uid_t callingUid = IPCThreadState::self()->getCallingUid();
778 if (!is_granted_to(callingUid, targetUid)) {
779 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600780 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700781 }
782
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700783 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700784
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700785 KeyStoreServiceReturnCode rc;
786 Blob keyBlob;
787 Blob charBlob;
788 LockedKeyBlobEntry lockedEntry;
789
790 std::tie(rc, keyBlob, charBlob, lockedEntry) =
791 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskis3cf85322018-11-19 13:37:49 -0800792 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600793 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700794 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100795
Janis Danisevskisc1460142017-12-18 16:48:46 -0800796 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100797
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700798 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600799 std::move(keyBlob), std::move(charBlob),
800 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
Ji Wang2c142312016-10-14 17:21:10 +0800801
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600802 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700803}
804
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600805Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
806 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700807 bool pruneable, const KeymasterArguments& params,
808 const ::std::vector<uint8_t>& entropy, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600809 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700810 uid_t callingUid = IPCThreadState::self()->getCallingUid();
811 uid_t targetUid = getEffectiveUid(uid);
812 if (!is_granted_to(callingUid, targetUid)) {
813 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600814 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700815 }
816 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
817 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600818 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700819 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700820 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600821 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700822 }
Shawn Willden0329a822017-12-04 13:55:14 -0700823
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700824 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700825 Blob keyBlob;
826 Blob charBlob;
827 LockedKeyBlobEntry lockedEntry;
828 ResponseCode rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100829
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700830 std::tie(rc, keyBlob, charBlob, lockedEntry) =
831 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
832
833 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600834 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700835 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600836 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700837
Janis Danisevskisc1460142017-12-18 16:48:46 -0800838 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700839 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100840
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700841 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
842 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600843 [this, cb, dev](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700844 if (result_.resultCode.isOk() ||
845 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700846 mKeyStore->addOperationDevice(result_.token, dev);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700847 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600848 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700849 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400850
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600851 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700852}
853
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600854Status KeyStoreService::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
855 const ::android::sp<::android::IBinder>& token,
856 const ::android::security::keymaster::KeymasterArguments& params,
857 const ::std::vector<uint8_t>& input, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700858 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600859 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700860 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700861
Janis Danisevskisbec89992019-08-14 13:42:19 -0700862 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700863 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600864 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700865 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700866
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600867 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700868 if (!result_.resultCode.isOk()) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700869 mKeyStore->removeOperationDevice(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100870 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600871 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700872 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100873
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600874 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700875}
876
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600877Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
878 const ::android::sp<::android::IBinder>& token,
879 const ::android::security::keymaster::KeymasterArguments& params,
Rob Barnes3af223f2019-11-14 14:50:30 -0700880 const ::std::vector<uint8_t>& input,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700881 const ::std::vector<uint8_t>& signature,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600882 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700883 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600884 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700885 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700886
Janis Danisevskisbec89992019-08-14 13:42:19 -0700887 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700888 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600889 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700890 }
891
Rob Barnes3af223f2019-11-14 14:50:30 -0700892 dev->finish(token, params.getParameters(), input, signature, entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600893 [this, cb, token](OperationResult result_) {
Janis Danisevskis8c4c1d62019-10-04 11:01:54 -0700894 mKeyStore->removeOperationDevice(token);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600895 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700896 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700897
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600898 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700899}
900
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600901Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
902 const ::android::sp<::android::IBinder>& token,
903 int32_t* _aidl_return) {
Janis Danisevskisbec89992019-08-14 13:42:19 -0700904 auto dev = mKeyStore->getOperationDevice(token);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700905 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600906 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700907 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100908
Janis Danisevskisbec89992019-08-14 13:42:19 -0700909 dev->abort(token, [this, cb, token](KeyStoreServiceReturnCode rc) {
910 mKeyStore->removeOperationDevice(token);
911 cb->onFinished(rc);
912 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700913
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600914 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700915}
916
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700917Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000918 int32_t* aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700919
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000920 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
921 // receive a HardwareAuthToken, rather than an opaque byte array.
922
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700923 if (!checkBinderPermission(P_ADD_AUTH)) {
924 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700925 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
926 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700927 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700928 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
Branden Archer70080742018-11-20 11:04:11 -0800929 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700930 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000931 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100932
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000933 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700934 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000935 if (authToken.version != 0) {
Branden Archer70080742018-11-20 11:04:11 -0800936 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700937 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000938 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100939
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700940 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
941 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700942 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
943 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700944}
945
David Zeuthenab3e5652019-10-28 13:32:48 -0400946Status KeyStoreService::getAuthTokenForCredstore(int64_t challenge, int64_t secureUserId,
947 int32_t authTokenMaxAgeMillis,
948 std::vector<uint8_t>* _aidl_return) {
949 uid_t callingUid = IPCThreadState::self()->getCallingUid();
950 if (callingUid != AID_CREDSTORE) {
951 return Status::fromServiceSpecificError(static_cast<int32_t>(0));
952 }
953
954 auto [err, authToken] = mKeyStore->getAuthTokenTable().FindAuthorizationForCredstore(
955 challenge, secureUserId, authTokenMaxAgeMillis);
956 std::vector<uint8_t> ret;
957 if (err == AuthTokenTable::OK) {
958 ret = android::hardware::keymaster::V4_0::support::authToken2HidlVec(authToken);
959 }
960 *_aidl_return = ret;
961 return Status::ok();
962}
963
Eran Messerid9f8ae52018-10-24 13:54:00 +0100964bool isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -0700965 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700966 for (size_t i = 0; i < paramsVec.size(); ++i) {
967 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -0600968 case Tag::ATTESTATION_ID_BRAND:
969 case Tag::ATTESTATION_ID_DEVICE:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600970 case Tag::ATTESTATION_ID_MANUFACTURER:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600971 case Tag::ATTESTATION_ID_MODEL:
972 case Tag::ATTESTATION_ID_PRODUCT:
Rubin Xu1a203e32018-05-08 14:25:21 +0100973 case Tag::ATTESTATION_ID_IMEI:
974 case Tag::ATTESTATION_ID_MEID:
975 case Tag::ATTESTATION_ID_SERIAL:
Eran Messerid9f8ae52018-10-24 13:54:00 +0100976 return true;
Rubin Xu1a203e32018-05-08 14:25:21 +0100977 default:
978 continue;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100979 }
980 }
Eran Messerid9f8ae52018-10-24 13:54:00 +0100981 return false;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100982}
983
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600984Status KeyStoreService::attestKey(
985 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
986 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700987 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
988 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600989 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -0700990 }
991
Eran Messerie2c34152017-12-21 21:01:22 +0000992 uid_t callingUid = IPCThreadState::self()->getCallingUid();
993
Eran Messerid9f8ae52018-10-24 13:54:00 +0100994 if (isDeviceIdAttestationRequested(params) && (get_app_id(callingUid) != AID_SYSTEM)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600995 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100996 }
997
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700998 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200999 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1000 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001001 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001002 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001003
Shawn Willden50eb1b22016-01-21 12:41:23 -07001004 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001005 Blob keyBlob;
1006 Blob charBlob;
1007 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001008
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001009 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1010 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1011
Janis Danisevskis9dff56c2019-07-10 14:08:06 -07001012 if (!rc.isOk()) {
1013 return AIDL_RETURN(rc);
1014 }
1015
Janis Danisevskisc1460142017-12-18 16:48:46 -08001016 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001017 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001018 dev->attestKey(
1019 std::move(hidlKey), mutableParams.hidl_data(),
Janis Danisevskisa359c672019-03-14 17:15:06 -07001020 [dev, cb](Return<void> rc,
1021 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001022 auto& [ret, certChain] = hidlResult;
1023 if (!rc.isOk()) {
1024 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1025 } else if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001026 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001027 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1028 } else {
1029 cb->onFinished(KeyStoreServiceReturnCode(ret),
1030 KeymasterCertificateChain(std::move(certChain)));
1031 }
1032 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001033
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001034 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001035}
1036
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001037// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1038// It should never be redefined by a build system though.
1039#ifndef CAPTURE_MOVE
1040#define CAPTURE_MOVE(x) x = std::move(x)
1041#endif
1042
1043Status KeyStoreService::attestDeviceIds(
1044 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1045 const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001046 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001047
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001048 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001049 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001050 }
1051
1052 if (!isDeviceIdAttestationRequested(params)) {
1053 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001054 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001055 }
1056
1057 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1058 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
Yi Konge353f252018-07-30 01:38:39 -07001059 if (binder == nullptr) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001060 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001061 }
1062 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1063 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1064 IPCThreadState::self()->getCallingPid(), callingUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001065 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001066 }
1067
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001068 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001069 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1070 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001071 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001072 }
1073
1074 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001075 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001076
Shawn Willden70c1a782018-07-11 15:13:20 -06001077 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001078 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001079 }
1080
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001081
1082 AuthorizationSet keyCharacteristics;
1083 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1084 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1085 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1086 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1087 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001088
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001089 std::promise<KeyStoreServiceReturnCode> resultPromise;
1090 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001091
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001092 dev->generateKey(
1093 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001094 [cb, dev, CAPTURE_MOVE(mutableParams)](
1095 Return<void> rc,
1096 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001097 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1098 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1099 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001100 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001101 return;
1102 }
1103 if (ret != ErrorCode::OK) {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001104 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001105 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001106 return;
1107 }
1108 dev->attestKey(
1109 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001110 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001111 hidlKeyBlob](Return<void> rc,
1112 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1113 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001114 // schedule temp key for deletion
Janis Danisevskisa359c672019-03-14 17:15:06 -07001115 dev->deleteKey(std::move(hidlKeyBlob), [dev](Return<ErrorCode> rc) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001116 // log error but don't return an error
Janis Danisevskisa359c672019-03-14 17:15:06 -07001117 KS_HANDLE_HIDL_ERROR(dev, rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001118 });
1119 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001120 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001121 return;
1122 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001123 if (ret == ErrorCode::OK) {
1124 cb->onFinished(
1125 KeyStoreServiceReturnCode(ret),
1126 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1127 } else {
Janis Danisevskisa359c672019-03-14 17:15:06 -07001128 dev->logIfKeymasterVendorError(ret);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001129 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001130 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001131 });
1132 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001133
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001134 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001135}
1136
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001137Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001138 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001139 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001140 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1141 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001142}
1143
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001144Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001145 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001146 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1147 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1148 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001149 int32_t* _aidl_return) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001150
1151 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1152
1153 if (!checkBinderPermission(P_INSERT, callingUid)) {
1154 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1155 }
1156
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001157 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001158
1159 KeyStoreServiceReturnCode rc;
1160 Blob wrappingKeyBlob;
1161 Blob wrappingCharBlob;
1162 LockedKeyBlobEntry wrappingLockedEntry;
1163
1164 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1165 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
Branden Archerd166a882018-11-20 10:56:48 -08001166 if (!rc.isOk()) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001167 return AIDL_RETURN(rc);
1168 }
1169
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001170 String8 wrappedKeyName8(wrappedKeyAlias);
1171 auto wrappedLockedEntry =
1172 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1173 if (!wrappedLockedEntry) {
1174 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1175 }
1176
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001177 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1178 auto dev = mKeyStore->getDevice(securityLevel);
1179 if (!dev) {
1180 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1181 }
1182
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001183 dev->importWrappedKey(
1184 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1185 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001186 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1187 cb->onFinished(rc,
1188 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001189 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001190
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001191 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001192}
1193
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001194Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1195 const String16& promptText,
1196 const ::std::vector<uint8_t>& extraData,
1197 const String16& locale, int32_t uiOptionsAsFlags,
1198 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001199 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1200 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001201}
1202
1203Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1204 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001205 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001206}
1207
David Zeuthen1a492312018-02-26 11:00:30 -05001208Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001209 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001210}
1211
1212/**
1213 * Get the effective target uid for a binder operation that takes an
1214 * optional uid as the target.
1215 */
1216uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1217 if (targetUid == UID_SELF) {
1218 return IPCThreadState::self()->getCallingUid();
1219 }
1220 return static_cast<uid_t>(targetUid);
1221}
1222
1223/**
1224 * Check if the caller of the current binder method has the required
1225 * permission and if acting on other uids the grants to do so.
1226 */
1227bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1228 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1229 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001230 const char* ssid = IPCThreadState::self()->getCallingSid();
1231 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001232 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1233 return false;
1234 }
1235 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1236 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1237 return false;
1238 }
1239 return true;
1240}
1241
1242/**
1243 * Check if the caller of the current binder method has the required
1244 * permission and the target uid is the caller or the caller is system.
1245 */
1246bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1247 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1248 pid_t spid = IPCThreadState::self()->getCallingPid();
Steven Moreland23115b02019-01-10 16:20:20 -08001249 const char* ssid = IPCThreadState::self()->getCallingSid();
1250 if (!has_permission(callingUid, permission, spid, ssid)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001251 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1252 return false;
1253 }
1254 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1255}
1256
1257/**
1258 * Check if the caller of the current binder method has the required
1259 * permission or the target of the operation is the caller's uid. This is
1260 * for operation where the permission is only for cross-uid activity and all
1261 * uids are allowed to act on their own (ie: clearing all entries for a
1262 * given uid).
1263 */
1264bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1265 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1266 if (getEffectiveUid(targetUid) == callingUid) {
1267 return true;
1268 } else {
1269 return checkBinderPermission(permission, targetUid);
1270 }
1271}
1272
1273/**
1274 * Helper method to check that the caller has the required permission as
1275 * well as the keystore is in the unlocked state if checkUnlocked is true.
1276 *
1277 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1278 * otherwise the state of keystore when not unlocked and checkUnlocked is
1279 * true.
1280 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001281KeyStoreServiceReturnCode
1282KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1283 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001284 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001285 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001286 }
1287 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1288 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001289 // All State values coincide with ResponseCodes
1290 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001291 }
1292
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001293 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001294}
1295
1296bool KeyStoreService::isKeystoreUnlocked(State state) {
1297 switch (state) {
1298 case ::STATE_NO_ERROR:
1299 return true;
1300 case ::STATE_UNINITIALIZED:
1301 case ::STATE_LOCKED:
1302 return false;
1303 }
1304 return false;
1305}
1306
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001307/**
Shawn Willden0329a822017-12-04 13:55:14 -07001308 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1309 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001310 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001311bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1312 for (size_t i = 0; i < params.size(); ++i) {
1313 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001314 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001315 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001316 return false;
1317 default:
1318 break;
1319 }
1320 }
1321 return true;
1322}
1323
Brian Young9a947d52018-02-23 18:03:14 +00001324Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
1325 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001326 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Brian Young9a947d52018-02-23 18:03:14 +00001327 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001328
1329 return Status::ok();
1330}
1331
Shawn Willdene2a7b522017-04-11 09:27:40 -06001332} // namespace keystore