blob: d5923b5f13d298a4d9dec9ea379ad07ec390cf2e [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>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070025#include <sstream>
26
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010027#include <binder/IInterface.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070028#include <binder/IPCThreadState.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010029#include <binder/IPermissionController.h>
30#include <binder/IServiceManager.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070031
32#include <private/android_filesystem_config.h>
33
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010034#include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070035
36#include "defaults.h"
Janis Danisevskis18f27ad2016-06-01 13:57:40 -070037#include "keystore_attestation_id.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010038#include "keystore_keymaster_enforcement.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070039#include "keystore_utils.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010040#include <keystore/keystore_hidl_support.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070041
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010042namespace keystore {
Shawn Willdend5a24e62017-02-28 13:53:24 -070043
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010044using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070045
Shawn Willdene2a7b522017-04-11 09:27:40 -060046namespace {
47
48constexpr size_t kMaxOperations = 15;
49constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
50const char* kTimestampFilePath = "timestamp";
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070051
52struct BIGNUM_Delete {
53 void operator()(BIGNUM* p) const { BN_free(p); }
54};
55typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
56
Shawn Willdene2a7b522017-04-11 09:27:40 -060057bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
58 return params.end() != std::find_if(params.begin(), params.end(),
59 [&](auto& param) { return param.tag == tag; });
60}
61
Shawn Willdend5a24e62017-02-28 13:53:24 -070062bool isAuthenticationBound(const hidl_vec<KeyParameter>& params) {
63 return !containsTag(params, Tag::NO_AUTH_REQUIRED);
64}
65
Shawn Willdene2a7b522017-04-11 09:27:40 -060066std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
67 struct stat sbuf;
68 if (stat(kTimestampFilePath, &sbuf) == 0) {
69 double diff_secs = difftime(time(NULL), sbuf.st_ctime);
70 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
71 }
72
73 if (errno != ENOENT) {
74 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
75 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
76 }
77
78 int fd = creat(kTimestampFilePath, 0600);
79 if (fd < 0) {
80 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
81 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
82 }
83
84 if (close(fd)) {
85 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
86 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
87 }
88
89 return {ResponseCode::NO_ERROR, true};
90}
91
92} // anonymous namespace
93
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070094void KeyStoreService::binderDied(const wp<IBinder>& who) {
95 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -070096 for (const auto& token : operations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070097 abort(token);
98 }
99}
100
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100101KeyStoreServiceReturnCode KeyStoreService::getState(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700102 if (!checkBinderPermission(P_GET_STATE)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100103 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700104 }
105
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100106 return ResponseCode(mKeyStore->getState(userId));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700107}
108
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100109KeyStoreServiceReturnCode KeyStoreService::get(const String16& name, int32_t uid,
110 hidl_vec<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700111 uid_t targetUid = getEffectiveUid(uid);
112 if (!checkBinderPermission(P_GET, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100113 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700114 }
115
116 String8 name8(name);
117 Blob keyBlob;
118
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100119 KeyStoreServiceReturnCode rc =
120 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
121 if (!rc.isOk()) {
122 if (item) *item = hidl_vec<uint8_t>();
123 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700124 }
125
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100126 // Do not replace this with "if (item) *item = blob2hidlVec(keyBlob)"!
127 // blob2hidlVec creates a hidl_vec<uint8_t> that references, but not owns, the data in keyBlob
128 // the subsequent assignment (*item = resultBlob) makes a deep copy, so that *item will own the
129 // corresponding resources.
130 auto resultBlob = blob2hidlVec(keyBlob);
131 if (item) {
132 *item = resultBlob;
133 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700134
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100135 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700136}
137
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100138KeyStoreServiceReturnCode KeyStoreService::insert(const String16& name,
139 const hidl_vec<uint8_t>& item, int targetUid,
140 int32_t flags) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700141 targetUid = getEffectiveUid(targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100142 auto result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700143 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100144 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700145 return result;
146 }
147
148 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400149 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_GENERIC));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700150
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100151 Blob keyBlob(&item[0], item.size(), NULL, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700152 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
153
154 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
155}
156
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100157KeyStoreServiceReturnCode KeyStoreService::del(const String16& name, int targetUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700158 targetUid = getEffectiveUid(targetUid);
159 if (!checkBinderPermission(P_DELETE, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100160 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700161 }
162 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000163 ALOGI("del %s %d", name8.string(), targetUid);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400164 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100165 ResponseCode result = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
166 if (result != ResponseCode::NO_ERROR) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400167 return result;
168 }
169
170 // Also delete any characteristics files
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100171 String8 chrFilename(
172 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400173 return mKeyStore->del(chrFilename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700174}
175
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100176KeyStoreServiceReturnCode KeyStoreService::exist(const String16& name, int targetUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700177 targetUid = getEffectiveUid(targetUid);
178 if (!checkBinderPermission(P_EXIST, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100179 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700180 }
181
182 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400183 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700184
185 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100186 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700187 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100188 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700189}
190
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100191KeyStoreServiceReturnCode KeyStoreService::list(const String16& prefix, int targetUid,
192 Vector<String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700193 targetUid = getEffectiveUid(targetUid);
194 if (!checkBinderPermission(P_LIST, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100195 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700196 }
197 const String8 prefix8(prefix);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400198 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid, TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700199
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100200 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
201 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700202 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100203 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700204}
205
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100206KeyStoreServiceReturnCode KeyStoreService::reset() {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700207 if (!checkBinderPermission(P_RESET)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100208 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700209 }
210
211 uid_t callingUid = IPCThreadState::self()->getCallingUid();
212 mKeyStore->resetUser(get_user_id(callingUid), false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100213 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700214}
215
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100216KeyStoreServiceReturnCode KeyStoreService::onUserPasswordChanged(int32_t userId,
217 const String16& password) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700218 if (!checkBinderPermission(P_PASSWORD)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100219 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700220 }
221
222 const String8 password8(password);
223 // Flush the auth token table to prevent stale tokens from sticking
224 // around.
225 mAuthTokenTable.Clear();
226
227 if (password.size() == 0) {
228 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
229 mKeyStore->resetUser(userId, true);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100230 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700231 } else {
232 switch (mKeyStore->getState(userId)) {
233 case ::STATE_UNINITIALIZED: {
234 // generate master key, encrypt with password, write to file,
235 // initialize mMasterKey*.
236 return mKeyStore->initializeUser(password8, userId);
237 }
238 case ::STATE_NO_ERROR: {
239 // rewrite master key with new password.
240 return mKeyStore->writeMasterKey(password8, userId);
241 }
242 case ::STATE_LOCKED: {
243 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
244 mKeyStore->resetUser(userId, true);
245 return mKeyStore->initializeUser(password8, userId);
246 }
247 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100248 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700249 }
250}
251
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100252KeyStoreServiceReturnCode KeyStoreService::onUserAdded(int32_t userId, int32_t parentId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700253 if (!checkBinderPermission(P_USER_CHANGED)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100254 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700255 }
256
257 // Sanity check that the new user has an empty keystore.
258 if (!mKeyStore->isEmpty(userId)) {
259 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
260 }
261 // Unconditionally clear the keystore, just to be safe.
262 mKeyStore->resetUser(userId, false);
263 if (parentId != -1) {
264 // This profile must share the same master key password as the parent profile. Because the
265 // password of the parent profile is not known here, the best we can do is copy the parent's
266 // master key and master key file. This makes this profile use the same master key as the
267 // parent profile, forever.
268 return mKeyStore->copyMasterKey(parentId, userId);
269 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100270 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700271 }
272}
273
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100274KeyStoreServiceReturnCode KeyStoreService::onUserRemoved(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700275 if (!checkBinderPermission(P_USER_CHANGED)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100276 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700277 }
278
279 mKeyStore->resetUser(userId, false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100280 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700281}
282
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100283KeyStoreServiceReturnCode KeyStoreService::lock(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700284 if (!checkBinderPermission(P_LOCK)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100285 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700286 }
287
288 State state = mKeyStore->getState(userId);
289 if (state != ::STATE_NO_ERROR) {
290 ALOGD("calling lock in state: %d", state);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100291 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700292 }
293
294 mKeyStore->lock(userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100295 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700296}
297
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100298KeyStoreServiceReturnCode KeyStoreService::unlock(int32_t userId, const String16& pw) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700299 if (!checkBinderPermission(P_UNLOCK)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100300 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700301 }
302
303 State state = mKeyStore->getState(userId);
304 if (state != ::STATE_LOCKED) {
305 switch (state) {
306 case ::STATE_NO_ERROR:
307 ALOGI("calling unlock when already unlocked, ignoring.");
308 break;
309 case ::STATE_UNINITIALIZED:
310 ALOGE("unlock called on uninitialized keystore.");
311 break;
312 default:
313 ALOGE("unlock called on keystore in unknown state: %d", state);
314 break;
315 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100316 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700317 }
318
319 const String8 password8(pw);
320 // read master key, decrypt with password, initialize mMasterKey*.
321 return mKeyStore->readMasterKey(password8, userId);
322}
323
324bool KeyStoreService::isEmpty(int32_t userId) {
325 if (!checkBinderPermission(P_IS_EMPTY)) {
326 return false;
327 }
328
329 return mKeyStore->isEmpty(userId);
330}
331
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100332KeyStoreServiceReturnCode KeyStoreService::generate(const String16& name, int32_t targetUid,
333 int32_t keyType, int32_t keySize, int32_t flags,
334 Vector<sp<KeystoreArg>>* args) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700335 targetUid = getEffectiveUid(targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100336 auto result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700337 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100338 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700339 return result;
340 }
341
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100342 keystore::AuthorizationSet params;
343 add_legacy_key_authorizations(keyType, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700344
345 switch (keyType) {
346 case EVP_PKEY_EC: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100347 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700348 if (keySize == -1) {
349 keySize = EC_DEFAULT_KEY_SIZE;
350 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
351 ALOGI("invalid key size %d", keySize);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100352 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700353 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100354 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700355 break;
356 }
357 case EVP_PKEY_RSA: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100358 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700359 if (keySize == -1) {
360 keySize = RSA_DEFAULT_KEY_SIZE;
361 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
362 ALOGI("invalid key size %d", keySize);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100363 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700364 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100365 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700366 unsigned long exponent = RSA_DEFAULT_EXPONENT;
367 if (args->size() > 1) {
368 ALOGI("invalid number of arguments: %zu", args->size());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100369 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700370 } else if (args->size() == 1) {
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700371 const sp<KeystoreArg>& expArg = args->itemAt(0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700372 if (expArg != NULL) {
373 Unique_BIGNUM pubExpBn(BN_bin2bn(
374 reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
375 if (pubExpBn.get() == NULL) {
376 ALOGI("Could not convert public exponent to BN");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100377 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700378 }
379 exponent = BN_get_word(pubExpBn.get());
380 if (exponent == 0xFFFFFFFFL) {
381 ALOGW("cannot represent public exponent as a long value");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100382 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700383 }
384 } else {
385 ALOGW("public exponent not read");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100386 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700387 }
388 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100389 params.push_back(TAG_RSA_PUBLIC_EXPONENT, exponent);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700390 break;
391 }
392 default: {
393 ALOGW("Unsupported key type %d", keyType);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100394 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700395 }
396 }
397
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100398 auto rc = generateKey(name, params.hidl_data(), hidl_vec<uint8_t>(), targetUid, flags,
399 /*outCharacteristics*/ NULL);
400 if (!rc.isOk()) {
401 ALOGW("generate failed: %d", int32_t(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700402 }
403 return translateResultToLegacyResult(rc);
404}
405
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100406KeyStoreServiceReturnCode KeyStoreService::import(const String16& name,
407 const hidl_vec<uint8_t>& data, int targetUid,
408 int32_t flags) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700409
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100410 const uint8_t* ptr = &data[0];
411
412 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, data.size()));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700413 if (!pkcs8.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100414 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700415 }
416 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
417 if (!pkey.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100418 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700419 }
420 int type = EVP_PKEY_type(pkey->type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100421 AuthorizationSet params;
422 add_legacy_key_authorizations(type, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700423 switch (type) {
424 case EVP_PKEY_RSA:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100425 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700426 break;
427 case EVP_PKEY_EC:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100428 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700429 break;
430 default:
431 ALOGW("Unsupported key type %d", type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100432 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700433 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100434
435 auto rc = importKey(name, params.hidl_data(), KeyFormat::PKCS8, data, targetUid, flags,
436 /*outCharacteristics*/ NULL);
437
438 if (!rc.isOk()) {
439 ALOGW("importKey failed: %d", int32_t(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700440 }
441 return translateResultToLegacyResult(rc);
442}
443
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100444KeyStoreServiceReturnCode KeyStoreService::sign(const String16& name, const hidl_vec<uint8_t>& data,
445 hidl_vec<uint8_t>* out) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700446 if (!checkBinderPermission(P_SIGN)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100447 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700448 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100449 return doLegacySignVerify(name, data, out, hidl_vec<uint8_t>(), KeyPurpose::SIGN);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700450}
451
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100452KeyStoreServiceReturnCode KeyStoreService::verify(const String16& name,
453 const hidl_vec<uint8_t>& data,
454 const hidl_vec<uint8_t>& signature) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700455 if (!checkBinderPermission(P_VERIFY)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100456 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700457 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100458 return doLegacySignVerify(name, data, nullptr, signature, KeyPurpose::VERIFY);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700459}
460
461/*
462 * TODO: The abstraction between things stored in hardware and regular blobs
463 * of data stored on the filesystem should be moved down to keystore itself.
464 * Unfortunately the Java code that calls this has naming conventions that it
465 * knows about. Ideally keystore shouldn't be used to store random blobs of
466 * data.
467 *
468 * Until that happens, it's necessary to have a separate "get_pubkey" and
469 * "del_key" since the Java code doesn't really communicate what it's
470 * intentions are.
471 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100472KeyStoreServiceReturnCode KeyStoreService::get_pubkey(const String16& name,
473 hidl_vec<uint8_t>* pubKey) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700474 ExportResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100475 exportKey(name, KeyFormat::X509, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF, &result);
476 if (!result.resultCode.isOk()) {
477 ALOGW("export failed: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700478 return translateResultToLegacyResult(result.resultCode);
479 }
480
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100481 if (pubKey) *pubKey = std::move(result.exportData);
482 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700483}
484
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100485KeyStoreServiceReturnCode KeyStoreService::grant(const String16& name, int32_t granteeUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700486 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100487 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
488 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700489 return result;
490 }
491
492 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400493 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700494
495 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100496 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700497 }
498
499 mKeyStore->addGrant(filename.string(), granteeUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100500 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700501}
502
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100503KeyStoreServiceReturnCode KeyStoreService::ungrant(const String16& name, int32_t granteeUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700504 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100505 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
506 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700507 return result;
508 }
509
510 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400511 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700512
513 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100514 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700515 }
516
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100517 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ResponseCode::NO_ERROR
518 : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700519}
520
521int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
522 uid_t targetUid = getEffectiveUid(uid);
523 if (!checkBinderPermission(P_GET, targetUid)) {
524 ALOGW("permission denied for %d: getmtime", targetUid);
525 return -1L;
526 }
527
528 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400529 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700530
531 if (access(filename.string(), R_OK) == -1) {
532 ALOGW("could not access %s for getmtime", filename.string());
533 return -1L;
534 }
535
536 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
537 if (fd < 0) {
538 ALOGW("could not open %s for getmtime", filename.string());
539 return -1L;
540 }
541
542 struct stat s;
543 int ret = fstat(fd, &s);
544 close(fd);
545 if (ret == -1) {
546 ALOGW("could not stat %s for getmtime", filename.string());
547 return -1L;
548 }
549
550 return static_cast<int64_t>(s.st_mtime);
551}
552
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400553// TODO(tuckeris): This is dead code, remove it. Don't bother copying over key characteristics here
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100554KeyStoreServiceReturnCode KeyStoreService::duplicate(const String16& srcKey, int32_t srcUid,
555 const String16& destKey, int32_t destUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700556 uid_t callingUid = IPCThreadState::self()->getCallingUid();
557 pid_t spid = IPCThreadState::self()->getCallingPid();
558 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
559 ALOGW("permission denied for %d: duplicate", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100560 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700561 }
562
563 State state = mKeyStore->getState(get_user_id(callingUid));
564 if (!isKeystoreUnlocked(state)) {
565 ALOGD("calling duplicate in state: %d", state);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100566 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700567 }
568
569 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
570 srcUid = callingUid;
571 } else if (!is_granted_to(callingUid, srcUid)) {
572 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100573 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700574 }
575
576 if (destUid == -1) {
577 destUid = callingUid;
578 }
579
580 if (srcUid != destUid) {
581 if (static_cast<uid_t>(srcUid) != callingUid) {
582 ALOGD("can only duplicate from caller to other or to same uid: "
583 "calling=%d, srcUid=%d, destUid=%d",
584 callingUid, srcUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100585 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700586 }
587
588 if (!is_granted_to(callingUid, destUid)) {
589 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100590 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700591 }
592 }
593
594 String8 source8(srcKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400595 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700596
597 String8 target8(destKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400598 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700599
600 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
601 ALOGD("destination already exists: %s", targetFile.string());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100602 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700603 }
604
605 Blob keyBlob;
606 ResponseCode responseCode =
607 mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, get_user_id(srcUid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100608 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700609 return responseCode;
610 }
611
612 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
613}
614
615int32_t KeyStoreService::is_hardware_backed(const String16& keyType) {
616 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
617}
618
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100619KeyStoreServiceReturnCode KeyStoreService::clear_uid(int64_t targetUid64) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700620 uid_t targetUid = getEffectiveUid(targetUid64);
621 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100622 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700623 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000624 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700625
626 String8 prefix = String8::format("%u_", targetUid);
627 Vector<String16> aliases;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100628 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
629 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700630 }
631
632 for (uint32_t i = 0; i < aliases.size(); i++) {
633 String8 name8(aliases[i]);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400634 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700635 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400636
637 // del() will fail silently if no cached characteristics are present for this alias.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100638 String8 chr_filename(
639 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400640 mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700641 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100642 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700643}
644
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100645KeyStoreServiceReturnCode KeyStoreService::addRngEntropy(const hidl_vec<uint8_t>& entropy) {
646 const auto& device = mKeyStore->getDevice();
647 return KS_HANDLE_HIDL_ERROR(device->addRngEntropy(entropy));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700648}
649
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100650KeyStoreServiceReturnCode KeyStoreService::generateKey(const String16& name,
651 const hidl_vec<KeyParameter>& params,
652 const hidl_vec<uint8_t>& entropy, int uid,
653 int flags,
654 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700655 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100656 KeyStoreServiceReturnCode rc =
657 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
658 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700659 return rc;
660 }
Rubin Xu67899de2017-04-21 19:15:13 +0100661 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
662 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
663 return ResponseCode::PERMISSION_DENIED;
664 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700665
Shawn Willdene2a7b522017-04-11 09:27:40 -0600666 if (containsTag(params, Tag::INCLUDE_UNIQUE_ID)) {
667 if (!checkBinderPermission(P_GEN_UNIQUE_ID)) return ResponseCode::PERMISSION_DENIED;
668 }
669
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100670 bool usingFallback = false;
671 auto& dev = mKeyStore->getDevice();
672 AuthorizationSet keyCharacteristics = params;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400673
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700674 // TODO: Seed from Linux RNG before this.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100675 rc = addRngEntropy(entropy);
676 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700677 return rc;
678 }
679
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100680 KeyStoreServiceReturnCode error;
681 auto hidl_cb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
682 const KeyCharacteristics& keyCharacteristics) {
683 error = ret;
684 if (!error.isOk()) {
685 return;
686 }
687 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700688
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100689 // Write the key
690 String8 name8(name);
691 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700692
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100693 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
694 keyBlob.setFallback(usingFallback);
Rubin Xu67899de2017-04-21 19:15:13 +0100695 keyBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
696 if (isAuthenticationBound(params) && !keyBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -0700697 keyBlob.setSuperEncrypted(true);
698 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100699 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700700
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100701 error = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
702 };
703
704 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(params, hidl_cb));
705 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400706 return rc;
707 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100708 if (!error.isOk()) {
709 ALOGE("Failed to generate key -> falling back to software keymaster");
710 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000711 auto fallback = mKeyStore->getFallbackDevice();
712 if (!fallback.isOk()) {
713 return error;
714 }
715 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->generateKey(params, hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100716 if (!rc.isOk()) {
717 return rc;
718 }
719 if (!error.isOk()) {
720 return error;
721 }
722 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400723
724 // Write the characteristics:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100725 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400726 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
727
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100728 std::stringstream kc_stream;
729 keyCharacteristics.Serialize(&kc_stream);
730 if (kc_stream.bad()) {
731 return ResponseCode::SYSTEM_ERROR;
732 }
733 auto kc_buf = kc_stream.str();
734 Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
735 ::TYPE_KEY_CHARACTERISTICS);
736 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400737 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
738
739 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700740}
741
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100742KeyStoreServiceReturnCode
743KeyStoreService::getKeyCharacteristics(const String16& name, const hidl_vec<uint8_t>& clientId,
744 const hidl_vec<uint8_t>& appData, int32_t uid,
745 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700746 if (!outCharacteristics) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100747 return ErrorCode::UNEXPECTED_NULL_POINTER;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700748 }
749
750 uid_t targetUid = getEffectiveUid(uid);
751 uid_t callingUid = IPCThreadState::self()->getCallingUid();
752 if (!is_granted_to(callingUid, targetUid)) {
753 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
754 targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100755 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700756 }
757
758 Blob keyBlob;
759 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700760
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100761 KeyStoreServiceReturnCode rc =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700762 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100763 if (!rc.isOk()) {
764 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700765 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100766
767 auto hidlKeyBlob = blob2hidlVec(keyBlob);
768 auto& dev = mKeyStore->getDevice(keyBlob);
769
770 KeyStoreServiceReturnCode error;
771
772 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
773 error = ret;
774 if (!error.isOk()) {
775 return;
Shawn Willden98c59162016-03-20 09:10:18 -0600776 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100777 *outCharacteristics = keyCharacteristics;
778 };
779
780 rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(hidlKeyBlob, clientId, appData, hidlCb));
781 if (!rc.isOk()) {
782 return rc;
783 }
784
785 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
786 AuthorizationSet upgradeParams;
787 if (clientId.size()) {
788 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
789 }
790 if (appData.size()) {
791 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
Shawn Willden98c59162016-03-20 09:10:18 -0600792 }
793 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100794 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -0600795 return rc;
796 }
Shawn Willden715d0232016-01-21 00:45:13 -0700797
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100798 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
799
800 rc = KS_HANDLE_HIDL_ERROR(
801 dev->getKeyCharacteristics(upgradedHidlKeyBlob, clientId, appData, hidlCb));
802 if (!rc.isOk()) {
803 return rc;
804 }
805 // Note that, on success, "error" will have been updated by the hidlCB callback.
806 // So it is fine to return "error" below.
807 }
808 return error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700809}
810
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100811KeyStoreServiceReturnCode
812KeyStoreService::importKey(const String16& name, const hidl_vec<KeyParameter>& params,
813 KeyFormat format, const hidl_vec<uint8_t>& keyData, int uid, int flags,
814 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700815 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100816 KeyStoreServiceReturnCode rc =
817 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
818 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700819 return rc;
820 }
Rubin Xu67899de2017-04-21 19:15:13 +0100821 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
822 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
823 return ResponseCode::PERMISSION_DENIED;
824 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700825
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100826 bool usingFallback = false;
827 auto& dev = mKeyStore->getDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700828
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700829 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700830
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100831 KeyStoreServiceReturnCode error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700832
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100833 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
834 const KeyCharacteristics& keyCharacteristics) {
835 error = ret;
836 if (!error.isOk()) {
837 return;
838 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700839
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100840 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
841
842 // Write the key:
843 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
844
845 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
846 ksBlob.setFallback(usingFallback);
Rubin Xu67899de2017-04-21 19:15:13 +0100847 ksBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
848 if (isAuthenticationBound(params) && !ksBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -0700849 ksBlob.setSuperEncrypted(true);
850 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100851 ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
852
853 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
854 };
855
856 rc = KS_HANDLE_HIDL_ERROR(dev->importKey(params, format, keyData, hidlCb));
857 // possible hidl error
858 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400859 return rc;
860 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100861 // now check error from callback
862 if (!error.isOk()) {
863 ALOGE("Failed to import key -> falling back to software keymaster");
864 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000865 auto fallback = mKeyStore->getFallbackDevice();
866 if (!fallback.isOk()) {
867 return error;
868 }
869 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->importKey(params, format, keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100870 // possible hidl error
871 if (!rc.isOk()) {
872 return rc;
873 }
874 // now check error from callback
875 if (!error.isOk()) {
876 return error;
877 }
878 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400879
880 // Write the characteristics:
881 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
882
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100883 AuthorizationSet opParams = params;
884 std::stringstream kcStream;
885 opParams.Serialize(&kcStream);
886 if (kcStream.bad()) return ResponseCode::SYSTEM_ERROR;
887 auto kcBuf = kcStream.str();
888
889 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
890 ::TYPE_KEY_CHARACTERISTICS);
891 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400892 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
893
894 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700895}
896
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100897void KeyStoreService::exportKey(const String16& name, KeyFormat format,
898 const hidl_vec<uint8_t>& clientId, const hidl_vec<uint8_t>& appData,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700899 int32_t uid, ExportResult* result) {
900
901 uid_t targetUid = getEffectiveUid(uid);
902 uid_t callingUid = IPCThreadState::self()->getCallingUid();
903 if (!is_granted_to(callingUid, targetUid)) {
904 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100905 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700906 return;
907 }
908
909 Blob keyBlob;
910 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700911
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100912 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
913 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700914 return;
915 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100916
917 auto key = blob2hidlVec(keyBlob);
918 auto& dev = mKeyStore->getDevice(keyBlob);
919
920 auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
921 result->resultCode = ret;
922 if (!result->resultCode.isOk()) {
Ji Wang2c142312016-10-14 17:21:10 +0800923 return;
924 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100925 result->exportData = keyMaterial;
926 };
927 KeyStoreServiceReturnCode rc =
928 KS_HANDLE_HIDL_ERROR(dev->exportKey(format, key, clientId, appData, hidlCb));
929 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
930 // callback hidlCb.
931 if (!rc.isOk()) {
932 result->resultCode = rc;
Ji Wang2c142312016-10-14 17:21:10 +0800933 }
934
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100935 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
936 AuthorizationSet upgradeParams;
937 if (clientId.size()) {
938 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
939 }
940 if (appData.size()) {
941 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
942 }
943 result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
944 if (!result->resultCode.isOk()) {
945 return;
946 }
947
948 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
949
950 result->resultCode = KS_HANDLE_HIDL_ERROR(
951 dev->exportKey(format, upgradedHidlKeyBlob, clientId, appData, hidlCb));
952 if (!result->resultCode.isOk()) {
953 return;
954 }
955 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700956}
957
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000958static inline void addAuthTokenToParams(AuthorizationSet* params, const HardwareAuthToken* token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100959 if (token) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000960 params->push_back(TAG_AUTH_TOKEN, authToken2HidlVec(*token));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100961 }
962}
963
964void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, KeyPurpose purpose,
965 bool pruneable, const hidl_vec<KeyParameter>& params,
966 const hidl_vec<uint8_t>& entropy, int32_t uid,
967 OperationResult* result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700968 uid_t callingUid = IPCThreadState::self()->getCallingUid();
969 uid_t targetUid = getEffectiveUid(uid);
970 if (!is_granted_to(callingUid, targetUid)) {
971 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100972 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700973 return;
974 }
975 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
976 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100977 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700978 return;
979 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100980 if (!checkAllowedOperationParams(params)) {
981 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700982 return;
983 }
984 Blob keyBlob;
985 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100986 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Shawn Willdend5a24e62017-02-28 13:53:24 -0700987 if (result->resultCode == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
988 result->resultCode = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
989 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100990 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700991 return;
992 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100993
994 auto key = blob2hidlVec(keyBlob);
995 auto& dev = mKeyStore->getDevice(keyBlob);
996 AuthorizationSet opParams = params;
997 KeyCharacteristics characteristics;
998 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
999
1000 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1001 result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
1002 if (!result->resultCode.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001003 return;
1004 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001005 key = blob2hidlVec(keyBlob);
1006 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
Shawn Willden98c59162016-03-20 09:10:18 -06001007 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001008 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001009 return;
1010 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001011
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001012 const HardwareAuthToken* authToken = NULL;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001013
1014 // Merge these characteristics with the ones cached when the key was generated or imported
1015 Blob charBlob;
1016 AuthorizationSet persistedCharacteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001017 result->resultCode =
1018 mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
1019 if (result->resultCode.isOk()) {
1020 // TODO write one shot stream buffer to avoid copying (twice here)
1021 std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
1022 charBlob.getLength());
1023 std::stringstream charStream(charBuffer);
1024 persistedCharacteristics.Deserialize(&charStream);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001025 } else {
1026 ALOGD("Unable to read cached characteristics for key");
1027 }
1028
1029 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001030 AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
1031 AuthorizationSet teeEnforced = characteristics.teeEnforced;
1032 persistedCharacteristics.Union(softwareEnforced);
1033 persistedCharacteristics.Subtract(teeEnforced);
1034 characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001035
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001036 result->resultCode = getAuthToken(characteristics, 0, purpose, &authToken,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001037 /*failOnTokenMissing*/ false);
1038 // If per-operation auth is needed we need to begin the operation and
1039 // the client will need to authorize that operation before calling
1040 // update. Any other auth issues stop here.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001041 if (!result->resultCode.isOk() && result->resultCode != ResponseCode::OP_AUTH_NEEDED) return;
1042
1043 addAuthTokenToParams(&opParams, authToken);
1044
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001045 // Add entropy to the device first.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001046 if (entropy.size()) {
1047 result->resultCode = addRngEntropy(entropy);
1048 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001049 return;
1050 }
1051 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001052
1053 // Create a keyid for this key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001054 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001055 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
1056 ALOGE("Failed to create a key ID for authorization checking.");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001057 result->resultCode = ErrorCode::UNKNOWN_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001058 return;
1059 }
1060
1061 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001062 AuthorizationSet key_auths = characteristics.teeEnforced;
1063 key_auths.append(&characteristics.softwareEnforced[0],
1064 &characteristics.softwareEnforced[characteristics.softwareEnforced.size()]);
1065
1066 result->resultCode = enforcement_policy.AuthorizeOperation(
1067 purpose, keyid, key_auths, opParams, 0 /* op_handle */, true /* is_begin_operation */);
1068 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001069 return;
1070 }
1071
Shawn Willdene2a7b522017-04-11 09:27:40 -06001072 // If there are more than kMaxOperations, abort the oldest operation that was started as
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001073 // pruneable.
Shawn Willdene2a7b522017-04-11 09:27:40 -06001074 while (mOperationMap.getOperationCount() >= kMaxOperations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001075 ALOGD("Reached or exceeded concurrent operations limit");
1076 if (!pruneOperation()) {
1077 break;
1078 }
1079 }
1080
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001081 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1082 uint64_t operationHandle) {
1083 result->resultCode = ret;
1084 if (!result->resultCode.isOk()) {
1085 return;
1086 }
1087 result->handle = operationHandle;
1088 result->outParams = outParams;
1089 };
1090
1091 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
1092 if (rc != ErrorCode::OK) {
1093 ALOGW("Got error %d from begin()", rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001094 }
1095
1096 // If there are too many operations abort the oldest operation that was
1097 // started as pruneable and try again.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001098 while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1099 ALOGW("Ran out of operation handles");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001100 if (!pruneOperation()) {
1101 break;
1102 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001103 rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001104 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001105 if (rc != ErrorCode::OK) {
1106 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001107 return;
1108 }
1109
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001110 // Note: The operation map takes possession of the contents of "characteristics".
1111 // It is safe to use characteristics after the following line but it will be empty.
1112 sp<IBinder> operationToken = mOperationMap.addOperation(
1113 result->handle, keyid, purpose, dev, appToken, std::move(characteristics), pruneable);
1114 assert(characteristics.teeEnforced.size() == 0);
1115 assert(characteristics.softwareEnforced.size() == 0);
1116
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001117 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001118 mOperationMap.setOperationAuthToken(operationToken, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001119 }
1120 // Return the authentication lookup result. If this is a per operation
1121 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1122 // application should get an auth token using the handle before the
1123 // first call to update, which will fail if keystore hasn't received the
1124 // auth token.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001125 // All fields but "token" were set in the begin operation's callback.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001126 result->token = operationToken;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001127}
1128
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001129void KeyStoreService::update(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1130 const hidl_vec<uint8_t>& data, OperationResult* result) {
1131 if (!checkAllowedOperationParams(params)) {
1132 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001133 return;
1134 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001135 km_device_t dev;
1136 uint64_t handle;
1137 KeyPurpose purpose;
1138 km_id_t keyid;
1139 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001140 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001141 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001142 return;
1143 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001144 AuthorizationSet opParams = params;
1145 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1146 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001147 return;
1148 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001149
1150 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001151 AuthorizationSet key_auths(characteristics->teeEnforced);
1152 key_auths.append(&characteristics->softwareEnforced[0],
1153 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001154 result->resultCode = enforcement_policy.AuthorizeOperation(
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001155 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1156 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001157 return;
1158 }
1159
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001160 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
1161 const hidl_vec<KeyParameter>& outParams, const hidl_vec<uint8_t>& output) {
1162 result->resultCode = ret;
1163 if (!result->resultCode.isOk()) {
1164 return;
1165 }
1166 result->inputConsumed = inputConsumed;
1167 result->outParams = outParams;
1168 result->data = output;
1169 };
1170
Janis Danisevskisb0245ee2017-01-25 15:43:01 +00001171 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->update(handle, opParams.hidl_data(),
1172 data, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001173 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1174 // it if there was a communication error indicated by the ErrorCode.
1175 if (!rc.isOk()) {
1176 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001177 }
1178}
1179
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001180void KeyStoreService::finish(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1181 const hidl_vec<uint8_t>& signature, const hidl_vec<uint8_t>& entropy,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001182 OperationResult* result) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001183 if (!checkAllowedOperationParams(params)) {
1184 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001185 return;
1186 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001187 km_device_t dev;
1188 uint64_t handle;
1189 KeyPurpose purpose;
1190 km_id_t keyid;
1191 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001192 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001193 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001194 return;
1195 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001196 AuthorizationSet opParams = params;
1197 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1198 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001199 return;
1200 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001201
1202 if (entropy.size()) {
1203 result->resultCode = addRngEntropy(entropy);
1204 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001205 return;
1206 }
1207 }
1208
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001209 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001210 AuthorizationSet key_auths(characteristics->teeEnforced);
1211 key_auths.append(&characteristics->softwareEnforced[0],
1212 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
1213 result->resultCode = enforcement_policy.AuthorizeOperation(
1214 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1215 if (!result->resultCode.isOk()) return;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001216
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001217 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1218 const hidl_vec<uint8_t>& output) {
1219 result->resultCode = ret;
1220 if (!result->resultCode.isOk()) {
1221 return;
1222 }
1223 result->outParams = outParams;
1224 result->data = output;
1225 };
1226
1227 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->finish(
1228 handle, opParams.hidl_data(),
1229 hidl_vec<uint8_t>() /* TODO(swillden): wire up input to finish() */, signature, hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001230 // Remove the operation regardless of the result
1231 mOperationMap.removeOperation(token);
1232 mAuthTokenTable.MarkCompleted(handle);
1233
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001234 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1235 // it if there was a communication error indicated by the ErrorCode.
1236 if (!rc.isOk()) {
1237 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001238 }
1239}
1240
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001241KeyStoreServiceReturnCode KeyStoreService::abort(const sp<IBinder>& token) {
1242 km_device_t dev;
1243 uint64_t handle;
1244 KeyPurpose purpose;
1245 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001246 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001247 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001248 }
1249 mOperationMap.removeOperation(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001250
1251 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->abort(handle));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001252 mAuthTokenTable.MarkCompleted(handle);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001253 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001254}
1255
1256bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001257 km_device_t dev;
1258 uint64_t handle;
1259 const KeyCharacteristics* characteristics;
1260 KeyPurpose purpose;
1261 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001262 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1263 return false;
1264 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001265 const HardwareAuthToken* authToken = NULL;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001266 mOperationMap.getOperationAuthToken(token, &authToken);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001267 AuthorizationSet ignored;
1268 auto authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1269 return authResult.isOk();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001270}
1271
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001272KeyStoreServiceReturnCode KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001273 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1274 // receive a HardwareAuthToken, rather than an opaque byte array.
1275
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001276 if (!checkBinderPermission(P_ADD_AUTH)) {
1277 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001278 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001279 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001280 if (length != sizeof(hw_auth_token_t)) {
1281 return ErrorCode::INVALID_ARGUMENT;
1282 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001283
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001284 hw_auth_token_t authToken;
1285 memcpy(reinterpret_cast<void*>(&authToken), token, sizeof(hw_auth_token_t));
1286 if (authToken.version != 0) {
1287 return ErrorCode::INVALID_ARGUMENT;
1288 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001289
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001290 std::unique_ptr<HardwareAuthToken> hidlAuthToken(new HardwareAuthToken);
1291 hidlAuthToken->challenge = authToken.challenge;
1292 hidlAuthToken->userId = authToken.user_id;
1293 hidlAuthToken->authenticatorId = authToken.authenticator_id;
1294 hidlAuthToken->authenticatorType = authToken.authenticator_type;
1295 hidlAuthToken->timestamp = authToken.timestamp;
1296 static_assert(
1297 std::is_same<decltype(hidlAuthToken->hmac),
1298 ::android::hardware::hidl_array<uint8_t, sizeof(authToken.hmac)>>::value,
1299 "This function assumes token HMAC is 32 bytes, but it might not be.");
1300 std::copy(authToken.hmac, authToken.hmac + sizeof(authToken.hmac), hidlAuthToken->hmac.data());
1301
1302 // The table takes ownership of authToken.
1303 mAuthTokenTable.AddAuthenticationToken(hidlAuthToken.release());
1304 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001305}
1306
Janis Danisevskis7612fd42016-09-01 11:50:02 +01001307constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
1308
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001309bool isDeviceIdAttestationRequested(const hidl_vec<KeyParameter>& params) {
1310 for (size_t i = 0; i < params.size(); ++i) {
1311 switch (params[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -06001312 case Tag::ATTESTATION_ID_BRAND:
1313 case Tag::ATTESTATION_ID_DEVICE:
1314 case Tag::ATTESTATION_ID_IMEI:
1315 case Tag::ATTESTATION_ID_MANUFACTURER:
1316 case Tag::ATTESTATION_ID_MEID:
1317 case Tag::ATTESTATION_ID_MODEL:
1318 case Tag::ATTESTATION_ID_PRODUCT:
1319 case Tag::ATTESTATION_ID_SERIAL:
1320 return true;
1321 default:
1322 break;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001323 }
1324 }
1325 return false;
1326}
1327
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001328KeyStoreServiceReturnCode KeyStoreService::attestKey(const String16& name,
1329 const hidl_vec<KeyParameter>& params,
1330 hidl_vec<hidl_vec<uint8_t>>* outChain) {
1331 if (!outChain) {
1332 return ErrorCode::OUTPUT_PARAMETER_NULL;
1333 }
Shawn Willden50eb1b22016-01-21 12:41:23 -07001334
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001335 if (!checkAllowedOperationParams(params)) {
1336 return ErrorCode::INVALID_ARGUMENT;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001337 }
1338
1339 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1340
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001341 bool attestingDeviceIds = isDeviceIdAttestationRequested(params);
1342 if (attestingDeviceIds) {
1343 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1344 if (binder == 0) {
1345 return ErrorCode::CANNOT_ATTEST_IDS;
1346 }
1347 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1348 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1349 IPCThreadState::self()->getCallingPid(), callingUid)) {
Shawn Willdene2a7b522017-04-11 09:27:40 -06001350 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001351 }
1352 }
1353
Shawn Willdene2a7b522017-04-11 09:27:40 -06001354 AuthorizationSet mutableParams = params;
1355
1356 KeyStoreServiceReturnCode responseCode;
1357 bool factoryResetSinceIdRotation;
1358 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
1359
1360 if (!responseCode.isOk()) return responseCode;
1361 if (factoryResetSinceIdRotation) mutableParams.push_back(TAG_RESET_SINCE_ID_ROTATION);
1362
Shawn Willden50eb1b22016-01-21 12:41:23 -07001363 Blob keyBlob;
1364 String8 name8(name);
Shawn Willdene2a7b522017-04-11 09:27:40 -06001365 responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001366 if (!responseCode.isOk()) {
Shawn Willden50eb1b22016-01-21 12:41:23 -07001367 return responseCode;
1368 }
1369
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001370 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
Janis Danisevskis011675d2016-09-01 11:41:29 +01001371 if (!asn1_attestation_id_result.isOk()) {
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001372 ALOGE("failed to gather attestation_id");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001373 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001374 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001375 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001376
1377 /*
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001378 * The attestation application ID cannot be longer than
1379 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, so we truncate if too long.
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001380 */
Shawn Willdene2a7b522017-04-11 09:27:40 -06001381 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001382 asn1_attestation_id.resize(KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE);
Shawn Willdene2a7b522017-04-11 09:27:40 -06001383 }
Shawn Willden50eb1b22016-01-21 12:41:23 -07001384
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001385 mutableParams.push_back(TAG_ATTESTATION_APPLICATION_ID, blob2hidlVec(asn1_attestation_id));
1386
1387 KeyStoreServiceReturnCode error;
1388 auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1389 error = ret;
1390 if (!error.isOk()) {
1391 return;
1392 }
1393 if (outChain) *outChain = certChain;
1394 };
1395
1396 auto hidlKey = blob2hidlVec(keyBlob);
1397 auto& dev = mKeyStore->getDevice(keyBlob);
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001398 KeyStoreServiceReturnCode attestationRc =
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001399 KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001400
1401 KeyStoreServiceReturnCode deletionRc;
1402 if (attestingDeviceIds) {
1403 // When performing device id attestation, treat the key as ephemeral and delete it straight
1404 // away.
1405 deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001406 }
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001407
1408 if (!attestationRc.isOk()) {
1409 return attestationRc;
1410 }
1411 if (!error.isOk()) {
1412 return error;
1413 }
1414 return deletionRc;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001415}
1416
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001417KeyStoreServiceReturnCode KeyStoreService::onDeviceOffBody() {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001418 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1419 mAuthTokenTable.onDeviceOffBody();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001420 return ResponseCode::NO_ERROR;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001421}
1422
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001423/**
1424 * Prune the oldest pruneable operation.
1425 */
1426bool KeyStoreService::pruneOperation() {
1427 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1428 ALOGD("Trying to prune operation %p", oldest.get());
1429 size_t op_count_before_abort = mOperationMap.getOperationCount();
1430 // We mostly ignore errors from abort() because all we care about is whether at least
1431 // one operation has been removed.
1432 int abort_error = abort(oldest);
1433 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1434 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1435 return false;
1436 }
1437 return true;
1438}
1439
1440/**
1441 * Get the effective target uid for a binder operation that takes an
1442 * optional uid as the target.
1443 */
1444uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1445 if (targetUid == UID_SELF) {
1446 return IPCThreadState::self()->getCallingUid();
1447 }
1448 return static_cast<uid_t>(targetUid);
1449}
1450
1451/**
1452 * Check if the caller of the current binder method has the required
1453 * permission and if acting on other uids the grants to do so.
1454 */
1455bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1456 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1457 pid_t spid = IPCThreadState::self()->getCallingPid();
1458 if (!has_permission(callingUid, permission, spid)) {
1459 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1460 return false;
1461 }
1462 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1463 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1464 return false;
1465 }
1466 return true;
1467}
1468
1469/**
1470 * Check if the caller of the current binder method has the required
1471 * permission and the target uid is the caller or the caller is system.
1472 */
1473bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1474 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1475 pid_t spid = IPCThreadState::self()->getCallingPid();
1476 if (!has_permission(callingUid, permission, spid)) {
1477 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1478 return false;
1479 }
1480 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1481}
1482
1483/**
1484 * Check if the caller of the current binder method has the required
1485 * permission or the target of the operation is the caller's uid. This is
1486 * for operation where the permission is only for cross-uid activity and all
1487 * uids are allowed to act on their own (ie: clearing all entries for a
1488 * given uid).
1489 */
1490bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1491 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1492 if (getEffectiveUid(targetUid) == callingUid) {
1493 return true;
1494 } else {
1495 return checkBinderPermission(permission, targetUid);
1496 }
1497}
1498
1499/**
1500 * Helper method to check that the caller has the required permission as
1501 * well as the keystore is in the unlocked state if checkUnlocked is true.
1502 *
1503 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1504 * otherwise the state of keystore when not unlocked and checkUnlocked is
1505 * true.
1506 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001507KeyStoreServiceReturnCode
1508KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1509 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001510 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001511 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001512 }
1513 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1514 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001515 // All State values coincide with ResponseCodes
1516 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001517 }
1518
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001519 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001520}
1521
1522bool KeyStoreService::isKeystoreUnlocked(State state) {
1523 switch (state) {
1524 case ::STATE_NO_ERROR:
1525 return true;
1526 case ::STATE_UNINITIALIZED:
1527 case ::STATE_LOCKED:
1528 return false;
1529 }
1530 return false;
1531}
1532
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001533/**
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001534 * Check that all KeyParameter's provided by the application are
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001535 * allowed. Any parameter that keystore adds itself should be disallowed here.
1536 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001537bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1538 for (size_t i = 0; i < params.size(); ++i) {
1539 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001540 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001541 case Tag::AUTH_TOKEN:
1542 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001543 return false;
1544 default:
1545 break;
1546 }
1547 }
1548 return true;
1549}
1550
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001551ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
1552 km_device_t* dev,
1553 const AuthorizationSet& params,
1554 KeyCharacteristics* out) {
1555 hidl_vec<uint8_t> appId;
1556 hidl_vec<uint8_t> appData;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001557 for (auto param : params) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001558 if (param.tag == Tag::APPLICATION_ID) {
1559 appId = authorizationValue(TAG_APPLICATION_ID, param).value();
1560 } else if (param.tag == Tag::APPLICATION_DATA) {
1561 appData = authorizationValue(TAG_APPLICATION_DATA, param).value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001562 }
1563 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001564 ErrorCode error = ErrorCode::OK;
1565
1566 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
1567 error = ret;
1568 if (error != ErrorCode::OK) {
1569 return;
1570 }
1571 if (out) *out = keyCharacteristics;
1572 };
1573
1574 ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appData, hidlCb));
1575 if (rc != ErrorCode::OK) {
1576 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001577 }
1578 return error;
1579}
1580
1581/**
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001582 * Get the auth token for this operation from the auth token table.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001583 *
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001584 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
1585 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1586 * authorization token exists for that operation and
1587 * failOnTokenMissing is false.
1588 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1589 * token for the operation
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001590 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001591KeyStoreServiceReturnCode KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics,
1592 uint64_t handle, KeyPurpose purpose,
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001593 const HardwareAuthToken** authToken,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001594 bool failOnTokenMissing) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001595
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001596 AuthorizationSet allCharacteristics;
1597 for (size_t i = 0; i < characteristics.softwareEnforced.size(); i++) {
1598 allCharacteristics.push_back(characteristics.softwareEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001599 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001600 for (size_t i = 0; i < characteristics.teeEnforced.size(); i++) {
1601 allCharacteristics.push_back(characteristics.teeEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001602 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001603 AuthTokenTable::Error err =
1604 mAuthTokenTable.FindAuthorization(allCharacteristics, purpose, handle, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001605 switch (err) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001606 case AuthTokenTable::OK:
1607 case AuthTokenTable::AUTH_NOT_REQUIRED:
1608 return ResponseCode::NO_ERROR;
1609 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1610 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
1611 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
1612 return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1613 case AuthTokenTable::OP_HANDLE_REQUIRED:
1614 return failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
1615 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001616 default:
1617 ALOGE("Unexpected FindAuthorization return value %d", err);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001618 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001619 }
1620}
1621
1622/**
1623 * Add the auth token for the operation to the param list if the operation
1624 * requires authorization. Uses the cached result in the OperationMap if available
1625 * otherwise gets the token from the AuthTokenTable and caches the result.
1626 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001627 * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001628 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1629 * authenticated.
1630 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1631 * operation token.
1632 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001633KeyStoreServiceReturnCode KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
1634 AuthorizationSet* params) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001635 const HardwareAuthToken* authToken = nullptr;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001636 mOperationMap.getOperationAuthToken(token, &authToken);
1637 if (!authToken) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001638 km_device_t dev;
1639 uint64_t handle;
1640 const KeyCharacteristics* characteristics = nullptr;
1641 KeyPurpose purpose;
1642 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001643 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001644 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001645 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001646 auto result = getAuthToken(*characteristics, handle, purpose, &authToken);
1647 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001648 return result;
1649 }
1650 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001651 mOperationMap.setOperationAuthToken(token, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001652 }
1653 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001654 addAuthTokenToParams(params, authToken);
1655 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001656}
1657
1658/**
1659 * Translate a result value to a legacy return value. All keystore errors are
1660 * preserved and keymaster errors become SYSTEM_ERRORs
1661 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001662KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001663 if (result > 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001664 return static_cast<ResponseCode>(result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001665 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001666 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001667}
1668
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001669static NullOr<const Algorithm&>
1670getKeyAlgoritmFromKeyCharacteristics(const KeyCharacteristics& characteristics) {
1671 for (size_t i = 0; i < characteristics.teeEnforced.size(); ++i) {
1672 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.teeEnforced[i]);
1673 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001674 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001675 for (size_t i = 0; i < characteristics.softwareEnforced.size(); ++i) {
1676 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.softwareEnforced[i]);
1677 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001678 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001679 return {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001680}
1681
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001682void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001683 // All legacy keys are DIGEST_NONE/PAD_NONE.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001684 params->push_back(TAG_DIGEST, Digest::NONE);
1685 params->push_back(TAG_PADDING, PaddingMode::NONE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001686
1687 // Look up the algorithm of the key.
1688 KeyCharacteristics characteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001689 auto rc = getKeyCharacteristics(name, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF,
1690 &characteristics);
1691 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001692 ALOGE("Failed to get key characteristics");
1693 return;
1694 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001695 auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
1696 if (!algorithm.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001697 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1698 return;
1699 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001700 params->push_back(TAG_ALGORITHM, algorithm.value());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001701}
1702
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001703KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
1704 const hidl_vec<uint8_t>& data,
1705 hidl_vec<uint8_t>* out,
1706 const hidl_vec<uint8_t>& signature,
1707 KeyPurpose purpose) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001708
1709 std::basic_stringstream<uint8_t> outBuffer;
1710 OperationResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001711 AuthorizationSet inArgs;
1712 addLegacyBeginParams(name, &inArgs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001713 sp<IBinder> appToken(new BBinder);
1714 sp<IBinder> token;
1715
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001716 begin(appToken, name, purpose, true, inArgs.hidl_data(), hidl_vec<uint8_t>(), UID_SELF,
1717 &result);
1718 if (!result.resultCode.isOk()) {
1719 if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001720 ALOGW("Key not found");
1721 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001722 ALOGW("Error in begin: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001723 }
1724 return translateResultToLegacyResult(result.resultCode);
1725 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001726 inArgs.Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001727 token = result.token;
1728 size_t consumed = 0;
1729 size_t lastConsumed = 0;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001730 hidl_vec<uint8_t> data_view;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001731 do {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001732 data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
1733 update(token, inArgs.hidl_data(), data_view, &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001734 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001735 ALOGW("Error in update: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001736 return translateResultToLegacyResult(result.resultCode);
1737 }
1738 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001739 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001740 }
1741 lastConsumed = result.inputConsumed;
1742 consumed += lastConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001743 } while (consumed < data.size() && lastConsumed > 0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001744
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001745 if (consumed != data.size()) {
1746 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
1747 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001748 }
1749
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001750 finish(token, inArgs.hidl_data(), signature, hidl_vec<uint8_t>(), &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001751 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001752 ALOGW("Error in finish: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001753 return translateResultToLegacyResult(result.resultCode);
1754 }
1755 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001756 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001757 }
1758
1759 if (out) {
1760 auto buf = outBuffer.str();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001761 out->resize(buf.size());
1762 memcpy(&(*out)[0], buf.data(), out->size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001763 }
1764
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001765 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001766}
1767
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001768KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
1769 const AuthorizationSet& params,
1770 Blob* blob) {
Shawn Willden98c59162016-03-20 09:10:18 -06001771 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
1772 String8 name8(name);
1773 ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001774 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willden98c59162016-03-20 09:10:18 -06001775 return responseCode;
1776 }
Rubin Xu7675c9f2017-03-15 19:26:52 +00001777 ALOGI("upgradeKeyBlob %s %d", name8.string(), uid);
Shawn Willden98c59162016-03-20 09:10:18 -06001778
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001779 auto hidlKey = blob2hidlVec(*blob);
1780 auto& dev = mKeyStore->getDevice(*blob);
Shawn Willden98c59162016-03-20 09:10:18 -06001781
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001782 KeyStoreServiceReturnCode error;
1783 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
1784 error = ret;
1785 if (!error.isOk()) {
1786 return;
1787 }
1788
1789 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1790 error = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(uid));
1791 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001792 ALOGI("upgradeKeyBlob keystore->del failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001793 return;
1794 }
1795
1796 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
1797 0 /* infoLength */, ::TYPE_KEYMASTER_10);
1798 newBlob.setFallback(blob->isFallback());
1799 newBlob.setEncrypted(blob->isEncrypted());
Rubin Xu67899de2017-04-21 19:15:13 +01001800 newBlob.setSuperEncrypted(blob->isSuperEncrypted());
1801 newBlob.setCriticalToDeviceEncryption(blob->isCriticalToDeviceEncryption());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001802
1803 error = mKeyStore->put(filename.string(), &newBlob, get_user_id(uid));
1804 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001805 ALOGI("upgradeKeyBlob keystore->put failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001806 return;
1807 }
1808
1809 // Re-read blob for caller. We can't use newBlob because writing it modified it.
1810 error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1811 };
1812
1813 KeyStoreServiceReturnCode rc =
1814 KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
1815 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001816 return rc;
1817 }
1818
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001819 return error;
Shawn Willden98c59162016-03-20 09:10:18 -06001820}
1821
Shawn Willdene2a7b522017-04-11 09:27:40 -06001822} // namespace keystore