blob: a7fcd38ddea74db558eaa53fc556b569cb723e3b [file] [log] [blame]
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Janis Danisevskis011675d2016-09-01 11:41:29 +010017#define LOG_TAG "keystore"
18
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070019#include "key_store_service.h"
20
21#include <fcntl.h>
22#include <sys/stat.h>
23
Janis Danisevskis7612fd42016-09-01 11:50:02 +010024#include <algorithm>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070025#include <atomic>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070026#include <sstream>
27
Pavel Grafovff311b42018-01-24 20:34:37 +000028#include <android-base/scopeguard.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010029#include <binder/IInterface.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070030#include <binder/IPCThreadState.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010031#include <binder/IPermissionController.h>
32#include <binder/IServiceManager.h>
Brian Claire Young3133c452018-08-31 13:56:49 -070033#include <cutils/multiuser.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000034#include <log/log_event_list.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070035
36#include <private/android_filesystem_config.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000037#include <private/android_logger.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070038
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070039#include <android/hardware/confirmationui/1.0/IConfirmationUI.h>
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010040#include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070041
42#include "defaults.h"
Max Bires33aac2d2018-02-23 10:53:10 -080043#include "key_proto_handler.h"
Janis Danisevskis18f27ad2016-06-01 13:57:40 -070044#include "keystore_attestation_id.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010045#include "keystore_keymaster_enforcement.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070046#include "keystore_utils.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010047#include <keystore/keystore_hidl_support.h>
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070048#include <keystore/keystore_return_types.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070049
Janis Danisevskis8f737ad2017-11-21 12:30:15 -080050#include <hardware/hw_auth_token.h>
51
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010052namespace keystore {
Shawn Willdend5a24e62017-02-28 13:53:24 -070053
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010054using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070055
Shawn Willdene2a7b522017-04-11 09:27:40 -060056namespace {
57
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070058using ::android::binder::Status;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070059using android::security::keymaster::ExportResult;
60using android::security::keymaster::KeymasterArguments;
61using android::security::keymaster::KeymasterBlob;
62using android::security::keymaster::KeymasterCertificateChain;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070063using android::security::keymaster::operationFailed;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070064using android::security::keymaster::OperationResult;
David Zeuthenc6eb7cd2017-11-27 11:33:55 -050065using ConfirmationResponseCode = android::hardware::confirmationui::V1_0::ResponseCode;
Rob Barnesbb6cabd2018-10-04 17:10:37 -060066using ::android::security::keystore::IKeystoreOperationResultCallback;
67using ::android::security::keystore::IKeystoreResponseCallback;
68using ::android::security::keystore::KeystoreResponse;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070069
Shawn Willdene2a7b522017-04-11 09:27:40 -060070constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
71const char* kTimestampFilePath = "timestamp";
Rubin Xu1a203e32018-05-08 14:25:21 +010072const int ID_ATTESTATION_REQUEST_GENERIC_INFO = 1 << 0;
73const int ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID = 1 << 1;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070074
75struct BIGNUM_Delete {
76 void operator()(BIGNUM* p) const { BN_free(p); }
77};
Janis Danisevskisccfff102017-05-01 11:02:51 -070078typedef std::unique_ptr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070079
Shawn Willdene2a7b522017-04-11 09:27:40 -060080bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070081 return params.end() !=
82 std::find_if(params.begin(), params.end(),
83 [&](const KeyParameter& param) { return param.tag == tag; });
Shawn Willdend5a24e62017-02-28 13:53:24 -070084}
85
Branden Archer70080742018-11-20 11:04:11 -080086#define AIDL_RETURN(rc) (*_aidl_return = KeyStoreServiceReturnCode(rc).getErrorCode(), Status::ok())
Rob Barnesbb6cabd2018-10-04 17:10:37 -060087
Shawn Willdene2a7b522017-04-11 09:27:40 -060088std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
89 struct stat sbuf;
90 if (stat(kTimestampFilePath, &sbuf) == 0) {
Yi Konge353f252018-07-30 01:38:39 -070091 double diff_secs = difftime(time(nullptr), sbuf.st_ctime);
Shawn Willdene2a7b522017-04-11 09:27:40 -060092 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
93 }
94
95 if (errno != ENOENT) {
96 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
97 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
98 }
99
100 int fd = creat(kTimestampFilePath, 0600);
101 if (fd < 0) {
102 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
103 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
104 }
105
106 if (close(fd)) {
107 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
108 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
109 }
110
111 return {ResponseCode::NO_ERROR, true};
112}
113
Eran Messeri03fc4c82018-08-16 18:53:15 +0100114using ::android::security::KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200115
116KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
117 KeyStoreServiceReturnCode responseCode;
118 bool factoryResetSinceIdRotation;
119 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
120
121 if (!responseCode.isOk()) return responseCode;
122 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
123
124 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
125 if (!asn1_attestation_id_result.isOk()) {
126 ALOGE("failed to gather attestation_id");
127 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
128 }
129 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
130
131 /*
Eran Messeri03fc4c82018-08-16 18:53:15 +0100132 * The attestation application ID must not be longer than
133 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, error out if gather_attestation_application_id
134 * returned such an invalid vector.
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200135 */
136 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Eran Messeri03fc4c82018-08-16 18:53:15 +0100137 ALOGE("BUG: Gathered Attestation Application ID is too big (%d)",
138 static_cast<int32_t>(asn1_attestation_id.size()));
139 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200140 }
141
142 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
143
144 return ResponseCode::NO_ERROR;
145}
146
Shawn Willdene2a7b522017-04-11 09:27:40 -0600147} // anonymous namespace
148
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700149Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700150 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700151 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
152 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700153 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700154 *aidl_return = mKeyStore->getState(userId);
155 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700156}
157
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700158Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700159 uid_t targetUid = getEffectiveUid(uid);
160 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700161 // see keystore/keystore.h
162 return Status::fromServiceSpecificError(
163 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700164 }
165
166 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700167 ResponseCode rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700168 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700169 Blob charBlob;
170 LockedKeyBlobEntry lockedEntry;
171
172 std::tie(rc, keyBlob, charBlob, lockedEntry) =
173 mKeyStore->getKeyForName(name8, targetUid, TYPE_GENERIC);
174 if (rc != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700175 *item = ::std::vector<uint8_t>();
176 // Return empty array if key is not found
177 // TODO: consider having returned value nullable or parse exception on the client.
178 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700179 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100180 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700181 // The static_cast here is needed to prevent a move, forcing a deep copy.
182 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
183 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700184}
185
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700186Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
187 int targetUid, int32_t flags, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700188 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700189 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700190 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100191 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800192 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700193 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700194 }
195
196 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700197 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), targetUid);
198
199 if (!lockedEntry) {
200 ALOGE("failed to grab lock on blob entry %u_%s", targetUid, name8.string());
201 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_ALREADY_EXISTS);
202 return Status::ok();
203 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700204
Yi Konge353f252018-07-30 01:38:39 -0700205 Blob keyBlob(&item[0], item.size(), nullptr, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700206 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
207
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700208 *aidl_return = static_cast<int32_t>(mKeyStore->put(lockedEntry, keyBlob, {}));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700209 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700210}
211
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700212Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700213 targetUid = getEffectiveUid(targetUid);
214 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700215 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
216 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700217 }
218 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000219 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700220 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
221 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700222 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
223 return Status::ok();
224 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700225
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700226 ResponseCode result = mKeyStore->del(lockedEntry);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400227
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700228 *aidl_return = static_cast<int32_t>(result);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700229 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700230}
231
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700232Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700233 targetUid = getEffectiveUid(targetUid);
234 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700235 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
236 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700237 }
238
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700239 LockedKeyBlobEntry lockedEntry =
240 mKeyStore->getLockedBlobEntryIfExists(String8(name).string(), targetUid);
241 *aidl_return =
242 static_cast<int32_t>(lockedEntry ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700243 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700244}
245
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700246Status KeyStoreService::list(const String16& prefix, int32_t targetUid,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700247 ::std::vector<::android::String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700248 targetUid = getEffectiveUid(targetUid);
249 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700250 return Status::fromServiceSpecificError(
251 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700252 }
253 const String8 prefix8(prefix);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700254 const std::string stdPrefix(prefix8.string());
255
256 ResponseCode rc;
257 std::list<LockedKeyBlobEntry> internal_matches;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800258 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700259
Janis Danisevskis265435f2018-11-16 14:10:46 -0800260 std::tie(rc, internal_matches) =
261 LockedKeyBlobEntry::list(userDirName, [&](uid_t uid, const std::string& alias) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700262 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end());
263 return uid == static_cast<uid_t>(targetUid) &&
264 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end())
265 .first == stdPrefix.end();
266 });
267
268 if (rc != ResponseCode::NO_ERROR) {
269 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700270 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700271
272 for (LockedKeyBlobEntry& entry : internal_matches) {
273 matches->push_back(String16(entry->alias().substr(prefix8.size()).c_str()));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700274 }
275 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700276}
277
Rob Barneseb7f79b2018-11-08 15:44:10 -0700278/*
279 * This method will return the uids of all auth bound keys for the calling user.
280 * This is intended to be used for alerting the user about which apps will be affected
281 * if the password/pin is removed. Only allowed to be called by system.
282 * The output is bound by the initial size of uidsOut to be compatible with Java.
283 */
Rob Barnes5d59e632018-12-07 16:09:02 -0700284Status KeyStoreService::listUidsOfAuthBoundKeys(std::vector<std::string>* uidsOut,
Rob Barneseb7f79b2018-11-08 15:44:10 -0700285 int32_t* aidl_return) {
286 const int32_t callingUid = IPCThreadState::self()->getCallingUid();
287 const int32_t userId = get_user_id(callingUid);
288 const int32_t appId = get_app_id(callingUid);
289 if (appId != AID_SYSTEM) {
290 ALOGE("Permission listUidsOfAuthBoundKeys denied for aid %d", appId);
291 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
292 return Status::ok();
293 }
294
295 const String8 prefix8("");
296 auto userState = mKeyStore->getUserStateDB().getUserState(userId);
297 const std::string userDirName = userState->getUserDirName();
298 auto encryptionKey = userState->getEncryptionKey();
299 auto state = userState->getState();
300 // unlock the user state
301 userState = {};
302
303 ResponseCode rc;
304 std::list<LockedKeyBlobEntry> internal_matches;
305 std::tie(rc, internal_matches) =
306 LockedKeyBlobEntry::list(userDirName, [&](uid_t, const std::string&) {
307 // Need to filter on auth bound state, so just return true.
308 return true;
309 });
310 if (rc != ResponseCode::NO_ERROR) {
311 ALOGE("Error listing blob entries for user %d", userId);
312 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
313 }
314
Rob Barneseb7f79b2018-11-08 15:44:10 -0700315 for (LockedKeyBlobEntry& entry : internal_matches) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700316 // Need to store uids as a list of strings because integer list output
317 // parameters is not supported in aidl-cpp.
318 std::string entryUid = std::to_string(entry->uid());
319 if (std::find(uidsOut->begin(), uidsOut->end(), entryUid) != uidsOut->end()) {
Rob Barneseb7f79b2018-11-08 15:44:10 -0700320 // uid already in list, skip
321 continue;
322 }
323
324 auto [rc, blob, charBlob] = entry.readBlobs(encryptionKey, state);
325 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::LOCKED) {
326 ALOGE("Error reading blob for key %s", entry->alias().c_str());
327 continue;
328 }
329
330 if (blob && blob.isEncrypted()) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700331 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700332 } else if (charBlob) {
333 auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
334 if (!success) {
335 ALOGE("Error reading blob characteristics for key %s", entry->alias().c_str());
336 continue;
337 }
338 if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
339 swEnforced.Contains(TAG_USER_SECURE_ID)) {
Rob Barnes5d59e632018-12-07 16:09:02 -0700340 uidsOut->push_back(entryUid);
Rob Barneseb7f79b2018-11-08 15:44:10 -0700341 }
342 }
343 }
344 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
345 return Status::ok();
346}
347
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700348Status KeyStoreService::reset(int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700349 if (!checkBinderPermission(P_RESET)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700350 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
351 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700352 }
353
354 uid_t callingUid = IPCThreadState::self()->getCallingUid();
355 mKeyStore->resetUser(get_user_id(callingUid), false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700356 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
357 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700358}
359
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700360Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
361 int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700362 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700363 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
364 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700365 }
366
367 const String8 password8(password);
368 // Flush the auth token table to prevent stale tokens from sticking
369 // around.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700370 mKeyStore->getAuthTokenTable().Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700371
372 if (password.size() == 0) {
373 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
374 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700375 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
376 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700377 } else {
378 switch (mKeyStore->getState(userId)) {
379 case ::STATE_UNINITIALIZED: {
380 // generate master key, encrypt with password, write to file,
381 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700382 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
383 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700384 }
385 case ::STATE_NO_ERROR: {
386 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700387 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
388 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700389 }
390 case ::STATE_LOCKED: {
391 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
392 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700393 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
394 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700395 }
396 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700397 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
398 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700399 }
400}
401
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700402Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700403 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700404 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
405 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700406 }
407
408 // Sanity check that the new user has an empty keystore.
409 if (!mKeyStore->isEmpty(userId)) {
410 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
411 }
412 // Unconditionally clear the keystore, just to be safe.
413 mKeyStore->resetUser(userId, false);
414 if (parentId != -1) {
415 // This profile must share the same master key password as the parent profile. Because the
416 // password of the parent profile is not known here, the best we can do is copy the parent's
417 // master key and master key file. This makes this profile use the same master key as the
418 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700419 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
420 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700421 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700422 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
423 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700424 }
425}
426
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700427Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700428 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700429 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
430 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700431 }
432
433 mKeyStore->resetUser(userId, false);
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::lock(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700439 if (!checkBinderPermission(P_LOCK)) {
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_NO_ERROR) {
446 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700447 *aidl_return = static_cast<int32_t>(ResponseCode(state));
448 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700449 }
450
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700451 mKeyStore->getEnforcementPolicy().set_device_locked(true, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700452 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700453 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
454 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700455}
456
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700457Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700458 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700459 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
460 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700461 }
462
463 State state = mKeyStore->getState(userId);
464 if (state != ::STATE_LOCKED) {
465 switch (state) {
466 case ::STATE_NO_ERROR:
467 ALOGI("calling unlock when already unlocked, ignoring.");
468 break;
469 case ::STATE_UNINITIALIZED:
470 ALOGE("unlock called on uninitialized keystore.");
471 break;
472 default:
473 ALOGE("unlock called on keystore in unknown state: %d", state);
474 break;
475 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700476 *aidl_return = static_cast<int32_t>(ResponseCode(state));
477 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700478 }
479
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700480 mKeyStore->getEnforcementPolicy().set_device_locked(false, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700481 const String8 password8(pw);
482 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700483 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
484 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700485}
486
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700487Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700488 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700489 *aidl_return = static_cast<int32_t>(false);
490 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700491 }
492
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700493 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
494 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700495}
496
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700497Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
498 ::android::String16* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700499 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700500 auto result =
501 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100502 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700503 *aidl_return = String16();
504 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700505 }
506
507 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700508 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
509 if (!lockedEntry) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700510 *aidl_return = String16();
511 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700512 }
513
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700514 *aidl_return = String16(mKeyStore->addGrant(lockedEntry, granteeUid).c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700515 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700516}
517
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700518Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700519 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Bo Zhu91de6db2018-03-20 12:52:13 -0700520 KeyStoreServiceReturnCode result =
521 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100522 if (!result.isOk()) {
Branden Archer70080742018-11-20 11:04:11 -0800523 *aidl_return = result.getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700524 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700525 }
526
527 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700528
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700529 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
530 if (!lockedEntry) {
531 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700532 }
533
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700534 *aidl_return = mKeyStore->removeGrant(lockedEntry, granteeUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700535 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700536}
537
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700538Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700539 uid_t targetUid = getEffectiveUid(uid);
540 if (!checkBinderPermission(P_GET, targetUid)) {
541 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700542 *time = -1L;
543 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700544 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700545 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700546
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700547 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
548 if (!lockedEntry) {
549 ALOGW("could not access key with alias %s for getmtime", name8.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700550 *time = -1L;
551 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700552 }
553
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700554 std::string filename = lockedEntry->getKeyBlobPath();
555
556 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700557 if (fd < 0) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700558 ALOGW("could not open %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700559 *time = -1L;
560 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700561 }
562
563 struct stat s;
564 int ret = fstat(fd, &s);
565 close(fd);
566 if (ret == -1) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700567 ALOGW("could not stat %s for getmtime", filename.c_str());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700568 *time = -1L;
569 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700570 }
571
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700572 *time = static_cast<int64_t>(s.st_mtime);
573 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700574}
575
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700576Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
577 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
578 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700579}
580
Janis Danisevskis265435f2018-11-16 14:10:46 -0800581Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700582 uid_t targetUid = getEffectiveUid(targetUid64);
583 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800584 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700585 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000586 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700587
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700588 mKeyStore->removeAllGrantsToUid(targetUid);
589
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700590 ResponseCode rc;
591 std::list<LockedKeyBlobEntry> entries;
Janis Danisevskis265435f2018-11-16 14:10:46 -0800592 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700593
594 // list has a fence making sure no workers are modifying blob files before iterating the
595 // data base. All returned entries are locked.
596 std::tie(rc, entries) = LockedKeyBlobEntry::list(
Janis Danisevskis265435f2018-11-16 14:10:46 -0800597 userDirName, [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700598
599 if (rc != ResponseCode::NO_ERROR) {
Janis Danisevskis265435f2018-11-16 14:10:46 -0800600 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700601 }
602
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700603 for (LockedKeyBlobEntry& lockedEntry : entries) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100604 if (get_app_id(targetUid) == AID_SYSTEM) {
605 Blob keyBlob;
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700606 Blob charBlob;
607 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
608 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
Rubin Xu85c85e92017-04-26 20:07:30 +0100609 // Do not clear keys critical to device encryption under system uid.
610 continue;
611 }
612 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700613 mKeyStore->del(lockedEntry);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700614 }
Janis Danisevskis265435f2018-11-16 14:10:46 -0800615 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700616}
617
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600618Status KeyStoreService::addRngEntropy(
619 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
620 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
Janis Danisevskisc1460142017-12-18 16:48:46 -0800621 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
622 if (!device) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600623 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800624 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700625
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600626 device->addRngEntropy(entropy, [cb](Return<ErrorCode> rc) {
627 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(rc)));
628 });
629
630 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700631}
632
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600633Status KeyStoreService::generateKey(
634 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
635 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
636 int uid, int flags, int32_t* _aidl_return) {
Max Biresef4f0672017-11-29 14:38:48 -0800637 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
638 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700639 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000640 auto logOnScopeExit = android::base::make_scope_guard([&] {
641 if (__android_log_security()) {
642 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600643 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000644 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
645 }
646 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100647 KeyStoreServiceReturnCode rc =
648 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
649 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600650 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700651 }
Rubin Xu67899de2017-04-21 19:15:13 +0100652 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
653 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600654 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100655 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700656
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700657 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700658 // TODO(jbires): remove uid checking upon implementation of b/25646100
Max Bires670467d2017-12-12 11:16:43 -0800659 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Biresef4f0672017-11-29 14:38:48 -0800660 originalUid != IPCThreadState::self()->getCallingUid()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600661 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700662 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600663 }
664
Janis Danisevskisc1460142017-12-18 16:48:46 -0800665 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
666 auto dev = mKeyStore->getDevice(securityLevel);
667 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600668 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800669 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400670
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100671 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700672 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
673 if (!lockedEntry) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600674 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100675 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400676
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700677 logOnScopeExit.Disable();
678
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600679 dev->generateKey(
680 std::move(lockedEntry), params.getParameters(), entropy, flags,
681 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
682 if (__android_log_security()) {
683 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
684 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
685 }
686 cb->onFinished(rc,
687 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
688 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700689
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600690 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700691}
692
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700693Status KeyStoreService::getKeyCharacteristics(
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600694 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700695 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
Janis Danisevskis64ec1fe2018-02-26 16:47:21 -0800696 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600697 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700698
699 uid_t targetUid = getEffectiveUid(uid);
700 uid_t callingUid = IPCThreadState::self()->getCallingUid();
701 if (!is_granted_to(callingUid, targetUid)) {
702 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
703 targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600704 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700705 }
706
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700707 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700708
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700709 ResponseCode rc;
710 Blob keyBlob;
711 Blob charBlob;
712 LockedKeyBlobEntry lockedEntry;
Janis Danisevskisd714a672017-09-01 14:31:36 -0700713
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700714 std::tie(rc, keyBlob, charBlob, lockedEntry) =
715 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
716
717 if (rc != ResponseCode::NO_ERROR) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600718 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700719 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100720
Janis Danisevskisc1460142017-12-18 16:48:46 -0800721 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700722 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600723 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100724 }
725
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700726 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
727 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
728 // from keymaster. It may also upgrade the key blob.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700729 dev->getKeyCharacteristics(
730 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
731 std::move(charBlob),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600732 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
733 cb->onFinished(rc,
734 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700735 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100736
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600737 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700738}
739
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600740Status KeyStoreService::importKey(
741 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
742 const String16& name, const KeymasterArguments& params, int32_t format,
743 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700744 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000745 auto logOnScopeExit = android::base::make_scope_guard([&] {
746 if (__android_log_security()) {
747 android_log_event_list(SEC_TAG_KEY_IMPORTED)
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600748 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
Pavel Grafovff311b42018-01-24 20:34:37 +0000749 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
750 }
751 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100752 KeyStoreServiceReturnCode rc =
753 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
754 if (!rc.isOk()) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700755 LOG(ERROR) << "permissission denied";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600756 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700757 }
Rubin Xu67899de2017-04-21 19:15:13 +0100758 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
759 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600760 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Rubin Xu67899de2017-04-21 19:15:13 +0100761 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700762
Janis Danisevskisc1460142017-12-18 16:48:46 -0800763 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
764 auto dev = mKeyStore->getDevice(securityLevel);
765 if (!dev) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700766 LOG(ERROR) << "importKey - cound not get keymaster device";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600767 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800768 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700769
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700770 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700771 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
772 if (!lockedEntry) {
773 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
774 << " already exists.";
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600775 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400776 }
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700777
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700778 logOnScopeExit.Disable();
Janis Danisevskis4a1da2f2018-03-26 15:02:38 -0700779
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600780 dev->importKey(
781 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
782 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
783 if (__android_log_security()) {
784 android_log_event_list(SEC_TAG_KEY_IMPORTED)
785 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
786 }
787 cb->onFinished(rc,
788 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
789 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400790
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600791 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700792}
793
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600794Status KeyStoreService::exportKey(
795 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
796 const String16& name, int32_t format,
797 const ::android::security::keymaster::KeymasterBlob& clientId,
798 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
799 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700800
801 uid_t targetUid = getEffectiveUid(uid);
802 uid_t callingUid = IPCThreadState::self()->getCallingUid();
803 if (!is_granted_to(callingUid, targetUid)) {
804 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600805 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700806 }
807
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700808 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700809
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700810 KeyStoreServiceReturnCode rc;
811 Blob keyBlob;
812 Blob charBlob;
813 LockedKeyBlobEntry lockedEntry;
814
815 std::tie(rc, keyBlob, charBlob, lockedEntry) =
816 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskis3cf85322018-11-19 13:37:49 -0800817 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600818 return AIDL_RETURN(rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700819 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100820
Janis Danisevskisc1460142017-12-18 16:48:46 -0800821 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100822
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700823 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600824 std::move(keyBlob), std::move(charBlob),
825 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
Ji Wang2c142312016-10-14 17:21:10 +0800826
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600827 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700828}
829
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600830Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
831 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700832 bool pruneable, const KeymasterArguments& params,
833 const ::std::vector<uint8_t>& entropy, int32_t uid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600834 int32_t* _aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700835 uid_t callingUid = IPCThreadState::self()->getCallingUid();
836 uid_t targetUid = getEffectiveUid(uid);
837 if (!is_granted_to(callingUid, targetUid)) {
838 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600839 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700840 }
841 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
842 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600843 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700844 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700845 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600846 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700847 }
Shawn Willden0329a822017-12-04 13:55:14 -0700848
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700849 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700850 Blob keyBlob;
851 Blob charBlob;
852 LockedKeyBlobEntry lockedEntry;
853 ResponseCode rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100854
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700855 std::tie(rc, keyBlob, charBlob, lockedEntry) =
856 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
857
858 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600859 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700860 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600861 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700862
Janis Danisevskisc1460142017-12-18 16:48:46 -0800863 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700864 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100865
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700866 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
867 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600868 [this, cb, dev](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700869 if (result_.resultCode.isOk() ||
870 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
871 addOperationDevice(result_.token, dev);
872 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600873 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700874 });
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400875
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::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
880 const ::android::sp<::android::IBinder>& token,
881 const ::android::security::keymaster::KeymasterArguments& params,
882 const ::std::vector<uint8_t>& input, 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 Danisevskisff3d7f42018-10-08 07:15:09 -0700887 auto dev = getOperationDevice(token);
888 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 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700891
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600892 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700893 if (!result_.resultCode.isOk()) {
894 removeOperationDevice(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100895 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600896 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700897 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100898
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600899 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700900}
901
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600902Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
903 const ::android::sp<::android::IBinder>& token,
904 const ::android::security::keymaster::KeymasterArguments& params,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700905 const ::std::vector<uint8_t>& signature,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600906 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700907 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600908 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700909 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700910
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700911 auto dev = getOperationDevice(token);
912 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600913 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700914 }
915
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700916 dev->finish(token, params.getParameters(), {}, signature, entropy,
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600917 [this, cb, token](OperationResult result_) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700918 if (!result_.resultCode.isOk()) {
919 removeOperationDevice(token);
920 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600921 cb->onFinished(result_);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700922 });
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700923
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600924 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700925}
926
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600927Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
928 const ::android::sp<::android::IBinder>& token,
929 int32_t* _aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700930 auto dev = getOperationDevice(token);
931 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600932 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700933 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100934
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600935 dev->abort(token, [cb](KeyStoreServiceReturnCode rc) { cb->onFinished(rc); });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700936
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600937 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700938}
939
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700940Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +0000941 int32_t* aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700942
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000943 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
944 // receive a HardwareAuthToken, rather than an opaque byte array.
945
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700946 if (!checkBinderPermission(P_ADD_AUTH)) {
947 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700948 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
949 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700950 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700951 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
Branden Archer70080742018-11-20 11:04:11 -0800952 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700953 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000954 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100955
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000956 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700957 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000958 if (authToken.version != 0) {
Branden Archer70080742018-11-20 11:04:11 -0800959 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700960 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000961 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100962
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700963 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
964 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700965 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
966 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700967}
968
Rubin Xu1a203e32018-05-08 14:25:21 +0100969int isDeviceIdAttestationRequested(const KeymasterArguments& params) {
Chih-Hung Hsiehb81e68b2018-07-13 11:37:45 -0700970 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
Rubin Xu1a203e32018-05-08 14:25:21 +0100971 int result = 0;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700972 for (size_t i = 0; i < paramsVec.size(); ++i) {
973 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -0600974 case Tag::ATTESTATION_ID_BRAND:
975 case Tag::ATTESTATION_ID_DEVICE:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600976 case Tag::ATTESTATION_ID_MANUFACTURER:
Shawn Willdene2a7b522017-04-11 09:27:40 -0600977 case Tag::ATTESTATION_ID_MODEL:
978 case Tag::ATTESTATION_ID_PRODUCT:
Rubin Xu1a203e32018-05-08 14:25:21 +0100979 result |= ID_ATTESTATION_REQUEST_GENERIC_INFO;
Shawn Willdene2a7b522017-04-11 09:27:40 -0600980 break;
Rubin Xu1a203e32018-05-08 14:25:21 +0100981 case Tag::ATTESTATION_ID_IMEI:
982 case Tag::ATTESTATION_ID_MEID:
983 case Tag::ATTESTATION_ID_SERIAL:
984 result |= ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID;
985 break;
986 default:
987 continue;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100988 }
989 }
Rubin Xu1a203e32018-05-08 14:25:21 +0100990 return result;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100991}
992
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600993Status KeyStoreService::attestKey(
994 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
995 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700996 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
997 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -0600998 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Shawn Willden50eb1b22016-01-21 12:41:23 -0700999 }
1000
Eran Messerie2c34152017-12-21 21:01:22 +00001001 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1002
Rubin Xu1a203e32018-05-08 14:25:21 +01001003 int needsIdAttestation = isDeviceIdAttestationRequested(params);
1004 bool needsUniqueIdAttestation = needsIdAttestation & ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID;
1005 bool isPrimaryUserSystemUid = (callingUid == AID_SYSTEM);
1006 bool isSomeUserSystemUid = (get_app_id(callingUid) == AID_SYSTEM);
1007 // Allow system context from any user to request attestation with basic device information,
1008 // while only allow system context from user 0 (device owner) to request attestation with
1009 // unique device ID.
1010 if ((needsIdAttestation && !isSomeUserSystemUid) ||
1011 (needsUniqueIdAttestation && !isPrimaryUserSystemUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001012 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001013 }
1014
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001015 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001016 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1017 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001018 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001019 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001020
Shawn Willden50eb1b22016-01-21 12:41:23 -07001021 String8 name8(name);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001022 Blob keyBlob;
1023 Blob charBlob;
1024 LockedKeyBlobEntry lockedEntry;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001025
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001026 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1027 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1028
Janis Danisevskisc1460142017-12-18 16:48:46 -08001029 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001030 auto hidlKey = blob2hidlVec(keyBlob);
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001031 dev->attestKey(
1032 std::move(hidlKey), mutableParams.hidl_data(),
1033 [cb](Return<void> rc, std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1034 auto& [ret, certChain] = hidlResult;
1035 if (!rc.isOk()) {
1036 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1037 } else if (ret != ErrorCode::OK) {
1038 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1039 } else {
1040 cb->onFinished(KeyStoreServiceReturnCode(ret),
1041 KeymasterCertificateChain(std::move(certChain)));
1042 }
1043 });
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001044
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001045 return AIDL_RETURN(ResponseCode::NO_ERROR);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001046}
1047
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001048// My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1049// It should never be redefined by a build system though.
1050#ifndef CAPTURE_MOVE
1051#define CAPTURE_MOVE(x) x = std::move(x)
1052#endif
1053
1054Status KeyStoreService::attestDeviceIds(
1055 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1056 const KeymasterArguments& params, int32_t* _aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001057 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001058
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001059 if (!checkAllowedOperationParams(params.getParameters())) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001060 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001061 }
1062
1063 if (!isDeviceIdAttestationRequested(params)) {
1064 // There is an attestKey() method for attesting keys without device ID attestation.
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001065 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001066 }
1067
1068 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1069 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
Yi Konge353f252018-07-30 01:38:39 -07001070 if (binder == nullptr) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001071 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001072 }
1073 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1074 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1075 IPCThreadState::self()->getCallingPid(), callingUid)) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001076 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001077 }
1078
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001079 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001080 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1081 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001082 return AIDL_RETURN(rc);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001083 }
1084
1085 // Generate temporary key.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001086 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001087
Shawn Willden70c1a782018-07-11 15:13:20 -06001088 if (!dev) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001089 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001090 }
1091
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001092
1093 AuthorizationSet keyCharacteristics;
1094 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1095 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1096 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1097 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1098 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001099
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001100 std::promise<KeyStoreServiceReturnCode> resultPromise;
1101 auto resultFuture = resultPromise.get_future();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001102
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001103 dev->generateKey(
1104 keyCharacteristics.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001105 [cb, dev, CAPTURE_MOVE(mutableParams)](
1106 Return<void> rc,
1107 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001108 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1109 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1110 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001111 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001112 return;
1113 }
1114 if (ret != ErrorCode::OK) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001115 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001116 return;
1117 }
1118 dev->attestKey(
1119 hidlKeyBlob, mutableParams.hidl_data(),
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001120 [cb, dev,
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001121 hidlKeyBlob](Return<void> rc,
1122 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1123 auto& [ret, certChain] = hidlResult;
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001124 // schedule temp key for deletion
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001125 dev->deleteKey(std::move(hidlKeyBlob), [](Return<ErrorCode> rc) {
1126 // log error but don't return an error
1127 KS_HANDLE_HIDL_ERROR(rc);
1128 });
1129 if (!rc.isOk()) {
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001130 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001131 return;
1132 }
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001133 if (ret == ErrorCode::OK) {
1134 cb->onFinished(
1135 KeyStoreServiceReturnCode(ret),
1136 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1137 } else {
1138 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001139 }
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001140 });
1141 });
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001142
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001143 return AIDL_RETURN(ResponseCode::NO_ERROR);
Shawn Willden50eb1b22016-01-21 12:41:23 -07001144}
1145
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001146Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001147 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001148 mKeyStore->getAuthTokenTable().onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001149 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1150 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001151}
1152
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001153Status KeyStoreService::importWrappedKey(
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001154 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001155 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1156 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1157 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001158 int32_t* _aidl_return) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001159
1160 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1161
1162 if (!checkBinderPermission(P_INSERT, callingUid)) {
1163 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1164 }
1165
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001166 String8 wrappingKeyName8(wrappingKeyAlias);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001167
1168 KeyStoreServiceReturnCode rc;
1169 Blob wrappingKeyBlob;
1170 Blob wrappingCharBlob;
1171 LockedKeyBlobEntry wrappingLockedEntry;
1172
1173 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1174 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
Branden Archerd166a882018-11-20 10:56:48 -08001175 if (!rc.isOk()) {
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001176 return AIDL_RETURN(rc);
1177 }
1178
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001179 String8 wrappedKeyName8(wrappedKeyAlias);
1180 auto wrappedLockedEntry =
1181 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1182 if (!wrappedLockedEntry) {
1183 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1184 }
1185
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001186 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1187 auto dev = mKeyStore->getDevice(securityLevel);
1188 if (!dev) {
1189 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1190 }
1191
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001192 dev->importWrappedKey(
1193 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1194 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001195 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1196 cb->onFinished(rc,
1197 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001198 });
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001199
Rob Barnesbb6cabd2018-10-04 17:10:37 -06001200 return AIDL_RETURN(ResponseCode::NO_ERROR);
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001201}
1202
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001203Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1204 const String16& promptText,
1205 const ::std::vector<uint8_t>& extraData,
1206 const String16& locale, int32_t uiOptionsAsFlags,
1207 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001208 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1209 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001210}
1211
1212Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1213 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001214 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001215}
1216
David Zeuthen1a492312018-02-26 11:00:30 -05001217Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001218 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001219}
1220
1221/**
1222 * Get the effective target uid for a binder operation that takes an
1223 * optional uid as the target.
1224 */
1225uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1226 if (targetUid == UID_SELF) {
1227 return IPCThreadState::self()->getCallingUid();
1228 }
1229 return static_cast<uid_t>(targetUid);
1230}
1231
1232/**
1233 * Check if the caller of the current binder method has the required
1234 * permission and if acting on other uids the grants to do so.
1235 */
1236bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1237 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1238 pid_t spid = IPCThreadState::self()->getCallingPid();
1239 if (!has_permission(callingUid, permission, spid)) {
1240 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1241 return false;
1242 }
1243 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1244 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1245 return false;
1246 }
1247 return true;
1248}
1249
1250/**
1251 * Check if the caller of the current binder method has the required
1252 * permission and the target uid is the caller or the caller is system.
1253 */
1254bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1255 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1256 pid_t spid = IPCThreadState::self()->getCallingPid();
1257 if (!has_permission(callingUid, permission, spid)) {
1258 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1259 return false;
1260 }
1261 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1262}
1263
1264/**
1265 * Check if the caller of the current binder method has the required
1266 * permission or the target of the operation is the caller's uid. This is
1267 * for operation where the permission is only for cross-uid activity and all
1268 * uids are allowed to act on their own (ie: clearing all entries for a
1269 * given uid).
1270 */
1271bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1272 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1273 if (getEffectiveUid(targetUid) == callingUid) {
1274 return true;
1275 } else {
1276 return checkBinderPermission(permission, targetUid);
1277 }
1278}
1279
1280/**
1281 * Helper method to check that the caller has the required permission as
1282 * well as the keystore is in the unlocked state if checkUnlocked is true.
1283 *
1284 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1285 * otherwise the state of keystore when not unlocked and checkUnlocked is
1286 * true.
1287 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001288KeyStoreServiceReturnCode
1289KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1290 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001291 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001292 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001293 }
1294 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1295 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001296 // All State values coincide with ResponseCodes
1297 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001298 }
1299
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001300 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001301}
1302
1303bool KeyStoreService::isKeystoreUnlocked(State state) {
1304 switch (state) {
1305 case ::STATE_NO_ERROR:
1306 return true;
1307 case ::STATE_UNINITIALIZED:
1308 case ::STATE_LOCKED:
1309 return false;
1310 }
1311 return false;
1312}
1313
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001314/**
Shawn Willden0329a822017-12-04 13:55:14 -07001315 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1316 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001317 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001318bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1319 for (size_t i = 0; i < params.size(); ++i) {
1320 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001321 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001322 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001323 return false;
1324 default:
1325 break;
1326 }
1327 }
1328 return true;
1329}
1330
Brian Young9a947d52018-02-23 18:03:14 +00001331Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
1332 int32_t* aidl_return) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -07001333 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
Brian Young9a947d52018-02-23 18:03:14 +00001334 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
Brian Young9371e952018-02-23 18:03:14 +00001335
1336 return Status::ok();
1337}
1338
Shawn Willdene2a7b522017-04-11 09:27:40 -06001339} // namespace keystore