blob: 6d1774961cc1d21daf9acab3ad8653c7a9c87caa [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 {
43using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070044
45const size_t MAX_OPERATIONS = 15;
46
47struct BIGNUM_Delete {
48 void operator()(BIGNUM* p) const { BN_free(p); }
49};
50typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
51
52void KeyStoreService::binderDied(const wp<IBinder>& who) {
53 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -070054 for (const auto& token : operations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070055 abort(token);
56 }
57}
58
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010059KeyStoreServiceReturnCode KeyStoreService::getState(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070060 if (!checkBinderPermission(P_GET_STATE)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010061 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070062 }
63
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010064 return ResponseCode(mKeyStore->getState(userId));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070065}
66
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010067KeyStoreServiceReturnCode KeyStoreService::get(const String16& name, int32_t uid,
68 hidl_vec<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070069 uid_t targetUid = getEffectiveUid(uid);
70 if (!checkBinderPermission(P_GET, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010071 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070072 }
73
74 String8 name8(name);
75 Blob keyBlob;
76
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010077 KeyStoreServiceReturnCode rc =
78 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
79 if (!rc.isOk()) {
80 if (item) *item = hidl_vec<uint8_t>();
81 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070082 }
83
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010084 // Do not replace this with "if (item) *item = blob2hidlVec(keyBlob)"!
85 // blob2hidlVec creates a hidl_vec<uint8_t> that references, but not owns, the data in keyBlob
86 // the subsequent assignment (*item = resultBlob) makes a deep copy, so that *item will own the
87 // corresponding resources.
88 auto resultBlob = blob2hidlVec(keyBlob);
89 if (item) {
90 *item = resultBlob;
91 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070092
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010093 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070094}
95
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010096KeyStoreServiceReturnCode KeyStoreService::insert(const String16& name,
97 const hidl_vec<uint8_t>& item, int targetUid,
98 int32_t flags) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070099 targetUid = getEffectiveUid(targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100100 auto result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700101 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100102 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700103 return result;
104 }
105
106 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400107 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_GENERIC));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700108
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100109 Blob keyBlob(&item[0], item.size(), NULL, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700110 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
111
112 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
113}
114
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100115KeyStoreServiceReturnCode KeyStoreService::del(const String16& name, int targetUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700116 targetUid = getEffectiveUid(targetUid);
117 if (!checkBinderPermission(P_DELETE, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100118 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700119 }
120 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400121 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100122 ResponseCode result = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
123 if (result != ResponseCode::NO_ERROR) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400124 return result;
125 }
126
127 // Also delete any characteristics files
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100128 String8 chrFilename(
129 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400130 return mKeyStore->del(chrFilename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700131}
132
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100133KeyStoreServiceReturnCode KeyStoreService::exist(const String16& name, int targetUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700134 targetUid = getEffectiveUid(targetUid);
135 if (!checkBinderPermission(P_EXIST, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100136 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700137 }
138
139 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400140 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700141
142 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100143 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700144 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100145 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700146}
147
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100148KeyStoreServiceReturnCode KeyStoreService::list(const String16& prefix, int targetUid,
149 Vector<String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700150 targetUid = getEffectiveUid(targetUid);
151 if (!checkBinderPermission(P_LIST, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100152 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700153 }
154 const String8 prefix8(prefix);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400155 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid, TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700156
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100157 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
158 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700159 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100160 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700161}
162
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100163KeyStoreServiceReturnCode KeyStoreService::reset() {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700164 if (!checkBinderPermission(P_RESET)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100165 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700166 }
167
168 uid_t callingUid = IPCThreadState::self()->getCallingUid();
169 mKeyStore->resetUser(get_user_id(callingUid), false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100170 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700171}
172
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100173KeyStoreServiceReturnCode KeyStoreService::onUserPasswordChanged(int32_t userId,
174 const String16& password) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700175 if (!checkBinderPermission(P_PASSWORD)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100176 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700177 }
178
179 const String8 password8(password);
180 // Flush the auth token table to prevent stale tokens from sticking
181 // around.
182 mAuthTokenTable.Clear();
183
184 if (password.size() == 0) {
185 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
186 mKeyStore->resetUser(userId, true);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100187 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700188 } else {
189 switch (mKeyStore->getState(userId)) {
190 case ::STATE_UNINITIALIZED: {
191 // generate master key, encrypt with password, write to file,
192 // initialize mMasterKey*.
193 return mKeyStore->initializeUser(password8, userId);
194 }
195 case ::STATE_NO_ERROR: {
196 // rewrite master key with new password.
197 return mKeyStore->writeMasterKey(password8, userId);
198 }
199 case ::STATE_LOCKED: {
200 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
201 mKeyStore->resetUser(userId, true);
202 return mKeyStore->initializeUser(password8, userId);
203 }
204 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100205 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700206 }
207}
208
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100209KeyStoreServiceReturnCode KeyStoreService::onUserAdded(int32_t userId, int32_t parentId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700210 if (!checkBinderPermission(P_USER_CHANGED)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100211 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700212 }
213
214 // Sanity check that the new user has an empty keystore.
215 if (!mKeyStore->isEmpty(userId)) {
216 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
217 }
218 // Unconditionally clear the keystore, just to be safe.
219 mKeyStore->resetUser(userId, false);
220 if (parentId != -1) {
221 // This profile must share the same master key password as the parent profile. Because the
222 // password of the parent profile is not known here, the best we can do is copy the parent's
223 // master key and master key file. This makes this profile use the same master key as the
224 // parent profile, forever.
225 return mKeyStore->copyMasterKey(parentId, userId);
226 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100227 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700228 }
229}
230
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100231KeyStoreServiceReturnCode KeyStoreService::onUserRemoved(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700232 if (!checkBinderPermission(P_USER_CHANGED)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100233 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700234 }
235
236 mKeyStore->resetUser(userId, false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100237 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700238}
239
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100240KeyStoreServiceReturnCode KeyStoreService::lock(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700241 if (!checkBinderPermission(P_LOCK)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100242 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700243 }
244
245 State state = mKeyStore->getState(userId);
246 if (state != ::STATE_NO_ERROR) {
247 ALOGD("calling lock in state: %d", state);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100248 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700249 }
250
251 mKeyStore->lock(userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100252 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700253}
254
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100255KeyStoreServiceReturnCode KeyStoreService::unlock(int32_t userId, const String16& pw) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700256 if (!checkBinderPermission(P_UNLOCK)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100257 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700258 }
259
260 State state = mKeyStore->getState(userId);
261 if (state != ::STATE_LOCKED) {
262 switch (state) {
263 case ::STATE_NO_ERROR:
264 ALOGI("calling unlock when already unlocked, ignoring.");
265 break;
266 case ::STATE_UNINITIALIZED:
267 ALOGE("unlock called on uninitialized keystore.");
268 break;
269 default:
270 ALOGE("unlock called on keystore in unknown state: %d", state);
271 break;
272 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100273 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700274 }
275
276 const String8 password8(pw);
277 // read master key, decrypt with password, initialize mMasterKey*.
278 return mKeyStore->readMasterKey(password8, userId);
279}
280
281bool KeyStoreService::isEmpty(int32_t userId) {
282 if (!checkBinderPermission(P_IS_EMPTY)) {
283 return false;
284 }
285
286 return mKeyStore->isEmpty(userId);
287}
288
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100289KeyStoreServiceReturnCode KeyStoreService::generate(const String16& name, int32_t targetUid,
290 int32_t keyType, int32_t keySize, int32_t flags,
291 Vector<sp<KeystoreArg>>* args) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700292 targetUid = getEffectiveUid(targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100293 auto result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700294 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100295 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700296 return result;
297 }
298
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100299 keystore::AuthorizationSet params;
300 add_legacy_key_authorizations(keyType, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700301
302 switch (keyType) {
303 case EVP_PKEY_EC: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100304 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700305 if (keySize == -1) {
306 keySize = EC_DEFAULT_KEY_SIZE;
307 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
308 ALOGI("invalid key size %d", keySize);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100309 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700310 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100311 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700312 break;
313 }
314 case EVP_PKEY_RSA: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100315 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700316 if (keySize == -1) {
317 keySize = RSA_DEFAULT_KEY_SIZE;
318 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
319 ALOGI("invalid key size %d", keySize);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100320 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700321 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100322 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700323 unsigned long exponent = RSA_DEFAULT_EXPONENT;
324 if (args->size() > 1) {
325 ALOGI("invalid number of arguments: %zu", args->size());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100326 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700327 } else if (args->size() == 1) {
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700328 const sp<KeystoreArg>& expArg = args->itemAt(0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700329 if (expArg != NULL) {
330 Unique_BIGNUM pubExpBn(BN_bin2bn(
331 reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
332 if (pubExpBn.get() == NULL) {
333 ALOGI("Could not convert public exponent to BN");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100334 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700335 }
336 exponent = BN_get_word(pubExpBn.get());
337 if (exponent == 0xFFFFFFFFL) {
338 ALOGW("cannot represent public exponent as a long value");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100339 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700340 }
341 } else {
342 ALOGW("public exponent not read");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100343 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700344 }
345 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100346 params.push_back(TAG_RSA_PUBLIC_EXPONENT, exponent);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700347 break;
348 }
349 default: {
350 ALOGW("Unsupported key type %d", keyType);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100351 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700352 }
353 }
354
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100355 auto rc = generateKey(name, params.hidl_data(), hidl_vec<uint8_t>(), targetUid, flags,
356 /*outCharacteristics*/ NULL);
357 if (!rc.isOk()) {
358 ALOGW("generate failed: %d", int32_t(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700359 }
360 return translateResultToLegacyResult(rc);
361}
362
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100363KeyStoreServiceReturnCode KeyStoreService::import(const String16& name,
364 const hidl_vec<uint8_t>& data, int targetUid,
365 int32_t flags) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700366
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100367 const uint8_t* ptr = &data[0];
368
369 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, data.size()));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700370 if (!pkcs8.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100371 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700372 }
373 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
374 if (!pkey.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100375 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700376 }
377 int type = EVP_PKEY_type(pkey->type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100378 AuthorizationSet params;
379 add_legacy_key_authorizations(type, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700380 switch (type) {
381 case EVP_PKEY_RSA:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100382 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700383 break;
384 case EVP_PKEY_EC:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100385 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700386 break;
387 default:
388 ALOGW("Unsupported key type %d", type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100389 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700390 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100391
392 auto rc = importKey(name, params.hidl_data(), KeyFormat::PKCS8, data, targetUid, flags,
393 /*outCharacteristics*/ NULL);
394
395 if (!rc.isOk()) {
396 ALOGW("importKey failed: %d", int32_t(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700397 }
398 return translateResultToLegacyResult(rc);
399}
400
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100401KeyStoreServiceReturnCode KeyStoreService::sign(const String16& name, const hidl_vec<uint8_t>& data,
402 hidl_vec<uint8_t>* out) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700403 if (!checkBinderPermission(P_SIGN)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100404 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700405 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100406 return doLegacySignVerify(name, data, out, hidl_vec<uint8_t>(), KeyPurpose::SIGN);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700407}
408
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100409KeyStoreServiceReturnCode KeyStoreService::verify(const String16& name,
410 const hidl_vec<uint8_t>& data,
411 const hidl_vec<uint8_t>& signature) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700412 if (!checkBinderPermission(P_VERIFY)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100413 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700414 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100415 return doLegacySignVerify(name, data, nullptr, signature, KeyPurpose::VERIFY);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700416}
417
418/*
419 * TODO: The abstraction between things stored in hardware and regular blobs
420 * of data stored on the filesystem should be moved down to keystore itself.
421 * Unfortunately the Java code that calls this has naming conventions that it
422 * knows about. Ideally keystore shouldn't be used to store random blobs of
423 * data.
424 *
425 * Until that happens, it's necessary to have a separate "get_pubkey" and
426 * "del_key" since the Java code doesn't really communicate what it's
427 * intentions are.
428 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100429KeyStoreServiceReturnCode KeyStoreService::get_pubkey(const String16& name,
430 hidl_vec<uint8_t>* pubKey) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700431 ExportResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100432 exportKey(name, KeyFormat::X509, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF, &result);
433 if (!result.resultCode.isOk()) {
434 ALOGW("export failed: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700435 return translateResultToLegacyResult(result.resultCode);
436 }
437
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100438 if (pubKey) *pubKey = std::move(result.exportData);
439 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700440}
441
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100442KeyStoreServiceReturnCode KeyStoreService::grant(const String16& name, int32_t granteeUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700443 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100444 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
445 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700446 return result;
447 }
448
449 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400450 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700451
452 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100453 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700454 }
455
456 mKeyStore->addGrant(filename.string(), granteeUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100457 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700458}
459
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100460KeyStoreServiceReturnCode KeyStoreService::ungrant(const String16& name, int32_t granteeUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700461 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100462 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
463 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700464 return result;
465 }
466
467 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400468 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700469
470 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100471 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700472 }
473
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100474 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ResponseCode::NO_ERROR
475 : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700476}
477
478int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
479 uid_t targetUid = getEffectiveUid(uid);
480 if (!checkBinderPermission(P_GET, targetUid)) {
481 ALOGW("permission denied for %d: getmtime", targetUid);
482 return -1L;
483 }
484
485 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400486 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700487
488 if (access(filename.string(), R_OK) == -1) {
489 ALOGW("could not access %s for getmtime", filename.string());
490 return -1L;
491 }
492
493 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
494 if (fd < 0) {
495 ALOGW("could not open %s for getmtime", filename.string());
496 return -1L;
497 }
498
499 struct stat s;
500 int ret = fstat(fd, &s);
501 close(fd);
502 if (ret == -1) {
503 ALOGW("could not stat %s for getmtime", filename.string());
504 return -1L;
505 }
506
507 return static_cast<int64_t>(s.st_mtime);
508}
509
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400510// TODO(tuckeris): This is dead code, remove it. Don't bother copying over key characteristics here
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100511KeyStoreServiceReturnCode KeyStoreService::duplicate(const String16& srcKey, int32_t srcUid,
512 const String16& destKey, int32_t destUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700513 uid_t callingUid = IPCThreadState::self()->getCallingUid();
514 pid_t spid = IPCThreadState::self()->getCallingPid();
515 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
516 ALOGW("permission denied for %d: duplicate", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100517 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700518 }
519
520 State state = mKeyStore->getState(get_user_id(callingUid));
521 if (!isKeystoreUnlocked(state)) {
522 ALOGD("calling duplicate in state: %d", state);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100523 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700524 }
525
526 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
527 srcUid = callingUid;
528 } else if (!is_granted_to(callingUid, srcUid)) {
529 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100530 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700531 }
532
533 if (destUid == -1) {
534 destUid = callingUid;
535 }
536
537 if (srcUid != destUid) {
538 if (static_cast<uid_t>(srcUid) != callingUid) {
539 ALOGD("can only duplicate from caller to other or to same uid: "
540 "calling=%d, srcUid=%d, destUid=%d",
541 callingUid, srcUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100542 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700543 }
544
545 if (!is_granted_to(callingUid, destUid)) {
546 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100547 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700548 }
549 }
550
551 String8 source8(srcKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400552 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700553
554 String8 target8(destKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400555 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700556
557 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
558 ALOGD("destination already exists: %s", targetFile.string());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100559 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700560 }
561
562 Blob keyBlob;
563 ResponseCode responseCode =
564 mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, get_user_id(srcUid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100565 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700566 return responseCode;
567 }
568
569 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
570}
571
572int32_t KeyStoreService::is_hardware_backed(const String16& keyType) {
573 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
574}
575
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100576KeyStoreServiceReturnCode KeyStoreService::clear_uid(int64_t targetUid64) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700577 uid_t targetUid = getEffectiveUid(targetUid64);
578 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100579 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700580 }
581
582 String8 prefix = String8::format("%u_", targetUid);
583 Vector<String16> aliases;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100584 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
585 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700586 }
587
588 for (uint32_t i = 0; i < aliases.size(); i++) {
589 String8 name8(aliases[i]);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400590 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700591 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400592
593 // del() will fail silently if no cached characteristics are present for this alias.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100594 String8 chr_filename(
595 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400596 mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700597 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100598 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700599}
600
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100601KeyStoreServiceReturnCode KeyStoreService::addRngEntropy(const hidl_vec<uint8_t>& entropy) {
602 const auto& device = mKeyStore->getDevice();
603 return KS_HANDLE_HIDL_ERROR(device->addRngEntropy(entropy));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700604}
605
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100606KeyStoreServiceReturnCode KeyStoreService::generateKey(const String16& name,
607 const hidl_vec<KeyParameter>& params,
608 const hidl_vec<uint8_t>& entropy, int uid,
609 int flags,
610 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700611 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100612 KeyStoreServiceReturnCode rc =
613 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
614 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700615 return rc;
616 }
617
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100618 bool usingFallback = false;
619 auto& dev = mKeyStore->getDevice();
620 AuthorizationSet keyCharacteristics = params;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400621
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700622 // TODO: Seed from Linux RNG before this.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100623 rc = addRngEntropy(entropy);
624 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700625 return rc;
626 }
627
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100628 KeyStoreServiceReturnCode error;
629 auto hidl_cb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
630 const KeyCharacteristics& keyCharacteristics) {
631 error = ret;
632 if (!error.isOk()) {
633 return;
634 }
635 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700636
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100637 // Write the key
638 String8 name8(name);
639 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700640
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100641 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
642 keyBlob.setFallback(usingFallback);
643 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700644
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100645 error = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
646 };
647
648 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(params, hidl_cb));
649 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400650 return rc;
651 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100652 if (!error.isOk()) {
653 ALOGE("Failed to generate key -> falling back to software keymaster");
654 usingFallback = true;
655 auto& fallback = mKeyStore->getFallbackDevice();
656 rc = KS_HANDLE_HIDL_ERROR(fallback->generateKey(params, hidl_cb));
657 if (!rc.isOk()) {
658 return rc;
659 }
660 if (!error.isOk()) {
661 return error;
662 }
663 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400664
665 // Write the characteristics:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100666 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400667 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
668
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100669 std::stringstream kc_stream;
670 keyCharacteristics.Serialize(&kc_stream);
671 if (kc_stream.bad()) {
672 return ResponseCode::SYSTEM_ERROR;
673 }
674 auto kc_buf = kc_stream.str();
675 Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
676 ::TYPE_KEY_CHARACTERISTICS);
677 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400678 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
679
680 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700681}
682
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100683KeyStoreServiceReturnCode
684KeyStoreService::getKeyCharacteristics(const String16& name, const hidl_vec<uint8_t>& clientId,
685 const hidl_vec<uint8_t>& appData, int32_t uid,
686 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700687 if (!outCharacteristics) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100688 return ErrorCode::UNEXPECTED_NULL_POINTER;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700689 }
690
691 uid_t targetUid = getEffectiveUid(uid);
692 uid_t callingUid = IPCThreadState::self()->getCallingUid();
693 if (!is_granted_to(callingUid, targetUid)) {
694 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
695 targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100696 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700697 }
698
699 Blob keyBlob;
700 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700701
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100702 KeyStoreServiceReturnCode rc =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700703 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100704 if (!rc.isOk()) {
705 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700706 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100707
708 auto hidlKeyBlob = blob2hidlVec(keyBlob);
709 auto& dev = mKeyStore->getDevice(keyBlob);
710
711 KeyStoreServiceReturnCode error;
712
713 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
714 error = ret;
715 if (!error.isOk()) {
716 return;
Shawn Willden98c59162016-03-20 09:10:18 -0600717 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100718 *outCharacteristics = keyCharacteristics;
719 };
720
721 rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(hidlKeyBlob, clientId, appData, hidlCb));
722 if (!rc.isOk()) {
723 return rc;
724 }
725
726 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
727 AuthorizationSet upgradeParams;
728 if (clientId.size()) {
729 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
730 }
731 if (appData.size()) {
732 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
Shawn Willden98c59162016-03-20 09:10:18 -0600733 }
734 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100735 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -0600736 return rc;
737 }
Shawn Willden715d0232016-01-21 00:45:13 -0700738
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100739 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
740
741 rc = KS_HANDLE_HIDL_ERROR(
742 dev->getKeyCharacteristics(upgradedHidlKeyBlob, clientId, appData, hidlCb));
743 if (!rc.isOk()) {
744 return rc;
745 }
746 // Note that, on success, "error" will have been updated by the hidlCB callback.
747 // So it is fine to return "error" below.
748 }
749 return error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700750}
751
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100752KeyStoreServiceReturnCode
753KeyStoreService::importKey(const String16& name, const hidl_vec<KeyParameter>& params,
754 KeyFormat format, const hidl_vec<uint8_t>& keyData, int uid, int flags,
755 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700756 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100757 KeyStoreServiceReturnCode rc =
758 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
759 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700760 return rc;
761 }
762
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100763 bool usingFallback = false;
764 auto& dev = mKeyStore->getDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700765
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700766 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700767
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100768 KeyStoreServiceReturnCode error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700769
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100770 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
771 const KeyCharacteristics& keyCharacteristics) {
772 error = ret;
773 if (!error.isOk()) {
774 return;
775 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700776
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100777 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
778
779 // Write the key:
780 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
781
782 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
783 ksBlob.setFallback(usingFallback);
784 ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
785
786 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
787 };
788
789 rc = KS_HANDLE_HIDL_ERROR(dev->importKey(params, format, keyData, hidlCb));
790 // possible hidl error
791 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400792 return rc;
793 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100794 // now check error from callback
795 if (!error.isOk()) {
796 ALOGE("Failed to import key -> falling back to software keymaster");
797 usingFallback = true;
798 auto& fallback = mKeyStore->getFallbackDevice();
799 rc = KS_HANDLE_HIDL_ERROR(fallback->importKey(params, format, keyData, hidlCb));
800 // possible hidl error
801 if (!rc.isOk()) {
802 return rc;
803 }
804 // now check error from callback
805 if (!error.isOk()) {
806 return error;
807 }
808 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400809
810 // Write the characteristics:
811 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
812
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100813 AuthorizationSet opParams = params;
814 std::stringstream kcStream;
815 opParams.Serialize(&kcStream);
816 if (kcStream.bad()) return ResponseCode::SYSTEM_ERROR;
817 auto kcBuf = kcStream.str();
818
819 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
820 ::TYPE_KEY_CHARACTERISTICS);
821 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400822 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
823
824 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700825}
826
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100827void KeyStoreService::exportKey(const String16& name, KeyFormat format,
828 const hidl_vec<uint8_t>& clientId, const hidl_vec<uint8_t>& appData,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700829 int32_t uid, ExportResult* result) {
830
831 uid_t targetUid = getEffectiveUid(uid);
832 uid_t callingUid = IPCThreadState::self()->getCallingUid();
833 if (!is_granted_to(callingUid, targetUid)) {
834 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100835 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700836 return;
837 }
838
839 Blob keyBlob;
840 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700841
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100842 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
843 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700844 return;
845 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100846
847 auto key = blob2hidlVec(keyBlob);
848 auto& dev = mKeyStore->getDevice(keyBlob);
849
850 auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
851 result->resultCode = ret;
852 if (!result->resultCode.isOk()) {
Ji Wang2c142312016-10-14 17:21:10 +0800853 return;
854 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100855 result->exportData = keyMaterial;
856 };
857 KeyStoreServiceReturnCode rc =
858 KS_HANDLE_HIDL_ERROR(dev->exportKey(format, key, clientId, appData, hidlCb));
859 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
860 // callback hidlCb.
861 if (!rc.isOk()) {
862 result->resultCode = rc;
Ji Wang2c142312016-10-14 17:21:10 +0800863 }
864
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100865 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
866 AuthorizationSet upgradeParams;
867 if (clientId.size()) {
868 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
869 }
870 if (appData.size()) {
871 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
872 }
873 result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
874 if (!result->resultCode.isOk()) {
875 return;
876 }
877
878 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
879
880 result->resultCode = KS_HANDLE_HIDL_ERROR(
881 dev->exportKey(format, upgradedHidlKeyBlob, clientId, appData, hidlCb));
882 if (!result->resultCode.isOk()) {
883 return;
884 }
885 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700886}
887
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100888static inline void addAuthTokenToParams(AuthorizationSet* params, const HardwareAuthToken* token) {
889 if (token) {
890 params->push_back(TAG_AUTH_TOKEN, authToken2HidlVec(*token));
891 }
892}
893
894void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, KeyPurpose purpose,
895 bool pruneable, const hidl_vec<KeyParameter>& params,
896 const hidl_vec<uint8_t>& entropy, int32_t uid,
897 OperationResult* result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700898 uid_t callingUid = IPCThreadState::self()->getCallingUid();
899 uid_t targetUid = getEffectiveUid(uid);
900 if (!is_granted_to(callingUid, targetUid)) {
901 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100902 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700903 return;
904 }
905 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
906 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100907 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700908 return;
909 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100910 if (!checkAllowedOperationParams(params)) {
911 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700912 return;
913 }
914 Blob keyBlob;
915 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100916 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
917 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700918 return;
919 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100920
921 auto key = blob2hidlVec(keyBlob);
922 auto& dev = mKeyStore->getDevice(keyBlob);
923 AuthorizationSet opParams = params;
924 KeyCharacteristics characteristics;
925 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
926
927 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
928 result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
929 if (!result->resultCode.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -0600930 return;
931 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100932 key = blob2hidlVec(keyBlob);
933 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
Shawn Willden98c59162016-03-20 09:10:18 -0600934 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100935 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700936 return;
937 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100938
939 const HardwareAuthToken* authToken = NULL;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400940
941 // Merge these characteristics with the ones cached when the key was generated or imported
942 Blob charBlob;
943 AuthorizationSet persistedCharacteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100944 result->resultCode =
945 mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
946 if (result->resultCode.isOk()) {
947 // TODO write one shot stream buffer to avoid copying (twice here)
948 std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
949 charBlob.getLength());
950 std::stringstream charStream(charBuffer);
951 persistedCharacteristics.Deserialize(&charStream);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400952 } else {
953 ALOGD("Unable to read cached characteristics for key");
954 }
955
956 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100957 AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
958 AuthorizationSet teeEnforced = characteristics.teeEnforced;
959 persistedCharacteristics.Union(softwareEnforced);
960 persistedCharacteristics.Subtract(teeEnforced);
961 characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400962
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100963 result->resultCode = getAuthToken(characteristics, 0, purpose, &authToken,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700964 /*failOnTokenMissing*/ false);
965 // If per-operation auth is needed we need to begin the operation and
966 // the client will need to authorize that operation before calling
967 // update. Any other auth issues stop here.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100968 if (!result->resultCode.isOk() && result->resultCode != ResponseCode::OP_AUTH_NEEDED) return;
969
970 addAuthTokenToParams(&opParams, authToken);
971
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700972 // Add entropy to the device first.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100973 if (entropy.size()) {
974 result->resultCode = addRngEntropy(entropy);
975 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700976 return;
977 }
978 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700979
980 // Create a keyid for this key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100981 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700982 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
983 ALOGE("Failed to create a key ID for authorization checking.");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100984 result->resultCode = ErrorCode::UNKNOWN_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700985 return;
986 }
987
988 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100989 AuthorizationSet key_auths = characteristics.teeEnforced;
990 key_auths.append(&characteristics.softwareEnforced[0],
991 &characteristics.softwareEnforced[characteristics.softwareEnforced.size()]);
992
993 result->resultCode = enforcement_policy.AuthorizeOperation(
994 purpose, keyid, key_auths, opParams, 0 /* op_handle */, true /* is_begin_operation */);
995 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700996 return;
997 }
998
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700999 // If there are more than MAX_OPERATIONS, abort the oldest operation that was started as
1000 // pruneable.
1001 while (mOperationMap.getOperationCount() >= MAX_OPERATIONS) {
1002 ALOGD("Reached or exceeded concurrent operations limit");
1003 if (!pruneOperation()) {
1004 break;
1005 }
1006 }
1007
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001008 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1009 uint64_t operationHandle) {
1010 result->resultCode = ret;
1011 if (!result->resultCode.isOk()) {
1012 return;
1013 }
1014 result->handle = operationHandle;
1015 result->outParams = outParams;
1016 };
1017
1018 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
1019 if (rc != ErrorCode::OK) {
1020 ALOGW("Got error %d from begin()", rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001021 }
1022
1023 // If there are too many operations abort the oldest operation that was
1024 // started as pruneable and try again.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001025 while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1026 ALOGW("Ran out of operation handles");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001027 if (!pruneOperation()) {
1028 break;
1029 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001030 rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001031 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001032 if (rc != ErrorCode::OK) {
1033 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001034 return;
1035 }
1036
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001037 // Note: The operation map takes possession of the contents of "characteristics".
1038 // It is safe to use characteristics after the following line but it will be empty.
1039 sp<IBinder> operationToken = mOperationMap.addOperation(
1040 result->handle, keyid, purpose, dev, appToken, std::move(characteristics), pruneable);
1041 assert(characteristics.teeEnforced.size() == 0);
1042 assert(characteristics.softwareEnforced.size() == 0);
1043
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001044 if (authToken) {
1045 mOperationMap.setOperationAuthToken(operationToken, authToken);
1046 }
1047 // Return the authentication lookup result. If this is a per operation
1048 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1049 // application should get an auth token using the handle before the
1050 // first call to update, which will fail if keystore hasn't received the
1051 // auth token.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001052 // All fields but "token" were set in the begin operation's callback.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001053 result->token = operationToken;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001054}
1055
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001056void KeyStoreService::update(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1057 const hidl_vec<uint8_t>& data, OperationResult* result) {
1058 if (!checkAllowedOperationParams(params)) {
1059 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001060 return;
1061 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001062 km_device_t dev;
1063 uint64_t handle;
1064 KeyPurpose purpose;
1065 km_id_t keyid;
1066 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001067 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001068 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001069 return;
1070 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001071 AuthorizationSet opParams = params;
1072 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1073 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001074 return;
1075 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001076
1077 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001078 AuthorizationSet key_auths(characteristics->teeEnforced);
1079 key_auths.append(&characteristics->softwareEnforced[0],
1080 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001081 result->resultCode = enforcement_policy.AuthorizeOperation(
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001082 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1083 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001084 return;
1085 }
1086
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001087 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
1088 const hidl_vec<KeyParameter>& outParams, const hidl_vec<uint8_t>& output) {
1089 result->resultCode = ret;
1090 if (!result->resultCode.isOk()) {
1091 return;
1092 }
1093 result->inputConsumed = inputConsumed;
1094 result->outParams = outParams;
1095 result->data = output;
1096 };
1097
Janis Danisevskisb0245ee2017-01-25 15:43:01 +00001098 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->update(handle, opParams.hidl_data(),
1099 data, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001100 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1101 // it if there was a communication error indicated by the ErrorCode.
1102 if (!rc.isOk()) {
1103 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001104 }
1105}
1106
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001107void KeyStoreService::finish(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1108 const hidl_vec<uint8_t>& signature, const hidl_vec<uint8_t>& entropy,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001109 OperationResult* result) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001110 if (!checkAllowedOperationParams(params)) {
1111 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001112 return;
1113 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001114 km_device_t dev;
1115 uint64_t handle;
1116 KeyPurpose purpose;
1117 km_id_t keyid;
1118 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001119 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001120 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001121 return;
1122 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001123 AuthorizationSet opParams = params;
1124 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1125 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001126 return;
1127 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001128
1129 if (entropy.size()) {
1130 result->resultCode = addRngEntropy(entropy);
1131 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001132 return;
1133 }
1134 }
1135
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001136 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001137 AuthorizationSet key_auths(characteristics->teeEnforced);
1138 key_auths.append(&characteristics->softwareEnforced[0],
1139 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
1140 result->resultCode = enforcement_policy.AuthorizeOperation(
1141 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1142 if (!result->resultCode.isOk()) return;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001143
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001144 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1145 const hidl_vec<uint8_t>& output) {
1146 result->resultCode = ret;
1147 if (!result->resultCode.isOk()) {
1148 return;
1149 }
1150 result->outParams = outParams;
1151 result->data = output;
1152 };
1153
1154 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->finish(
1155 handle, opParams.hidl_data(),
1156 hidl_vec<uint8_t>() /* TODO(swillden): wire up input to finish() */, signature, hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001157 // Remove the operation regardless of the result
1158 mOperationMap.removeOperation(token);
1159 mAuthTokenTable.MarkCompleted(handle);
1160
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001161 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1162 // it if there was a communication error indicated by the ErrorCode.
1163 if (!rc.isOk()) {
1164 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001165 }
1166}
1167
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001168KeyStoreServiceReturnCode KeyStoreService::abort(const sp<IBinder>& token) {
1169 km_device_t dev;
1170 uint64_t handle;
1171 KeyPurpose purpose;
1172 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001173 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001174 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001175 }
1176 mOperationMap.removeOperation(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001177
1178 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->abort(handle));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001179 mAuthTokenTable.MarkCompleted(handle);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001180 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001181}
1182
1183bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001184 km_device_t dev;
1185 uint64_t handle;
1186 const KeyCharacteristics* characteristics;
1187 KeyPurpose purpose;
1188 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001189 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1190 return false;
1191 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001192 const HardwareAuthToken* authToken = NULL;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001193 mOperationMap.getOperationAuthToken(token, &authToken);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001194 AuthorizationSet ignored;
1195 auto authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1196 return authResult.isOk();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001197}
1198
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001199KeyStoreServiceReturnCode KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
1200 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1201 // receive a HardwareAuthToken, rather than an opaque byte array.
1202
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001203 if (!checkBinderPermission(P_ADD_AUTH)) {
1204 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001205 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001206 }
1207 if (length != sizeof(hw_auth_token_t)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001208 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001209 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001210
1211 hw_auth_token_t authToken;
1212 memcpy(reinterpret_cast<void*>(&authToken), token, sizeof(hw_auth_token_t));
1213 if (authToken.version != 0) {
1214 return ErrorCode::INVALID_ARGUMENT;
1215 }
1216
1217 std::unique_ptr<HardwareAuthToken> hidlAuthToken(new HardwareAuthToken);
1218 hidlAuthToken->challenge = authToken.challenge;
1219 hidlAuthToken->userId = authToken.user_id;
1220 hidlAuthToken->authenticatorId = authToken.authenticator_id;
1221 hidlAuthToken->authenticatorType = authToken.authenticator_type;
1222 hidlAuthToken->timestamp = authToken.timestamp;
1223 static_assert(
1224 std::is_same<decltype(hidlAuthToken->hmac),
1225 ::android::hardware::hidl_array<uint8_t, sizeof(authToken.hmac)>>::value,
1226 "This function assumes token HMAC is 32 bytes, but it might not be.");
1227 std::copy(authToken.hmac, authToken.hmac + sizeof(authToken.hmac), hidlAuthToken->hmac.data());
1228
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001229 // The table takes ownership of authToken.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001230 mAuthTokenTable.AddAuthenticationToken(hidlAuthToken.release());
1231 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001232}
1233
Janis Danisevskis7612fd42016-09-01 11:50:02 +01001234constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
1235
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001236bool isDeviceIdAttestationRequested(const hidl_vec<KeyParameter>& params) {
1237 for (size_t i = 0; i < params.size(); ++i) {
1238 switch (params[i].tag) {
1239 case Tag::ATTESTATION_ID_BRAND:
1240 case Tag::ATTESTATION_ID_DEVICE:
1241 case Tag::ATTESTATION_ID_PRODUCT:
1242 case Tag::ATTESTATION_ID_SERIAL:
1243 case Tag::ATTESTATION_ID_IMEI:
1244 case Tag::ATTESTATION_ID_MEID:
1245 return true;
1246 default:
1247 break;
1248 }
1249 }
1250 return false;
1251}
1252
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001253KeyStoreServiceReturnCode KeyStoreService::attestKey(const String16& name,
1254 const hidl_vec<KeyParameter>& params,
1255 hidl_vec<hidl_vec<uint8_t>>* outChain) {
1256 if (!outChain) {
1257 return ErrorCode::OUTPUT_PARAMETER_NULL;
1258 }
Shawn Willden50eb1b22016-01-21 12:41:23 -07001259
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001260 if (!checkAllowedOperationParams(params)) {
1261 return ErrorCode::INVALID_ARGUMENT;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001262 }
1263
1264 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1265
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001266 bool attestingDeviceIds = isDeviceIdAttestationRequested(params);
1267 if (attestingDeviceIds) {
1268 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1269 if (binder == 0) {
1270 return ErrorCode::CANNOT_ATTEST_IDS;
1271 }
1272 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1273 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1274 IPCThreadState::self()->getCallingPid(), callingUid)) {
1275 return ErrorCode::CANNOT_ATTEST_IDS;
1276 }
1277 }
1278
Shawn Willden50eb1b22016-01-21 12:41:23 -07001279 Blob keyBlob;
1280 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001281 KeyStoreServiceReturnCode responseCode =
Shawn Willden50eb1b22016-01-21 12:41:23 -07001282 mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001283 if (!responseCode.isOk()) {
Shawn Willden50eb1b22016-01-21 12:41:23 -07001284 return responseCode;
1285 }
1286
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001287 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
Janis Danisevskis011675d2016-09-01 11:41:29 +01001288 if (!asn1_attestation_id_result.isOk()) {
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001289 ALOGE("failed to gather attestation_id");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001290 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001291 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001292 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001293
1294 /*
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001295 * The attestation application ID cannot be longer than
1296 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, so we truncate if too long.
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001297 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001298 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE)
1299 asn1_attestation_id.resize(KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE);
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001300
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001301 AuthorizationSet mutableParams = params;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001302
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001303 mutableParams.push_back(TAG_ATTESTATION_APPLICATION_ID, blob2hidlVec(asn1_attestation_id));
1304
1305 KeyStoreServiceReturnCode error;
1306 auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1307 error = ret;
1308 if (!error.isOk()) {
1309 return;
1310 }
1311 if (outChain) *outChain = certChain;
1312 };
1313
1314 auto hidlKey = blob2hidlVec(keyBlob);
1315 auto& dev = mKeyStore->getDevice(keyBlob);
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001316 KeyStoreServiceReturnCode attestationRc =
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001317 KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001318
1319 KeyStoreServiceReturnCode deletionRc;
1320 if (attestingDeviceIds) {
1321 // When performing device id attestation, treat the key as ephemeral and delete it straight
1322 // away.
1323 deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001324 }
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001325
1326 if (!attestationRc.isOk()) {
1327 return attestationRc;
1328 }
1329 if (!error.isOk()) {
1330 return error;
1331 }
1332 return deletionRc;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001333}
1334
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001335KeyStoreServiceReturnCode KeyStoreService::onDeviceOffBody() {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001336 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1337 mAuthTokenTable.onDeviceOffBody();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001338 return ResponseCode::NO_ERROR;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001339}
1340
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001341/**
1342 * Prune the oldest pruneable operation.
1343 */
1344bool KeyStoreService::pruneOperation() {
1345 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1346 ALOGD("Trying to prune operation %p", oldest.get());
1347 size_t op_count_before_abort = mOperationMap.getOperationCount();
1348 // We mostly ignore errors from abort() because all we care about is whether at least
1349 // one operation has been removed.
1350 int abort_error = abort(oldest);
1351 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1352 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1353 return false;
1354 }
1355 return true;
1356}
1357
1358/**
1359 * Get the effective target uid for a binder operation that takes an
1360 * optional uid as the target.
1361 */
1362uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1363 if (targetUid == UID_SELF) {
1364 return IPCThreadState::self()->getCallingUid();
1365 }
1366 return static_cast<uid_t>(targetUid);
1367}
1368
1369/**
1370 * Check if the caller of the current binder method has the required
1371 * permission and if acting on other uids the grants to do so.
1372 */
1373bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1374 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1375 pid_t spid = IPCThreadState::self()->getCallingPid();
1376 if (!has_permission(callingUid, permission, spid)) {
1377 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1378 return false;
1379 }
1380 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1381 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1382 return false;
1383 }
1384 return true;
1385}
1386
1387/**
1388 * Check if the caller of the current binder method has the required
1389 * permission and the target uid is the caller or the caller is system.
1390 */
1391bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1392 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1393 pid_t spid = IPCThreadState::self()->getCallingPid();
1394 if (!has_permission(callingUid, permission, spid)) {
1395 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1396 return false;
1397 }
1398 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1399}
1400
1401/**
1402 * Check if the caller of the current binder method has the required
1403 * permission or the target of the operation is the caller's uid. This is
1404 * for operation where the permission is only for cross-uid activity and all
1405 * uids are allowed to act on their own (ie: clearing all entries for a
1406 * given uid).
1407 */
1408bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1409 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1410 if (getEffectiveUid(targetUid) == callingUid) {
1411 return true;
1412 } else {
1413 return checkBinderPermission(permission, targetUid);
1414 }
1415}
1416
1417/**
1418 * Helper method to check that the caller has the required permission as
1419 * well as the keystore is in the unlocked state if checkUnlocked is true.
1420 *
1421 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1422 * otherwise the state of keystore when not unlocked and checkUnlocked is
1423 * true.
1424 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001425KeyStoreServiceReturnCode
1426KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1427 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001428 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001429 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001430 }
1431 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1432 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001433 // All State values coincide with ResponseCodes
1434 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001435 }
1436
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001437 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001438}
1439
1440bool KeyStoreService::isKeystoreUnlocked(State state) {
1441 switch (state) {
1442 case ::STATE_NO_ERROR:
1443 return true;
1444 case ::STATE_UNINITIALIZED:
1445 case ::STATE_LOCKED:
1446 return false;
1447 }
1448 return false;
1449}
1450
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001451/**
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001452 * Check that all KeyParameter's provided by the application are
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001453 * allowed. Any parameter that keystore adds itself should be disallowed here.
1454 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001455bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1456 for (size_t i = 0; i < params.size(); ++i) {
1457 switch (params[i].tag) {
1458 case Tag::AUTH_TOKEN:
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001459 // fall through intended
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001460 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001461 return false;
1462 default:
1463 break;
1464 }
1465 }
1466 return true;
1467}
1468
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001469ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
1470 km_device_t* dev,
1471 const AuthorizationSet& params,
1472 KeyCharacteristics* out) {
1473 hidl_vec<uint8_t> appId;
1474 hidl_vec<uint8_t> appData;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001475 for (auto param : params) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001476 if (param.tag == Tag::APPLICATION_ID) {
1477 appId = authorizationValue(TAG_APPLICATION_ID, param).value();
1478 } else if (param.tag == Tag::APPLICATION_DATA) {
1479 appData = authorizationValue(TAG_APPLICATION_DATA, param).value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001480 }
1481 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001482 ErrorCode error = ErrorCode::OK;
1483
1484 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
1485 error = ret;
1486 if (error != ErrorCode::OK) {
1487 return;
1488 }
1489 if (out) *out = keyCharacteristics;
1490 };
1491
1492 ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appData, hidlCb));
1493 if (rc != ErrorCode::OK) {
1494 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001495 }
1496 return error;
1497}
1498
1499/**
1500 * Get the auth token for this operation from the auth token table.
1501 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001502 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001503 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1504 * authorization token exists for that operation and
1505 * failOnTokenMissing is false.
1506 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1507 * token for the operation
1508 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001509KeyStoreServiceReturnCode KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics,
1510 uint64_t handle, KeyPurpose purpose,
1511 const HardwareAuthToken** authToken,
1512 bool failOnTokenMissing) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001513
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001514 AuthorizationSet allCharacteristics;
1515 for (size_t i = 0; i < characteristics.softwareEnforced.size(); i++) {
1516 allCharacteristics.push_back(characteristics.softwareEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001517 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001518 for (size_t i = 0; i < characteristics.teeEnforced.size(); i++) {
1519 allCharacteristics.push_back(characteristics.teeEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001520 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001521 AuthTokenTable::Error err =
1522 mAuthTokenTable.FindAuthorization(allCharacteristics, purpose, handle, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001523 switch (err) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001524 case AuthTokenTable::OK:
1525 case AuthTokenTable::AUTH_NOT_REQUIRED:
1526 return ResponseCode::NO_ERROR;
1527 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1528 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
1529 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
1530 return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1531 case AuthTokenTable::OP_HANDLE_REQUIRED:
1532 return failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
1533 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001534 default:
1535 ALOGE("Unexpected FindAuthorization return value %d", err);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001536 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001537 }
1538}
1539
1540/**
1541 * Add the auth token for the operation to the param list if the operation
1542 * requires authorization. Uses the cached result in the OperationMap if available
1543 * otherwise gets the token from the AuthTokenTable and caches the result.
1544 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001545 * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001546 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1547 * authenticated.
1548 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1549 * operation token.
1550 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001551KeyStoreServiceReturnCode KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
1552 AuthorizationSet* params) {
1553 const HardwareAuthToken* authToken = nullptr;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001554 mOperationMap.getOperationAuthToken(token, &authToken);
1555 if (!authToken) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001556 km_device_t dev;
1557 uint64_t handle;
1558 const KeyCharacteristics* characteristics = nullptr;
1559 KeyPurpose purpose;
1560 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001561 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001562 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001563 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001564 auto result = getAuthToken(*characteristics, handle, purpose, &authToken);
1565 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001566 return result;
1567 }
1568 if (authToken) {
1569 mOperationMap.setOperationAuthToken(token, authToken);
1570 }
1571 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001572 addAuthTokenToParams(params, authToken);
1573 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001574}
1575
1576/**
1577 * Translate a result value to a legacy return value. All keystore errors are
1578 * preserved and keymaster errors become SYSTEM_ERRORs
1579 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001580KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001581 if (result > 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001582 return static_cast<ResponseCode>(result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001583 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001584 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001585}
1586
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001587static NullOr<const Algorithm&>
1588getKeyAlgoritmFromKeyCharacteristics(const KeyCharacteristics& characteristics) {
1589 for (size_t i = 0; i < characteristics.teeEnforced.size(); ++i) {
1590 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.teeEnforced[i]);
1591 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001592 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001593 for (size_t i = 0; i < characteristics.softwareEnforced.size(); ++i) {
1594 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.softwareEnforced[i]);
1595 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001596 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001597 return {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001598}
1599
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001600void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001601 // All legacy keys are DIGEST_NONE/PAD_NONE.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001602 params->push_back(TAG_DIGEST, Digest::NONE);
1603 params->push_back(TAG_PADDING, PaddingMode::NONE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001604
1605 // Look up the algorithm of the key.
1606 KeyCharacteristics characteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001607 auto rc = getKeyCharacteristics(name, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF,
1608 &characteristics);
1609 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001610 ALOGE("Failed to get key characteristics");
1611 return;
1612 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001613 auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
1614 if (!algorithm.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001615 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1616 return;
1617 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001618 params->push_back(TAG_ALGORITHM, algorithm.value());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001619}
1620
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001621KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
1622 const hidl_vec<uint8_t>& data,
1623 hidl_vec<uint8_t>* out,
1624 const hidl_vec<uint8_t>& signature,
1625 KeyPurpose purpose) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001626
1627 std::basic_stringstream<uint8_t> outBuffer;
1628 OperationResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001629 AuthorizationSet inArgs;
1630 addLegacyBeginParams(name, &inArgs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001631 sp<IBinder> appToken(new BBinder);
1632 sp<IBinder> token;
1633
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001634 begin(appToken, name, purpose, true, inArgs.hidl_data(), hidl_vec<uint8_t>(), UID_SELF,
1635 &result);
1636 if (!result.resultCode.isOk()) {
1637 if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001638 ALOGW("Key not found");
1639 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001640 ALOGW("Error in begin: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001641 }
1642 return translateResultToLegacyResult(result.resultCode);
1643 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001644 inArgs.Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001645 token = result.token;
1646 size_t consumed = 0;
1647 size_t lastConsumed = 0;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001648 hidl_vec<uint8_t> data_view;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001649 do {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001650 data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
1651 update(token, inArgs.hidl_data(), data_view, &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001652 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001653 ALOGW("Error in update: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001654 return translateResultToLegacyResult(result.resultCode);
1655 }
1656 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001657 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001658 }
1659 lastConsumed = result.inputConsumed;
1660 consumed += lastConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001661 } while (consumed < data.size() && lastConsumed > 0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001662
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001663 if (consumed != data.size()) {
1664 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
1665 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001666 }
1667
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001668 finish(token, inArgs.hidl_data(), signature, hidl_vec<uint8_t>(), &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001669 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001670 ALOGW("Error in finish: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001671 return translateResultToLegacyResult(result.resultCode);
1672 }
1673 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001674 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001675 }
1676
1677 if (out) {
1678 auto buf = outBuffer.str();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001679 out->resize(buf.size());
1680 memcpy(&(*out)[0], buf.data(), out->size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001681 }
1682
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001683 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001684}
1685
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001686KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
1687 const AuthorizationSet& params,
1688 Blob* blob) {
Shawn Willden98c59162016-03-20 09:10:18 -06001689 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
1690 String8 name8(name);
1691 ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001692 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willden98c59162016-03-20 09:10:18 -06001693 return responseCode;
1694 }
1695
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001696 auto hidlKey = blob2hidlVec(*blob);
1697 auto& dev = mKeyStore->getDevice(*blob);
Shawn Willden98c59162016-03-20 09:10:18 -06001698
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001699 KeyStoreServiceReturnCode error;
1700 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
1701 error = ret;
1702 if (!error.isOk()) {
1703 return;
1704 }
1705
1706 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1707 error = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(uid));
1708 if (!error.isOk()) {
1709 return;
1710 }
1711
1712 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
1713 0 /* infoLength */, ::TYPE_KEYMASTER_10);
1714 newBlob.setFallback(blob->isFallback());
1715 newBlob.setEncrypted(blob->isEncrypted());
1716
1717 error = mKeyStore->put(filename.string(), &newBlob, get_user_id(uid));
1718 if (!error.isOk()) {
1719 return;
1720 }
1721
1722 // Re-read blob for caller. We can't use newBlob because writing it modified it.
1723 error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1724 };
1725
1726 KeyStoreServiceReturnCode rc =
1727 KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
1728 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001729 return rc;
1730 }
1731
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001732 return error;
Shawn Willden98c59162016-03-20 09:10:18 -06001733}
1734
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001735} // namespace android