blob: 417a164a8deff7b2c640795850fc3787b20df467 [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
1098 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->update(handle, params, data, hidlCb));
1099 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1100 // it if there was a communication error indicated by the ErrorCode.
1101 if (!rc.isOk()) {
1102 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001103 }
1104}
1105
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001106void KeyStoreService::finish(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1107 const hidl_vec<uint8_t>& signature, const hidl_vec<uint8_t>& entropy,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001108 OperationResult* result) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001109 if (!checkAllowedOperationParams(params)) {
1110 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001111 return;
1112 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001113 km_device_t dev;
1114 uint64_t handle;
1115 KeyPurpose purpose;
1116 km_id_t keyid;
1117 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001118 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001119 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001120 return;
1121 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001122 AuthorizationSet opParams = params;
1123 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1124 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001125 return;
1126 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001127
1128 if (entropy.size()) {
1129 result->resultCode = addRngEntropy(entropy);
1130 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001131 return;
1132 }
1133 }
1134
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001135 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001136 AuthorizationSet key_auths(characteristics->teeEnforced);
1137 key_auths.append(&characteristics->softwareEnforced[0],
1138 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
1139 result->resultCode = enforcement_policy.AuthorizeOperation(
1140 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1141 if (!result->resultCode.isOk()) return;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001142
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001143 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1144 const hidl_vec<uint8_t>& output) {
1145 result->resultCode = ret;
1146 if (!result->resultCode.isOk()) {
1147 return;
1148 }
1149 result->outParams = outParams;
1150 result->data = output;
1151 };
1152
1153 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->finish(
1154 handle, opParams.hidl_data(),
1155 hidl_vec<uint8_t>() /* TODO(swillden): wire up input to finish() */, signature, hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001156 // Remove the operation regardless of the result
1157 mOperationMap.removeOperation(token);
1158 mAuthTokenTable.MarkCompleted(handle);
1159
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001160 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1161 // it if there was a communication error indicated by the ErrorCode.
1162 if (!rc.isOk()) {
1163 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001164 }
1165}
1166
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001167KeyStoreServiceReturnCode KeyStoreService::abort(const sp<IBinder>& token) {
1168 km_device_t dev;
1169 uint64_t handle;
1170 KeyPurpose purpose;
1171 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001172 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001173 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001174 }
1175 mOperationMap.removeOperation(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001176
1177 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->abort(handle));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001178 mAuthTokenTable.MarkCompleted(handle);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001179 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001180}
1181
1182bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001183 km_device_t dev;
1184 uint64_t handle;
1185 const KeyCharacteristics* characteristics;
1186 KeyPurpose purpose;
1187 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001188 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1189 return false;
1190 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001191 const HardwareAuthToken* authToken = NULL;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001192 mOperationMap.getOperationAuthToken(token, &authToken);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001193 AuthorizationSet ignored;
1194 auto authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1195 return authResult.isOk();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001196}
1197
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001198KeyStoreServiceReturnCode KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
1199 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1200 // receive a HardwareAuthToken, rather than an opaque byte array.
1201
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001202 if (!checkBinderPermission(P_ADD_AUTH)) {
1203 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001204 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001205 }
1206 if (length != sizeof(hw_auth_token_t)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001207 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001208 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001209
1210 hw_auth_token_t authToken;
1211 memcpy(reinterpret_cast<void*>(&authToken), token, sizeof(hw_auth_token_t));
1212 if (authToken.version != 0) {
1213 return ErrorCode::INVALID_ARGUMENT;
1214 }
1215
1216 std::unique_ptr<HardwareAuthToken> hidlAuthToken(new HardwareAuthToken);
1217 hidlAuthToken->challenge = authToken.challenge;
1218 hidlAuthToken->userId = authToken.user_id;
1219 hidlAuthToken->authenticatorId = authToken.authenticator_id;
1220 hidlAuthToken->authenticatorType = authToken.authenticator_type;
1221 hidlAuthToken->timestamp = authToken.timestamp;
1222 static_assert(
1223 std::is_same<decltype(hidlAuthToken->hmac),
1224 ::android::hardware::hidl_array<uint8_t, sizeof(authToken.hmac)>>::value,
1225 "This function assumes token HMAC is 32 bytes, but it might not be.");
1226 std::copy(authToken.hmac, authToken.hmac + sizeof(authToken.hmac), hidlAuthToken->hmac.data());
1227
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001228 // The table takes ownership of authToken.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001229 mAuthTokenTable.AddAuthenticationToken(hidlAuthToken.release());
1230 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001231}
1232
Janis Danisevskis7612fd42016-09-01 11:50:02 +01001233constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
1234
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001235bool isDeviceIdAttestationRequested(const hidl_vec<KeyParameter>& params) {
1236 for (size_t i = 0; i < params.size(); ++i) {
1237 switch (params[i].tag) {
1238 case Tag::ATTESTATION_ID_BRAND:
1239 case Tag::ATTESTATION_ID_DEVICE:
1240 case Tag::ATTESTATION_ID_PRODUCT:
1241 case Tag::ATTESTATION_ID_SERIAL:
1242 case Tag::ATTESTATION_ID_IMEI:
1243 case Tag::ATTESTATION_ID_MEID:
1244 return true;
1245 default:
1246 break;
1247 }
1248 }
1249 return false;
1250}
1251
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001252KeyStoreServiceReturnCode KeyStoreService::attestKey(const String16& name,
1253 const hidl_vec<KeyParameter>& params,
1254 hidl_vec<hidl_vec<uint8_t>>* outChain) {
1255 if (!outChain) {
1256 return ErrorCode::OUTPUT_PARAMETER_NULL;
1257 }
Shawn Willden50eb1b22016-01-21 12:41:23 -07001258
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001259 if (!checkAllowedOperationParams(params)) {
1260 return ErrorCode::INVALID_ARGUMENT;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001261 }
1262
1263 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1264
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001265 bool attestingDeviceIds = isDeviceIdAttestationRequested(params);
1266 if (attestingDeviceIds) {
1267 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1268 if (binder == 0) {
1269 return ErrorCode::CANNOT_ATTEST_IDS;
1270 }
1271 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1272 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1273 IPCThreadState::self()->getCallingPid(), callingUid)) {
1274 return ErrorCode::CANNOT_ATTEST_IDS;
1275 }
1276 }
1277
Shawn Willden50eb1b22016-01-21 12:41:23 -07001278 Blob keyBlob;
1279 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001280 KeyStoreServiceReturnCode responseCode =
Shawn Willden50eb1b22016-01-21 12:41:23 -07001281 mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001282 if (!responseCode.isOk()) {
Shawn Willden50eb1b22016-01-21 12:41:23 -07001283 return responseCode;
1284 }
1285
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001286 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
Janis Danisevskis011675d2016-09-01 11:41:29 +01001287 if (!asn1_attestation_id_result.isOk()) {
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001288 ALOGE("failed to gather attestation_id");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001289 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001290 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001291 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001292
1293 /*
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001294 * The attestation application ID cannot be longer than
1295 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, so we truncate if too long.
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001296 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001297 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE)
1298 asn1_attestation_id.resize(KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE);
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001299
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001300 AuthorizationSet mutableParams = params;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001301
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001302 mutableParams.push_back(TAG_ATTESTATION_APPLICATION_ID, blob2hidlVec(asn1_attestation_id));
1303
1304 KeyStoreServiceReturnCode error;
1305 auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1306 error = ret;
1307 if (!error.isOk()) {
1308 return;
1309 }
1310 if (outChain) *outChain = certChain;
1311 };
1312
1313 auto hidlKey = blob2hidlVec(keyBlob);
1314 auto& dev = mKeyStore->getDevice(keyBlob);
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001315 KeyStoreServiceReturnCode attestationRc =
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001316 KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001317
1318 KeyStoreServiceReturnCode deletionRc;
1319 if (attestingDeviceIds) {
1320 // When performing device id attestation, treat the key as ephemeral and delete it straight
1321 // away.
1322 deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001323 }
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001324
1325 if (!attestationRc.isOk()) {
1326 return attestationRc;
1327 }
1328 if (!error.isOk()) {
1329 return error;
1330 }
1331 return deletionRc;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001332}
1333
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001334KeyStoreServiceReturnCode KeyStoreService::onDeviceOffBody() {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001335 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1336 mAuthTokenTable.onDeviceOffBody();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001337 return ResponseCode::NO_ERROR;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001338}
1339
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001340/**
1341 * Prune the oldest pruneable operation.
1342 */
1343bool KeyStoreService::pruneOperation() {
1344 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1345 ALOGD("Trying to prune operation %p", oldest.get());
1346 size_t op_count_before_abort = mOperationMap.getOperationCount();
1347 // We mostly ignore errors from abort() because all we care about is whether at least
1348 // one operation has been removed.
1349 int abort_error = abort(oldest);
1350 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1351 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1352 return false;
1353 }
1354 return true;
1355}
1356
1357/**
1358 * Get the effective target uid for a binder operation that takes an
1359 * optional uid as the target.
1360 */
1361uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1362 if (targetUid == UID_SELF) {
1363 return IPCThreadState::self()->getCallingUid();
1364 }
1365 return static_cast<uid_t>(targetUid);
1366}
1367
1368/**
1369 * Check if the caller of the current binder method has the required
1370 * permission and if acting on other uids the grants to do so.
1371 */
1372bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1373 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1374 pid_t spid = IPCThreadState::self()->getCallingPid();
1375 if (!has_permission(callingUid, permission, spid)) {
1376 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1377 return false;
1378 }
1379 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1380 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1381 return false;
1382 }
1383 return true;
1384}
1385
1386/**
1387 * Check if the caller of the current binder method has the required
1388 * permission and the target uid is the caller or the caller is system.
1389 */
1390bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1391 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1392 pid_t spid = IPCThreadState::self()->getCallingPid();
1393 if (!has_permission(callingUid, permission, spid)) {
1394 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1395 return false;
1396 }
1397 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1398}
1399
1400/**
1401 * Check if the caller of the current binder method has the required
1402 * permission or the target of the operation is the caller's uid. This is
1403 * for operation where the permission is only for cross-uid activity and all
1404 * uids are allowed to act on their own (ie: clearing all entries for a
1405 * given uid).
1406 */
1407bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1408 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1409 if (getEffectiveUid(targetUid) == callingUid) {
1410 return true;
1411 } else {
1412 return checkBinderPermission(permission, targetUid);
1413 }
1414}
1415
1416/**
1417 * Helper method to check that the caller has the required permission as
1418 * well as the keystore is in the unlocked state if checkUnlocked is true.
1419 *
1420 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1421 * otherwise the state of keystore when not unlocked and checkUnlocked is
1422 * true.
1423 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001424KeyStoreServiceReturnCode
1425KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1426 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001427 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001428 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001429 }
1430 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1431 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001432 // All State values coincide with ResponseCodes
1433 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001434 }
1435
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001436 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001437}
1438
1439bool KeyStoreService::isKeystoreUnlocked(State state) {
1440 switch (state) {
1441 case ::STATE_NO_ERROR:
1442 return true;
1443 case ::STATE_UNINITIALIZED:
1444 case ::STATE_LOCKED:
1445 return false;
1446 }
1447 return false;
1448}
1449
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001450/**
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001451 * Check that all KeyParameter's provided by the application are
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001452 * allowed. Any parameter that keystore adds itself should be disallowed here.
1453 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001454bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1455 for (size_t i = 0; i < params.size(); ++i) {
1456 switch (params[i].tag) {
1457 case Tag::AUTH_TOKEN:
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001458 // fall through intended
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001459 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001460 return false;
1461 default:
1462 break;
1463 }
1464 }
1465 return true;
1466}
1467
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001468ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
1469 km_device_t* dev,
1470 const AuthorizationSet& params,
1471 KeyCharacteristics* out) {
1472 hidl_vec<uint8_t> appId;
1473 hidl_vec<uint8_t> appData;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001474 for (auto param : params) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001475 if (param.tag == Tag::APPLICATION_ID) {
1476 appId = authorizationValue(TAG_APPLICATION_ID, param).value();
1477 } else if (param.tag == Tag::APPLICATION_DATA) {
1478 appData = authorizationValue(TAG_APPLICATION_DATA, param).value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001479 }
1480 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001481 ErrorCode error = ErrorCode::OK;
1482
1483 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
1484 error = ret;
1485 if (error != ErrorCode::OK) {
1486 return;
1487 }
1488 if (out) *out = keyCharacteristics;
1489 };
1490
1491 ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appData, hidlCb));
1492 if (rc != ErrorCode::OK) {
1493 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001494 }
1495 return error;
1496}
1497
1498/**
1499 * Get the auth token for this operation from the auth token table.
1500 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001501 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001502 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1503 * authorization token exists for that operation and
1504 * failOnTokenMissing is false.
1505 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1506 * token for the operation
1507 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001508KeyStoreServiceReturnCode KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics,
1509 uint64_t handle, KeyPurpose purpose,
1510 const HardwareAuthToken** authToken,
1511 bool failOnTokenMissing) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001512
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001513 AuthorizationSet allCharacteristics;
1514 for (size_t i = 0; i < characteristics.softwareEnforced.size(); i++) {
1515 allCharacteristics.push_back(characteristics.softwareEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001516 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001517 for (size_t i = 0; i < characteristics.teeEnforced.size(); i++) {
1518 allCharacteristics.push_back(characteristics.teeEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001519 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001520 AuthTokenTable::Error err =
1521 mAuthTokenTable.FindAuthorization(allCharacteristics, purpose, handle, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001522 switch (err) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001523 case AuthTokenTable::OK:
1524 case AuthTokenTable::AUTH_NOT_REQUIRED:
1525 return ResponseCode::NO_ERROR;
1526 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1527 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
1528 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
1529 return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1530 case AuthTokenTable::OP_HANDLE_REQUIRED:
1531 return failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
1532 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001533 default:
1534 ALOGE("Unexpected FindAuthorization return value %d", err);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001535 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001536 }
1537}
1538
1539/**
1540 * Add the auth token for the operation to the param list if the operation
1541 * requires authorization. Uses the cached result in the OperationMap if available
1542 * otherwise gets the token from the AuthTokenTable and caches the result.
1543 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001544 * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001545 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1546 * authenticated.
1547 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1548 * operation token.
1549 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001550KeyStoreServiceReturnCode KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
1551 AuthorizationSet* params) {
1552 const HardwareAuthToken* authToken = nullptr;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001553 mOperationMap.getOperationAuthToken(token, &authToken);
1554 if (!authToken) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001555 km_device_t dev;
1556 uint64_t handle;
1557 const KeyCharacteristics* characteristics = nullptr;
1558 KeyPurpose purpose;
1559 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001560 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001561 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001562 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001563 auto result = getAuthToken(*characteristics, handle, purpose, &authToken);
1564 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001565 return result;
1566 }
1567 if (authToken) {
1568 mOperationMap.setOperationAuthToken(token, authToken);
1569 }
1570 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001571 addAuthTokenToParams(params, authToken);
1572 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001573}
1574
1575/**
1576 * Translate a result value to a legacy return value. All keystore errors are
1577 * preserved and keymaster errors become SYSTEM_ERRORs
1578 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001579KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001580 if (result > 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001581 return static_cast<ResponseCode>(result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001582 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001583 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001584}
1585
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001586static NullOr<const Algorithm&>
1587getKeyAlgoritmFromKeyCharacteristics(const KeyCharacteristics& characteristics) {
1588 for (size_t i = 0; i < characteristics.teeEnforced.size(); ++i) {
1589 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.teeEnforced[i]);
1590 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001591 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001592 for (size_t i = 0; i < characteristics.softwareEnforced.size(); ++i) {
1593 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.softwareEnforced[i]);
1594 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001595 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001596 return {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001597}
1598
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001599void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001600 // All legacy keys are DIGEST_NONE/PAD_NONE.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001601 params->push_back(TAG_DIGEST, Digest::NONE);
1602 params->push_back(TAG_PADDING, PaddingMode::NONE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001603
1604 // Look up the algorithm of the key.
1605 KeyCharacteristics characteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001606 auto rc = getKeyCharacteristics(name, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF,
1607 &characteristics);
1608 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001609 ALOGE("Failed to get key characteristics");
1610 return;
1611 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001612 auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
1613 if (!algorithm.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001614 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1615 return;
1616 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001617 params->push_back(TAG_ALGORITHM, algorithm.value());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001618}
1619
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001620KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
1621 const hidl_vec<uint8_t>& data,
1622 hidl_vec<uint8_t>* out,
1623 const hidl_vec<uint8_t>& signature,
1624 KeyPurpose purpose) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001625
1626 std::basic_stringstream<uint8_t> outBuffer;
1627 OperationResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001628 AuthorizationSet inArgs;
1629 addLegacyBeginParams(name, &inArgs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001630 sp<IBinder> appToken(new BBinder);
1631 sp<IBinder> token;
1632
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001633 begin(appToken, name, purpose, true, inArgs.hidl_data(), hidl_vec<uint8_t>(), UID_SELF,
1634 &result);
1635 if (!result.resultCode.isOk()) {
1636 if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001637 ALOGW("Key not found");
1638 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001639 ALOGW("Error in begin: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001640 }
1641 return translateResultToLegacyResult(result.resultCode);
1642 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001643 inArgs.Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001644 token = result.token;
1645 size_t consumed = 0;
1646 size_t lastConsumed = 0;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001647 hidl_vec<uint8_t> data_view;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001648 do {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001649 data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
1650 update(token, inArgs.hidl_data(), data_view, &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001651 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001652 ALOGW("Error in update: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001653 return translateResultToLegacyResult(result.resultCode);
1654 }
1655 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001656 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001657 }
1658 lastConsumed = result.inputConsumed;
1659 consumed += lastConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001660 } while (consumed < data.size() && lastConsumed > 0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001661
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001662 if (consumed != data.size()) {
1663 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
1664 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001665 }
1666
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001667 finish(token, inArgs.hidl_data(), signature, hidl_vec<uint8_t>(), &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001668 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001669 ALOGW("Error in finish: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001670 return translateResultToLegacyResult(result.resultCode);
1671 }
1672 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001673 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001674 }
1675
1676 if (out) {
1677 auto buf = outBuffer.str();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001678 out->resize(buf.size());
1679 memcpy(&(*out)[0], buf.data(), out->size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001680 }
1681
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001682 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001683}
1684
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001685KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
1686 const AuthorizationSet& params,
1687 Blob* blob) {
Shawn Willden98c59162016-03-20 09:10:18 -06001688 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
1689 String8 name8(name);
1690 ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001691 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willden98c59162016-03-20 09:10:18 -06001692 return responseCode;
1693 }
1694
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001695 auto hidlKey = blob2hidlVec(*blob);
1696 auto& dev = mKeyStore->getDevice(*blob);
Shawn Willden98c59162016-03-20 09:10:18 -06001697
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001698 KeyStoreServiceReturnCode error;
1699 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
1700 error = ret;
1701 if (!error.isOk()) {
1702 return;
1703 }
1704
1705 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1706 error = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(uid));
1707 if (!error.isOk()) {
1708 return;
1709 }
1710
1711 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
1712 0 /* infoLength */, ::TYPE_KEYMASTER_10);
1713 newBlob.setFallback(blob->isFallback());
1714 newBlob.setEncrypted(blob->isEncrypted());
1715
1716 error = mKeyStore->put(filename.string(), &newBlob, get_user_id(uid));
1717 if (!error.isOk()) {
1718 return;
1719 }
1720
1721 // Re-read blob for caller. We can't use newBlob because writing it modified it.
1722 error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1723 };
1724
1725 KeyStoreServiceReturnCode rc =
1726 KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
1727 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001728 return rc;
1729 }
1730
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001731 return error;
Shawn Willden98c59162016-03-20 09:10:18 -06001732}
1733
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001734} // namespace android