blob: caf0655d0f753a4083ddbad78abb5e25c3dc8274 [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));
Rubin Xu85c85e92017-04-26 20:07:30 +0100635
636 if (get_app_id(targetUid) == AID_SYSTEM) {
637 Blob keyBlob;
638 ResponseCode responseCode =
639 mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, get_user_id(targetUid));
640 if (responseCode == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
641 // Do not clear keys critical to device encryption under system uid.
642 continue;
643 }
644 }
645
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700646 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400647
648 // del() will fail silently if no cached characteristics are present for this alias.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100649 String8 chr_filename(
650 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400651 mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700652 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100653 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700654}
655
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100656KeyStoreServiceReturnCode KeyStoreService::addRngEntropy(const hidl_vec<uint8_t>& entropy) {
657 const auto& device = mKeyStore->getDevice();
658 return KS_HANDLE_HIDL_ERROR(device->addRngEntropy(entropy));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700659}
660
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100661KeyStoreServiceReturnCode KeyStoreService::generateKey(const String16& name,
662 const hidl_vec<KeyParameter>& params,
663 const hidl_vec<uint8_t>& entropy, int uid,
664 int flags,
665 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700666 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100667 KeyStoreServiceReturnCode rc =
668 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
669 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700670 return rc;
671 }
Rubin Xu67899de2017-04-21 19:15:13 +0100672 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
673 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
674 return ResponseCode::PERMISSION_DENIED;
675 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700676
Shawn Willdene2a7b522017-04-11 09:27:40 -0600677 if (containsTag(params, Tag::INCLUDE_UNIQUE_ID)) {
678 if (!checkBinderPermission(P_GEN_UNIQUE_ID)) return ResponseCode::PERMISSION_DENIED;
679 }
680
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100681 bool usingFallback = false;
682 auto& dev = mKeyStore->getDevice();
683 AuthorizationSet keyCharacteristics = params;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400684
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700685 // TODO: Seed from Linux RNG before this.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100686 rc = addRngEntropy(entropy);
687 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700688 return rc;
689 }
690
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100691 KeyStoreServiceReturnCode error;
692 auto hidl_cb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
693 const KeyCharacteristics& keyCharacteristics) {
694 error = ret;
695 if (!error.isOk()) {
696 return;
697 }
698 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700699
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100700 // Write the key
701 String8 name8(name);
702 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700703
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100704 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
705 keyBlob.setFallback(usingFallback);
Rubin Xu67899de2017-04-21 19:15:13 +0100706 keyBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
707 if (isAuthenticationBound(params) && !keyBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -0700708 keyBlob.setSuperEncrypted(true);
709 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100710 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700711
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100712 error = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
713 };
714
715 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(params, hidl_cb));
716 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400717 return rc;
718 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100719 if (!error.isOk()) {
720 ALOGE("Failed to generate key -> falling back to software keymaster");
721 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000722 auto fallback = mKeyStore->getFallbackDevice();
723 if (!fallback.isOk()) {
724 return error;
725 }
726 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->generateKey(params, hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100727 if (!rc.isOk()) {
728 return rc;
729 }
730 if (!error.isOk()) {
731 return error;
732 }
733 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400734
735 // Write the characteristics:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100736 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400737 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
738
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100739 std::stringstream kc_stream;
740 keyCharacteristics.Serialize(&kc_stream);
741 if (kc_stream.bad()) {
742 return ResponseCode::SYSTEM_ERROR;
743 }
744 auto kc_buf = kc_stream.str();
745 Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
746 ::TYPE_KEY_CHARACTERISTICS);
747 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400748 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
749
750 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700751}
752
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100753KeyStoreServiceReturnCode
754KeyStoreService::getKeyCharacteristics(const String16& name, const hidl_vec<uint8_t>& clientId,
755 const hidl_vec<uint8_t>& appData, int32_t uid,
756 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700757 if (!outCharacteristics) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100758 return ErrorCode::UNEXPECTED_NULL_POINTER;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700759 }
760
761 uid_t targetUid = getEffectiveUid(uid);
762 uid_t callingUid = IPCThreadState::self()->getCallingUid();
763 if (!is_granted_to(callingUid, targetUid)) {
764 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
765 targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100766 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700767 }
768
769 Blob keyBlob;
770 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700771
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100772 KeyStoreServiceReturnCode rc =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700773 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100774 if (!rc.isOk()) {
775 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700776 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100777
778 auto hidlKeyBlob = blob2hidlVec(keyBlob);
779 auto& dev = mKeyStore->getDevice(keyBlob);
780
781 KeyStoreServiceReturnCode error;
782
783 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
784 error = ret;
785 if (!error.isOk()) {
786 return;
Shawn Willden98c59162016-03-20 09:10:18 -0600787 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100788 *outCharacteristics = keyCharacteristics;
789 };
790
791 rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(hidlKeyBlob, clientId, appData, hidlCb));
792 if (!rc.isOk()) {
793 return rc;
794 }
795
796 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
797 AuthorizationSet upgradeParams;
798 if (clientId.size()) {
799 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
800 }
801 if (appData.size()) {
802 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
Shawn Willden98c59162016-03-20 09:10:18 -0600803 }
804 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100805 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -0600806 return rc;
807 }
Shawn Willden715d0232016-01-21 00:45:13 -0700808
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100809 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
810
811 rc = KS_HANDLE_HIDL_ERROR(
812 dev->getKeyCharacteristics(upgradedHidlKeyBlob, clientId, appData, hidlCb));
813 if (!rc.isOk()) {
814 return rc;
815 }
816 // Note that, on success, "error" will have been updated by the hidlCB callback.
817 // So it is fine to return "error" below.
818 }
819 return error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700820}
821
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100822KeyStoreServiceReturnCode
823KeyStoreService::importKey(const String16& name, const hidl_vec<KeyParameter>& params,
824 KeyFormat format, const hidl_vec<uint8_t>& keyData, int uid, int flags,
825 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700826 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100827 KeyStoreServiceReturnCode rc =
828 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
829 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700830 return rc;
831 }
Rubin Xu67899de2017-04-21 19:15:13 +0100832 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
833 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
834 return ResponseCode::PERMISSION_DENIED;
835 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700836
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100837 bool usingFallback = false;
838 auto& dev = mKeyStore->getDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700839
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700840 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700841
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100842 KeyStoreServiceReturnCode error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700843
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100844 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
845 const KeyCharacteristics& keyCharacteristics) {
846 error = ret;
847 if (!error.isOk()) {
848 return;
849 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700850
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100851 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
852
853 // Write the key:
854 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
855
856 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
857 ksBlob.setFallback(usingFallback);
Rubin Xu67899de2017-04-21 19:15:13 +0100858 ksBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
859 if (isAuthenticationBound(params) && !ksBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -0700860 ksBlob.setSuperEncrypted(true);
861 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100862 ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
863
864 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
865 };
866
867 rc = KS_HANDLE_HIDL_ERROR(dev->importKey(params, format, keyData, hidlCb));
868 // possible hidl error
869 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400870 return rc;
871 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100872 // now check error from callback
873 if (!error.isOk()) {
874 ALOGE("Failed to import key -> falling back to software keymaster");
875 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000876 auto fallback = mKeyStore->getFallbackDevice();
877 if (!fallback.isOk()) {
878 return error;
879 }
880 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->importKey(params, format, keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100881 // possible hidl error
882 if (!rc.isOk()) {
883 return rc;
884 }
885 // now check error from callback
886 if (!error.isOk()) {
887 return error;
888 }
889 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400890
891 // Write the characteristics:
892 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
893
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100894 AuthorizationSet opParams = params;
895 std::stringstream kcStream;
896 opParams.Serialize(&kcStream);
897 if (kcStream.bad()) return ResponseCode::SYSTEM_ERROR;
898 auto kcBuf = kcStream.str();
899
900 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
901 ::TYPE_KEY_CHARACTERISTICS);
902 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400903 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
904
905 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700906}
907
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100908void KeyStoreService::exportKey(const String16& name, KeyFormat format,
909 const hidl_vec<uint8_t>& clientId, const hidl_vec<uint8_t>& appData,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700910 int32_t uid, ExportResult* result) {
911
912 uid_t targetUid = getEffectiveUid(uid);
913 uid_t callingUid = IPCThreadState::self()->getCallingUid();
914 if (!is_granted_to(callingUid, targetUid)) {
915 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100916 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700917 return;
918 }
919
920 Blob keyBlob;
921 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700922
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100923 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
924 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700925 return;
926 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100927
928 auto key = blob2hidlVec(keyBlob);
929 auto& dev = mKeyStore->getDevice(keyBlob);
930
931 auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
932 result->resultCode = ret;
933 if (!result->resultCode.isOk()) {
Ji Wang2c142312016-10-14 17:21:10 +0800934 return;
935 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100936 result->exportData = keyMaterial;
937 };
938 KeyStoreServiceReturnCode rc =
939 KS_HANDLE_HIDL_ERROR(dev->exportKey(format, key, clientId, appData, hidlCb));
940 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
941 // callback hidlCb.
942 if (!rc.isOk()) {
943 result->resultCode = rc;
Ji Wang2c142312016-10-14 17:21:10 +0800944 }
945
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100946 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
947 AuthorizationSet upgradeParams;
948 if (clientId.size()) {
949 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
950 }
951 if (appData.size()) {
952 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
953 }
954 result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
955 if (!result->resultCode.isOk()) {
956 return;
957 }
958
959 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
960
961 result->resultCode = KS_HANDLE_HIDL_ERROR(
962 dev->exportKey(format, upgradedHidlKeyBlob, clientId, appData, hidlCb));
963 if (!result->resultCode.isOk()) {
964 return;
965 }
966 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700967}
968
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000969static inline void addAuthTokenToParams(AuthorizationSet* params, const HardwareAuthToken* token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100970 if (token) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000971 params->push_back(TAG_AUTH_TOKEN, authToken2HidlVec(*token));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100972 }
973}
974
975void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, KeyPurpose purpose,
976 bool pruneable, const hidl_vec<KeyParameter>& params,
977 const hidl_vec<uint8_t>& entropy, int32_t uid,
978 OperationResult* result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700979 uid_t callingUid = IPCThreadState::self()->getCallingUid();
980 uid_t targetUid = getEffectiveUid(uid);
981 if (!is_granted_to(callingUid, targetUid)) {
982 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100983 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700984 return;
985 }
986 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
987 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100988 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700989 return;
990 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100991 if (!checkAllowedOperationParams(params)) {
992 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700993 return;
994 }
995 Blob keyBlob;
996 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100997 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Shawn Willdend5a24e62017-02-28 13:53:24 -0700998 if (result->resultCode == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
999 result->resultCode = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1000 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001001 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001002 return;
1003 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001004
1005 auto key = blob2hidlVec(keyBlob);
1006 auto& dev = mKeyStore->getDevice(keyBlob);
1007 AuthorizationSet opParams = params;
1008 KeyCharacteristics characteristics;
1009 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
1010
1011 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1012 result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
1013 if (!result->resultCode.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001014 return;
1015 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001016 key = blob2hidlVec(keyBlob);
1017 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
Shawn Willden98c59162016-03-20 09:10:18 -06001018 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001019 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001020 return;
1021 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001022
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001023 const HardwareAuthToken* authToken = NULL;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001024
1025 // Merge these characteristics with the ones cached when the key was generated or imported
1026 Blob charBlob;
1027 AuthorizationSet persistedCharacteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001028 result->resultCode =
1029 mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
1030 if (result->resultCode.isOk()) {
1031 // TODO write one shot stream buffer to avoid copying (twice here)
1032 std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
1033 charBlob.getLength());
1034 std::stringstream charStream(charBuffer);
1035 persistedCharacteristics.Deserialize(&charStream);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001036 } else {
1037 ALOGD("Unable to read cached characteristics for key");
1038 }
1039
1040 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001041 AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
1042 AuthorizationSet teeEnforced = characteristics.teeEnforced;
1043 persistedCharacteristics.Union(softwareEnforced);
1044 persistedCharacteristics.Subtract(teeEnforced);
1045 characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001046
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001047 result->resultCode = getAuthToken(characteristics, 0, purpose, &authToken,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001048 /*failOnTokenMissing*/ false);
1049 // If per-operation auth is needed we need to begin the operation and
1050 // the client will need to authorize that operation before calling
1051 // update. Any other auth issues stop here.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001052 if (!result->resultCode.isOk() && result->resultCode != ResponseCode::OP_AUTH_NEEDED) return;
1053
1054 addAuthTokenToParams(&opParams, authToken);
1055
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001056 // Add entropy to the device first.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001057 if (entropy.size()) {
1058 result->resultCode = addRngEntropy(entropy);
1059 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001060 return;
1061 }
1062 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001063
1064 // Create a keyid for this key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001065 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001066 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
1067 ALOGE("Failed to create a key ID for authorization checking.");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001068 result->resultCode = ErrorCode::UNKNOWN_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001069 return;
1070 }
1071
1072 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001073 AuthorizationSet key_auths = characteristics.teeEnforced;
1074 key_auths.append(&characteristics.softwareEnforced[0],
1075 &characteristics.softwareEnforced[characteristics.softwareEnforced.size()]);
1076
1077 result->resultCode = enforcement_policy.AuthorizeOperation(
1078 purpose, keyid, key_auths, opParams, 0 /* op_handle */, true /* is_begin_operation */);
1079 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001080 return;
1081 }
1082
Shawn Willdene2a7b522017-04-11 09:27:40 -06001083 // If there are more than kMaxOperations, abort the oldest operation that was started as
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001084 // pruneable.
Shawn Willdene2a7b522017-04-11 09:27:40 -06001085 while (mOperationMap.getOperationCount() >= kMaxOperations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001086 ALOGD("Reached or exceeded concurrent operations limit");
1087 if (!pruneOperation()) {
1088 break;
1089 }
1090 }
1091
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001092 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1093 uint64_t operationHandle) {
1094 result->resultCode = ret;
1095 if (!result->resultCode.isOk()) {
1096 return;
1097 }
1098 result->handle = operationHandle;
1099 result->outParams = outParams;
1100 };
1101
1102 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
1103 if (rc != ErrorCode::OK) {
1104 ALOGW("Got error %d from begin()", rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001105 }
1106
1107 // If there are too many operations abort the oldest operation that was
1108 // started as pruneable and try again.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001109 while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1110 ALOGW("Ran out of operation handles");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001111 if (!pruneOperation()) {
1112 break;
1113 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001114 rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001115 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001116 if (rc != ErrorCode::OK) {
1117 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001118 return;
1119 }
1120
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001121 // Note: The operation map takes possession of the contents of "characteristics".
1122 // It is safe to use characteristics after the following line but it will be empty.
1123 sp<IBinder> operationToken = mOperationMap.addOperation(
1124 result->handle, keyid, purpose, dev, appToken, std::move(characteristics), pruneable);
1125 assert(characteristics.teeEnforced.size() == 0);
1126 assert(characteristics.softwareEnforced.size() == 0);
1127
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001128 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001129 mOperationMap.setOperationAuthToken(operationToken, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001130 }
1131 // Return the authentication lookup result. If this is a per operation
1132 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1133 // application should get an auth token using the handle before the
1134 // first call to update, which will fail if keystore hasn't received the
1135 // auth token.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001136 // All fields but "token" were set in the begin operation's callback.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001137 result->token = operationToken;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001138}
1139
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001140void KeyStoreService::update(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1141 const hidl_vec<uint8_t>& data, OperationResult* result) {
1142 if (!checkAllowedOperationParams(params)) {
1143 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001144 return;
1145 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001146 km_device_t dev;
1147 uint64_t handle;
1148 KeyPurpose purpose;
1149 km_id_t keyid;
1150 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001151 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001152 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001153 return;
1154 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001155 AuthorizationSet opParams = params;
1156 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1157 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001158 return;
1159 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001160
1161 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001162 AuthorizationSet key_auths(characteristics->teeEnforced);
1163 key_auths.append(&characteristics->softwareEnforced[0],
1164 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001165 result->resultCode = enforcement_policy.AuthorizeOperation(
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001166 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1167 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001168 return;
1169 }
1170
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001171 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
1172 const hidl_vec<KeyParameter>& outParams, const hidl_vec<uint8_t>& output) {
1173 result->resultCode = ret;
1174 if (!result->resultCode.isOk()) {
1175 return;
1176 }
1177 result->inputConsumed = inputConsumed;
1178 result->outParams = outParams;
1179 result->data = output;
1180 };
1181
Janis Danisevskisb0245ee2017-01-25 15:43:01 +00001182 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->update(handle, opParams.hidl_data(),
1183 data, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001184 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1185 // it if there was a communication error indicated by the ErrorCode.
1186 if (!rc.isOk()) {
1187 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001188 }
1189}
1190
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001191void KeyStoreService::finish(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1192 const hidl_vec<uint8_t>& signature, const hidl_vec<uint8_t>& entropy,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001193 OperationResult* result) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001194 if (!checkAllowedOperationParams(params)) {
1195 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001196 return;
1197 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001198 km_device_t dev;
1199 uint64_t handle;
1200 KeyPurpose purpose;
1201 km_id_t keyid;
1202 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001203 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001204 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001205 return;
1206 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001207 AuthorizationSet opParams = params;
1208 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1209 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001210 return;
1211 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001212
1213 if (entropy.size()) {
1214 result->resultCode = addRngEntropy(entropy);
1215 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001216 return;
1217 }
1218 }
1219
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001220 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001221 AuthorizationSet key_auths(characteristics->teeEnforced);
1222 key_auths.append(&characteristics->softwareEnforced[0],
1223 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
1224 result->resultCode = enforcement_policy.AuthorizeOperation(
1225 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1226 if (!result->resultCode.isOk()) return;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001227
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001228 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1229 const hidl_vec<uint8_t>& output) {
1230 result->resultCode = ret;
1231 if (!result->resultCode.isOk()) {
1232 return;
1233 }
1234 result->outParams = outParams;
1235 result->data = output;
1236 };
1237
1238 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->finish(
1239 handle, opParams.hidl_data(),
1240 hidl_vec<uint8_t>() /* TODO(swillden): wire up input to finish() */, signature, hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001241 // Remove the operation regardless of the result
1242 mOperationMap.removeOperation(token);
1243 mAuthTokenTable.MarkCompleted(handle);
1244
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001245 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1246 // it if there was a communication error indicated by the ErrorCode.
1247 if (!rc.isOk()) {
1248 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001249 }
1250}
1251
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001252KeyStoreServiceReturnCode KeyStoreService::abort(const sp<IBinder>& token) {
1253 km_device_t dev;
1254 uint64_t handle;
1255 KeyPurpose purpose;
1256 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001257 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001258 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001259 }
1260 mOperationMap.removeOperation(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001261
1262 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->abort(handle));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001263 mAuthTokenTable.MarkCompleted(handle);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001264 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001265}
1266
1267bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001268 km_device_t dev;
1269 uint64_t handle;
1270 const KeyCharacteristics* characteristics;
1271 KeyPurpose purpose;
1272 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001273 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1274 return false;
1275 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001276 const HardwareAuthToken* authToken = NULL;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001277 mOperationMap.getOperationAuthToken(token, &authToken);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001278 AuthorizationSet ignored;
1279 auto authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1280 return authResult.isOk();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001281}
1282
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001283KeyStoreServiceReturnCode KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001284 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1285 // receive a HardwareAuthToken, rather than an opaque byte array.
1286
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001287 if (!checkBinderPermission(P_ADD_AUTH)) {
1288 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001289 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001290 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001291 if (length != sizeof(hw_auth_token_t)) {
1292 return ErrorCode::INVALID_ARGUMENT;
1293 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001294
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001295 hw_auth_token_t authToken;
1296 memcpy(reinterpret_cast<void*>(&authToken), token, sizeof(hw_auth_token_t));
1297 if (authToken.version != 0) {
1298 return ErrorCode::INVALID_ARGUMENT;
1299 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001300
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001301 std::unique_ptr<HardwareAuthToken> hidlAuthToken(new HardwareAuthToken);
1302 hidlAuthToken->challenge = authToken.challenge;
1303 hidlAuthToken->userId = authToken.user_id;
1304 hidlAuthToken->authenticatorId = authToken.authenticator_id;
1305 hidlAuthToken->authenticatorType = authToken.authenticator_type;
1306 hidlAuthToken->timestamp = authToken.timestamp;
1307 static_assert(
1308 std::is_same<decltype(hidlAuthToken->hmac),
1309 ::android::hardware::hidl_array<uint8_t, sizeof(authToken.hmac)>>::value,
1310 "This function assumes token HMAC is 32 bytes, but it might not be.");
1311 std::copy(authToken.hmac, authToken.hmac + sizeof(authToken.hmac), hidlAuthToken->hmac.data());
1312
1313 // The table takes ownership of authToken.
1314 mAuthTokenTable.AddAuthenticationToken(hidlAuthToken.release());
1315 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001316}
1317
Janis Danisevskis7612fd42016-09-01 11:50:02 +01001318constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
1319
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001320bool isDeviceIdAttestationRequested(const hidl_vec<KeyParameter>& params) {
1321 for (size_t i = 0; i < params.size(); ++i) {
1322 switch (params[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -06001323 case Tag::ATTESTATION_ID_BRAND:
1324 case Tag::ATTESTATION_ID_DEVICE:
1325 case Tag::ATTESTATION_ID_IMEI:
1326 case Tag::ATTESTATION_ID_MANUFACTURER:
1327 case Tag::ATTESTATION_ID_MEID:
1328 case Tag::ATTESTATION_ID_MODEL:
1329 case Tag::ATTESTATION_ID_PRODUCT:
1330 case Tag::ATTESTATION_ID_SERIAL:
1331 return true;
1332 default:
1333 break;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001334 }
1335 }
1336 return false;
1337}
1338
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001339KeyStoreServiceReturnCode KeyStoreService::attestKey(const String16& name,
1340 const hidl_vec<KeyParameter>& params,
1341 hidl_vec<hidl_vec<uint8_t>>* outChain) {
1342 if (!outChain) {
1343 return ErrorCode::OUTPUT_PARAMETER_NULL;
1344 }
Shawn Willden50eb1b22016-01-21 12:41:23 -07001345
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001346 if (!checkAllowedOperationParams(params)) {
1347 return ErrorCode::INVALID_ARGUMENT;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001348 }
1349
1350 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1351
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001352 bool attestingDeviceIds = isDeviceIdAttestationRequested(params);
1353 if (attestingDeviceIds) {
1354 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1355 if (binder == 0) {
1356 return ErrorCode::CANNOT_ATTEST_IDS;
1357 }
1358 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1359 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1360 IPCThreadState::self()->getCallingPid(), callingUid)) {
Shawn Willdene2a7b522017-04-11 09:27:40 -06001361 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001362 }
1363 }
1364
Shawn Willdene2a7b522017-04-11 09:27:40 -06001365 AuthorizationSet mutableParams = params;
1366
1367 KeyStoreServiceReturnCode responseCode;
1368 bool factoryResetSinceIdRotation;
1369 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
1370
1371 if (!responseCode.isOk()) return responseCode;
1372 if (factoryResetSinceIdRotation) mutableParams.push_back(TAG_RESET_SINCE_ID_ROTATION);
1373
Shawn Willden50eb1b22016-01-21 12:41:23 -07001374 Blob keyBlob;
1375 String8 name8(name);
Shawn Willdene2a7b522017-04-11 09:27:40 -06001376 responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001377 if (!responseCode.isOk()) {
Shawn Willden50eb1b22016-01-21 12:41:23 -07001378 return responseCode;
1379 }
1380
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001381 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
Janis Danisevskis011675d2016-09-01 11:41:29 +01001382 if (!asn1_attestation_id_result.isOk()) {
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001383 ALOGE("failed to gather attestation_id");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001384 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001385 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001386 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001387
1388 /*
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001389 * The attestation application ID cannot be longer than
1390 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, so we truncate if too long.
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001391 */
Shawn Willdene2a7b522017-04-11 09:27:40 -06001392 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001393 asn1_attestation_id.resize(KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE);
Shawn Willdene2a7b522017-04-11 09:27:40 -06001394 }
Shawn Willden50eb1b22016-01-21 12:41:23 -07001395
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001396 mutableParams.push_back(TAG_ATTESTATION_APPLICATION_ID, blob2hidlVec(asn1_attestation_id));
1397
1398 KeyStoreServiceReturnCode error;
1399 auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1400 error = ret;
1401 if (!error.isOk()) {
1402 return;
1403 }
1404 if (outChain) *outChain = certChain;
1405 };
1406
1407 auto hidlKey = blob2hidlVec(keyBlob);
1408 auto& dev = mKeyStore->getDevice(keyBlob);
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001409 KeyStoreServiceReturnCode attestationRc =
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001410 KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001411
1412 KeyStoreServiceReturnCode deletionRc;
1413 if (attestingDeviceIds) {
1414 // When performing device id attestation, treat the key as ephemeral and delete it straight
1415 // away.
Bartosz Fabianowskia65ab422017-04-20 04:41:21 +02001416 deletionRc = del(name, callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001417 }
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001418
1419 if (!attestationRc.isOk()) {
1420 return attestationRc;
1421 }
1422 if (!error.isOk()) {
1423 return error;
1424 }
1425 return deletionRc;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001426}
1427
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001428KeyStoreServiceReturnCode KeyStoreService::onDeviceOffBody() {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001429 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1430 mAuthTokenTable.onDeviceOffBody();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001431 return ResponseCode::NO_ERROR;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001432}
1433
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001434/**
1435 * Prune the oldest pruneable operation.
1436 */
1437bool KeyStoreService::pruneOperation() {
1438 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1439 ALOGD("Trying to prune operation %p", oldest.get());
1440 size_t op_count_before_abort = mOperationMap.getOperationCount();
1441 // We mostly ignore errors from abort() because all we care about is whether at least
1442 // one operation has been removed.
1443 int abort_error = abort(oldest);
1444 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1445 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1446 return false;
1447 }
1448 return true;
1449}
1450
1451/**
1452 * Get the effective target uid for a binder operation that takes an
1453 * optional uid as the target.
1454 */
1455uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1456 if (targetUid == UID_SELF) {
1457 return IPCThreadState::self()->getCallingUid();
1458 }
1459 return static_cast<uid_t>(targetUid);
1460}
1461
1462/**
1463 * Check if the caller of the current binder method has the required
1464 * permission and if acting on other uids the grants to do so.
1465 */
1466bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1467 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1468 pid_t spid = IPCThreadState::self()->getCallingPid();
1469 if (!has_permission(callingUid, permission, spid)) {
1470 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1471 return false;
1472 }
1473 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1474 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1475 return false;
1476 }
1477 return true;
1478}
1479
1480/**
1481 * Check if the caller of the current binder method has the required
1482 * permission and the target uid is the caller or the caller is system.
1483 */
1484bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1485 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1486 pid_t spid = IPCThreadState::self()->getCallingPid();
1487 if (!has_permission(callingUid, permission, spid)) {
1488 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1489 return false;
1490 }
1491 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1492}
1493
1494/**
1495 * Check if the caller of the current binder method has the required
1496 * permission or the target of the operation is the caller's uid. This is
1497 * for operation where the permission is only for cross-uid activity and all
1498 * uids are allowed to act on their own (ie: clearing all entries for a
1499 * given uid).
1500 */
1501bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1502 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1503 if (getEffectiveUid(targetUid) == callingUid) {
1504 return true;
1505 } else {
1506 return checkBinderPermission(permission, targetUid);
1507 }
1508}
1509
1510/**
1511 * Helper method to check that the caller has the required permission as
1512 * well as the keystore is in the unlocked state if checkUnlocked is true.
1513 *
1514 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1515 * otherwise the state of keystore when not unlocked and checkUnlocked is
1516 * true.
1517 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001518KeyStoreServiceReturnCode
1519KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1520 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001521 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001522 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001523 }
1524 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1525 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001526 // All State values coincide with ResponseCodes
1527 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001528 }
1529
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001530 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001531}
1532
1533bool KeyStoreService::isKeystoreUnlocked(State state) {
1534 switch (state) {
1535 case ::STATE_NO_ERROR:
1536 return true;
1537 case ::STATE_UNINITIALIZED:
1538 case ::STATE_LOCKED:
1539 return false;
1540 }
1541 return false;
1542}
1543
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001544/**
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001545 * Check that all KeyParameter's provided by the application are
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001546 * allowed. Any parameter that keystore adds itself should be disallowed here.
1547 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001548bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1549 for (size_t i = 0; i < params.size(); ++i) {
1550 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001551 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001552 case Tag::AUTH_TOKEN:
1553 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001554 return false;
1555 default:
1556 break;
1557 }
1558 }
1559 return true;
1560}
1561
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001562ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
1563 km_device_t* dev,
1564 const AuthorizationSet& params,
1565 KeyCharacteristics* out) {
1566 hidl_vec<uint8_t> appId;
1567 hidl_vec<uint8_t> appData;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001568 for (auto param : params) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001569 if (param.tag == Tag::APPLICATION_ID) {
1570 appId = authorizationValue(TAG_APPLICATION_ID, param).value();
1571 } else if (param.tag == Tag::APPLICATION_DATA) {
1572 appData = authorizationValue(TAG_APPLICATION_DATA, param).value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001573 }
1574 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001575 ErrorCode error = ErrorCode::OK;
1576
1577 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
1578 error = ret;
1579 if (error != ErrorCode::OK) {
1580 return;
1581 }
1582 if (out) *out = keyCharacteristics;
1583 };
1584
1585 ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appData, hidlCb));
1586 if (rc != ErrorCode::OK) {
1587 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001588 }
1589 return error;
1590}
1591
1592/**
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001593 * Get the auth token for this operation from the auth token table.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001594 *
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001595 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
1596 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1597 * authorization token exists for that operation and
1598 * failOnTokenMissing is false.
1599 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1600 * token for the operation
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001601 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001602KeyStoreServiceReturnCode KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics,
1603 uint64_t handle, KeyPurpose purpose,
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001604 const HardwareAuthToken** authToken,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001605 bool failOnTokenMissing) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001606
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001607 AuthorizationSet allCharacteristics;
1608 for (size_t i = 0; i < characteristics.softwareEnforced.size(); i++) {
1609 allCharacteristics.push_back(characteristics.softwareEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001610 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001611 for (size_t i = 0; i < characteristics.teeEnforced.size(); i++) {
1612 allCharacteristics.push_back(characteristics.teeEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001613 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001614 AuthTokenTable::Error err =
1615 mAuthTokenTable.FindAuthorization(allCharacteristics, purpose, handle, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001616 switch (err) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001617 case AuthTokenTable::OK:
1618 case AuthTokenTable::AUTH_NOT_REQUIRED:
1619 return ResponseCode::NO_ERROR;
1620 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1621 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
1622 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
1623 return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1624 case AuthTokenTable::OP_HANDLE_REQUIRED:
1625 return failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
1626 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001627 default:
1628 ALOGE("Unexpected FindAuthorization return value %d", err);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001629 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001630 }
1631}
1632
1633/**
1634 * Add the auth token for the operation to the param list if the operation
1635 * requires authorization. Uses the cached result in the OperationMap if available
1636 * otherwise gets the token from the AuthTokenTable and caches the result.
1637 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001638 * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001639 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1640 * authenticated.
1641 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1642 * operation token.
1643 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001644KeyStoreServiceReturnCode KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
1645 AuthorizationSet* params) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001646 const HardwareAuthToken* authToken = nullptr;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001647 mOperationMap.getOperationAuthToken(token, &authToken);
1648 if (!authToken) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001649 km_device_t dev;
1650 uint64_t handle;
1651 const KeyCharacteristics* characteristics = nullptr;
1652 KeyPurpose purpose;
1653 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001654 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001655 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001656 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001657 auto result = getAuthToken(*characteristics, handle, purpose, &authToken);
1658 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001659 return result;
1660 }
1661 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001662 mOperationMap.setOperationAuthToken(token, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001663 }
1664 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001665 addAuthTokenToParams(params, authToken);
1666 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001667}
1668
1669/**
1670 * Translate a result value to a legacy return value. All keystore errors are
1671 * preserved and keymaster errors become SYSTEM_ERRORs
1672 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001673KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001674 if (result > 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001675 return static_cast<ResponseCode>(result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001676 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001677 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001678}
1679
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001680static NullOr<const Algorithm&>
1681getKeyAlgoritmFromKeyCharacteristics(const KeyCharacteristics& characteristics) {
1682 for (size_t i = 0; i < characteristics.teeEnforced.size(); ++i) {
1683 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.teeEnforced[i]);
1684 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001685 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001686 for (size_t i = 0; i < characteristics.softwareEnforced.size(); ++i) {
1687 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.softwareEnforced[i]);
1688 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001689 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001690 return {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001691}
1692
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001693void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001694 // All legacy keys are DIGEST_NONE/PAD_NONE.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001695 params->push_back(TAG_DIGEST, Digest::NONE);
1696 params->push_back(TAG_PADDING, PaddingMode::NONE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001697
1698 // Look up the algorithm of the key.
1699 KeyCharacteristics characteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001700 auto rc = getKeyCharacteristics(name, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF,
1701 &characteristics);
1702 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001703 ALOGE("Failed to get key characteristics");
1704 return;
1705 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001706 auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
1707 if (!algorithm.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001708 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1709 return;
1710 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001711 params->push_back(TAG_ALGORITHM, algorithm.value());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001712}
1713
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001714KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
1715 const hidl_vec<uint8_t>& data,
1716 hidl_vec<uint8_t>* out,
1717 const hidl_vec<uint8_t>& signature,
1718 KeyPurpose purpose) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001719
1720 std::basic_stringstream<uint8_t> outBuffer;
1721 OperationResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001722 AuthorizationSet inArgs;
1723 addLegacyBeginParams(name, &inArgs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001724 sp<IBinder> appToken(new BBinder);
1725 sp<IBinder> token;
1726
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001727 begin(appToken, name, purpose, true, inArgs.hidl_data(), hidl_vec<uint8_t>(), UID_SELF,
1728 &result);
1729 if (!result.resultCode.isOk()) {
1730 if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001731 ALOGW("Key not found");
1732 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001733 ALOGW("Error in begin: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001734 }
1735 return translateResultToLegacyResult(result.resultCode);
1736 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001737 inArgs.Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001738 token = result.token;
1739 size_t consumed = 0;
1740 size_t lastConsumed = 0;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001741 hidl_vec<uint8_t> data_view;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001742 do {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001743 data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
1744 update(token, inArgs.hidl_data(), data_view, &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001745 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001746 ALOGW("Error in update: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001747 return translateResultToLegacyResult(result.resultCode);
1748 }
1749 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001750 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001751 }
1752 lastConsumed = result.inputConsumed;
1753 consumed += lastConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001754 } while (consumed < data.size() && lastConsumed > 0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001755
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001756 if (consumed != data.size()) {
1757 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
1758 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001759 }
1760
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001761 finish(token, inArgs.hidl_data(), signature, hidl_vec<uint8_t>(), &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001762 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001763 ALOGW("Error in finish: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001764 return translateResultToLegacyResult(result.resultCode);
1765 }
1766 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001767 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001768 }
1769
1770 if (out) {
1771 auto buf = outBuffer.str();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001772 out->resize(buf.size());
1773 memcpy(&(*out)[0], buf.data(), out->size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001774 }
1775
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001776 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001777}
1778
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001779KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
1780 const AuthorizationSet& params,
1781 Blob* blob) {
Shawn Willden98c59162016-03-20 09:10:18 -06001782 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
1783 String8 name8(name);
1784 ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001785 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willden98c59162016-03-20 09:10:18 -06001786 return responseCode;
1787 }
Rubin Xu7675c9f2017-03-15 19:26:52 +00001788 ALOGI("upgradeKeyBlob %s %d", name8.string(), uid);
Shawn Willden98c59162016-03-20 09:10:18 -06001789
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001790 auto hidlKey = blob2hidlVec(*blob);
1791 auto& dev = mKeyStore->getDevice(*blob);
Shawn Willden98c59162016-03-20 09:10:18 -06001792
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001793 KeyStoreServiceReturnCode error;
1794 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
1795 error = ret;
1796 if (!error.isOk()) {
1797 return;
1798 }
1799
1800 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1801 error = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(uid));
1802 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001803 ALOGI("upgradeKeyBlob keystore->del failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001804 return;
1805 }
1806
1807 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
1808 0 /* infoLength */, ::TYPE_KEYMASTER_10);
1809 newBlob.setFallback(blob->isFallback());
1810 newBlob.setEncrypted(blob->isEncrypted());
Rubin Xu67899de2017-04-21 19:15:13 +01001811 newBlob.setSuperEncrypted(blob->isSuperEncrypted());
1812 newBlob.setCriticalToDeviceEncryption(blob->isCriticalToDeviceEncryption());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001813
1814 error = mKeyStore->put(filename.string(), &newBlob, get_user_id(uid));
1815 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001816 ALOGI("upgradeKeyBlob keystore->put failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001817 return;
1818 }
1819
1820 // Re-read blob for caller. We can't use newBlob because writing it modified it.
1821 error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1822 };
1823
1824 KeyStoreServiceReturnCode rc =
1825 KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
1826 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001827 return rc;
1828 }
1829
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001830 return error;
Shawn Willden98c59162016-03-20 09:10:18 -06001831}
1832
Shawn Willdene2a7b522017-04-11 09:27:40 -06001833} // namespace keystore