blob: c2d98bb58a6def1fecd6b5db07510aefbb2afec8 [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;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000655 auto fallback = mKeyStore->getFallbackDevice();
656 if (!fallback.isOk()) {
657 return error;
658 }
659 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->generateKey(params, hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100660 if (!rc.isOk()) {
661 return rc;
662 }
663 if (!error.isOk()) {
664 return error;
665 }
666 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400667
668 // Write the characteristics:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100669 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400670 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
671
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100672 std::stringstream kc_stream;
673 keyCharacteristics.Serialize(&kc_stream);
674 if (kc_stream.bad()) {
675 return ResponseCode::SYSTEM_ERROR;
676 }
677 auto kc_buf = kc_stream.str();
678 Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
679 ::TYPE_KEY_CHARACTERISTICS);
680 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400681 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
682
683 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700684}
685
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100686KeyStoreServiceReturnCode
687KeyStoreService::getKeyCharacteristics(const String16& name, const hidl_vec<uint8_t>& clientId,
688 const hidl_vec<uint8_t>& appData, int32_t uid,
689 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700690 if (!outCharacteristics) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100691 return ErrorCode::UNEXPECTED_NULL_POINTER;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700692 }
693
694 uid_t targetUid = getEffectiveUid(uid);
695 uid_t callingUid = IPCThreadState::self()->getCallingUid();
696 if (!is_granted_to(callingUid, targetUid)) {
697 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
698 targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100699 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700700 }
701
702 Blob keyBlob;
703 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700704
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100705 KeyStoreServiceReturnCode rc =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700706 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100707 if (!rc.isOk()) {
708 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700709 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100710
711 auto hidlKeyBlob = blob2hidlVec(keyBlob);
712 auto& dev = mKeyStore->getDevice(keyBlob);
713
714 KeyStoreServiceReturnCode error;
715
716 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
717 error = ret;
718 if (!error.isOk()) {
719 return;
Shawn Willden98c59162016-03-20 09:10:18 -0600720 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100721 *outCharacteristics = keyCharacteristics;
722 };
723
724 rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(hidlKeyBlob, clientId, appData, hidlCb));
725 if (!rc.isOk()) {
726 return rc;
727 }
728
729 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
730 AuthorizationSet upgradeParams;
731 if (clientId.size()) {
732 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
733 }
734 if (appData.size()) {
735 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
Shawn Willden98c59162016-03-20 09:10:18 -0600736 }
737 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100738 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -0600739 return rc;
740 }
Shawn Willden715d0232016-01-21 00:45:13 -0700741
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100742 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
743
744 rc = KS_HANDLE_HIDL_ERROR(
745 dev->getKeyCharacteristics(upgradedHidlKeyBlob, clientId, appData, hidlCb));
746 if (!rc.isOk()) {
747 return rc;
748 }
749 // Note that, on success, "error" will have been updated by the hidlCB callback.
750 // So it is fine to return "error" below.
751 }
752 return error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700753}
754
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100755KeyStoreServiceReturnCode
756KeyStoreService::importKey(const String16& name, const hidl_vec<KeyParameter>& params,
757 KeyFormat format, const hidl_vec<uint8_t>& keyData, int uid, int flags,
758 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700759 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100760 KeyStoreServiceReturnCode rc =
761 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
762 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700763 return rc;
764 }
765
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100766 bool usingFallback = false;
767 auto& dev = mKeyStore->getDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700768
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700769 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700770
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100771 KeyStoreServiceReturnCode error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700772
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100773 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
774 const KeyCharacteristics& keyCharacteristics) {
775 error = ret;
776 if (!error.isOk()) {
777 return;
778 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700779
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100780 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
781
782 // Write the key:
783 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
784
785 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
786 ksBlob.setFallback(usingFallback);
787 ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
788
789 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
790 };
791
792 rc = KS_HANDLE_HIDL_ERROR(dev->importKey(params, format, keyData, hidlCb));
793 // possible hidl error
794 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400795 return rc;
796 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100797 // now check error from callback
798 if (!error.isOk()) {
799 ALOGE("Failed to import key -> falling back to software keymaster");
800 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000801 auto fallback = mKeyStore->getFallbackDevice();
802 if (!fallback.isOk()) {
803 return error;
804 }
805 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->importKey(params, format, keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100806 // possible hidl error
807 if (!rc.isOk()) {
808 return rc;
809 }
810 // now check error from callback
811 if (!error.isOk()) {
812 return error;
813 }
814 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400815
816 // Write the characteristics:
817 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
818
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100819 AuthorizationSet opParams = params;
820 std::stringstream kcStream;
821 opParams.Serialize(&kcStream);
822 if (kcStream.bad()) return ResponseCode::SYSTEM_ERROR;
823 auto kcBuf = kcStream.str();
824
825 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
826 ::TYPE_KEY_CHARACTERISTICS);
827 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400828 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
829
830 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700831}
832
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100833void KeyStoreService::exportKey(const String16& name, KeyFormat format,
834 const hidl_vec<uint8_t>& clientId, const hidl_vec<uint8_t>& appData,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700835 int32_t uid, ExportResult* result) {
836
837 uid_t targetUid = getEffectiveUid(uid);
838 uid_t callingUid = IPCThreadState::self()->getCallingUid();
839 if (!is_granted_to(callingUid, targetUid)) {
840 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100841 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700842 return;
843 }
844
845 Blob keyBlob;
846 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700847
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100848 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
849 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700850 return;
851 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100852
853 auto key = blob2hidlVec(keyBlob);
854 auto& dev = mKeyStore->getDevice(keyBlob);
855
856 auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
857 result->resultCode = ret;
858 if (!result->resultCode.isOk()) {
Ji Wang2c142312016-10-14 17:21:10 +0800859 return;
860 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100861 result->exportData = keyMaterial;
862 };
863 KeyStoreServiceReturnCode rc =
864 KS_HANDLE_HIDL_ERROR(dev->exportKey(format, key, clientId, appData, hidlCb));
865 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
866 // callback hidlCb.
867 if (!rc.isOk()) {
868 result->resultCode = rc;
Ji Wang2c142312016-10-14 17:21:10 +0800869 }
870
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100871 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
872 AuthorizationSet upgradeParams;
873 if (clientId.size()) {
874 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
875 }
876 if (appData.size()) {
877 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
878 }
879 result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
880 if (!result->resultCode.isOk()) {
881 return;
882 }
883
884 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
885
886 result->resultCode = KS_HANDLE_HIDL_ERROR(
887 dev->exportKey(format, upgradedHidlKeyBlob, clientId, appData, hidlCb));
888 if (!result->resultCode.isOk()) {
889 return;
890 }
891 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700892}
893
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100894static inline void addAuthTokenToParams(AuthorizationSet* params, const HardwareAuthToken* token) {
895 if (token) {
896 params->push_back(TAG_AUTH_TOKEN, authToken2HidlVec(*token));
897 }
898}
899
900void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, KeyPurpose purpose,
901 bool pruneable, const hidl_vec<KeyParameter>& params,
902 const hidl_vec<uint8_t>& entropy, int32_t uid,
903 OperationResult* result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700904 uid_t callingUid = IPCThreadState::self()->getCallingUid();
905 uid_t targetUid = getEffectiveUid(uid);
906 if (!is_granted_to(callingUid, targetUid)) {
907 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100908 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700909 return;
910 }
911 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
912 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100913 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700914 return;
915 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100916 if (!checkAllowedOperationParams(params)) {
917 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700918 return;
919 }
920 Blob keyBlob;
921 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100922 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
923 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700924 return;
925 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100926
927 auto key = blob2hidlVec(keyBlob);
928 auto& dev = mKeyStore->getDevice(keyBlob);
929 AuthorizationSet opParams = params;
930 KeyCharacteristics characteristics;
931 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
932
933 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
934 result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
935 if (!result->resultCode.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -0600936 return;
937 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100938 key = blob2hidlVec(keyBlob);
939 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
Shawn Willden98c59162016-03-20 09:10:18 -0600940 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100941 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700942 return;
943 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100944
945 const HardwareAuthToken* authToken = NULL;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400946
947 // Merge these characteristics with the ones cached when the key was generated or imported
948 Blob charBlob;
949 AuthorizationSet persistedCharacteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100950 result->resultCode =
951 mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
952 if (result->resultCode.isOk()) {
953 // TODO write one shot stream buffer to avoid copying (twice here)
954 std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
955 charBlob.getLength());
956 std::stringstream charStream(charBuffer);
957 persistedCharacteristics.Deserialize(&charStream);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400958 } else {
959 ALOGD("Unable to read cached characteristics for key");
960 }
961
962 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100963 AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
964 AuthorizationSet teeEnforced = characteristics.teeEnforced;
965 persistedCharacteristics.Union(softwareEnforced);
966 persistedCharacteristics.Subtract(teeEnforced);
967 characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400968
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100969 result->resultCode = getAuthToken(characteristics, 0, purpose, &authToken,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700970 /*failOnTokenMissing*/ false);
971 // If per-operation auth is needed we need to begin the operation and
972 // the client will need to authorize that operation before calling
973 // update. Any other auth issues stop here.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100974 if (!result->resultCode.isOk() && result->resultCode != ResponseCode::OP_AUTH_NEEDED) return;
975
976 addAuthTokenToParams(&opParams, authToken);
977
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700978 // Add entropy to the device first.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100979 if (entropy.size()) {
980 result->resultCode = addRngEntropy(entropy);
981 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700982 return;
983 }
984 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700985
986 // Create a keyid for this key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100987 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700988 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
989 ALOGE("Failed to create a key ID for authorization checking.");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100990 result->resultCode = ErrorCode::UNKNOWN_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700991 return;
992 }
993
994 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100995 AuthorizationSet key_auths = characteristics.teeEnforced;
996 key_auths.append(&characteristics.softwareEnforced[0],
997 &characteristics.softwareEnforced[characteristics.softwareEnforced.size()]);
998
999 result->resultCode = enforcement_policy.AuthorizeOperation(
1000 purpose, keyid, key_auths, opParams, 0 /* op_handle */, true /* is_begin_operation */);
1001 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001002 return;
1003 }
1004
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001005 // If there are more than MAX_OPERATIONS, abort the oldest operation that was started as
1006 // pruneable.
1007 while (mOperationMap.getOperationCount() >= MAX_OPERATIONS) {
1008 ALOGD("Reached or exceeded concurrent operations limit");
1009 if (!pruneOperation()) {
1010 break;
1011 }
1012 }
1013
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001014 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1015 uint64_t operationHandle) {
1016 result->resultCode = ret;
1017 if (!result->resultCode.isOk()) {
1018 return;
1019 }
1020 result->handle = operationHandle;
1021 result->outParams = outParams;
1022 };
1023
1024 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
1025 if (rc != ErrorCode::OK) {
1026 ALOGW("Got error %d from begin()", rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001027 }
1028
1029 // If there are too many operations abort the oldest operation that was
1030 // started as pruneable and try again.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001031 while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1032 ALOGW("Ran out of operation handles");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001033 if (!pruneOperation()) {
1034 break;
1035 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001036 rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001037 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001038 if (rc != ErrorCode::OK) {
1039 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001040 return;
1041 }
1042
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001043 // Note: The operation map takes possession of the contents of "characteristics".
1044 // It is safe to use characteristics after the following line but it will be empty.
1045 sp<IBinder> operationToken = mOperationMap.addOperation(
1046 result->handle, keyid, purpose, dev, appToken, std::move(characteristics), pruneable);
1047 assert(characteristics.teeEnforced.size() == 0);
1048 assert(characteristics.softwareEnforced.size() == 0);
1049
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001050 if (authToken) {
1051 mOperationMap.setOperationAuthToken(operationToken, authToken);
1052 }
1053 // Return the authentication lookup result. If this is a per operation
1054 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1055 // application should get an auth token using the handle before the
1056 // first call to update, which will fail if keystore hasn't received the
1057 // auth token.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001058 // All fields but "token" were set in the begin operation's callback.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001059 result->token = operationToken;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001060}
1061
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001062void KeyStoreService::update(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1063 const hidl_vec<uint8_t>& data, OperationResult* result) {
1064 if (!checkAllowedOperationParams(params)) {
1065 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001066 return;
1067 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001068 km_device_t dev;
1069 uint64_t handle;
1070 KeyPurpose purpose;
1071 km_id_t keyid;
1072 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001073 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001074 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001075 return;
1076 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001077 AuthorizationSet opParams = params;
1078 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1079 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001080 return;
1081 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001082
1083 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001084 AuthorizationSet key_auths(characteristics->teeEnforced);
1085 key_auths.append(&characteristics->softwareEnforced[0],
1086 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001087 result->resultCode = enforcement_policy.AuthorizeOperation(
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001088 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1089 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001090 return;
1091 }
1092
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001093 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
1094 const hidl_vec<KeyParameter>& outParams, const hidl_vec<uint8_t>& output) {
1095 result->resultCode = ret;
1096 if (!result->resultCode.isOk()) {
1097 return;
1098 }
1099 result->inputConsumed = inputConsumed;
1100 result->outParams = outParams;
1101 result->data = output;
1102 };
1103
Janis Danisevskisb0245ee2017-01-25 15:43:01 +00001104 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->update(handle, opParams.hidl_data(),
1105 data, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001106 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1107 // it if there was a communication error indicated by the ErrorCode.
1108 if (!rc.isOk()) {
1109 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001110 }
1111}
1112
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001113void KeyStoreService::finish(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1114 const hidl_vec<uint8_t>& signature, const hidl_vec<uint8_t>& entropy,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001115 OperationResult* result) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001116 if (!checkAllowedOperationParams(params)) {
1117 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001118 return;
1119 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001120 km_device_t dev;
1121 uint64_t handle;
1122 KeyPurpose purpose;
1123 km_id_t keyid;
1124 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001125 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001126 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001127 return;
1128 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001129 AuthorizationSet opParams = params;
1130 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1131 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001132 return;
1133 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001134
1135 if (entropy.size()) {
1136 result->resultCode = addRngEntropy(entropy);
1137 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001138 return;
1139 }
1140 }
1141
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001142 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001143 AuthorizationSet key_auths(characteristics->teeEnforced);
1144 key_auths.append(&characteristics->softwareEnforced[0],
1145 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
1146 result->resultCode = enforcement_policy.AuthorizeOperation(
1147 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1148 if (!result->resultCode.isOk()) return;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001149
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001150 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1151 const hidl_vec<uint8_t>& output) {
1152 result->resultCode = ret;
1153 if (!result->resultCode.isOk()) {
1154 return;
1155 }
1156 result->outParams = outParams;
1157 result->data = output;
1158 };
1159
1160 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->finish(
1161 handle, opParams.hidl_data(),
1162 hidl_vec<uint8_t>() /* TODO(swillden): wire up input to finish() */, signature, hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001163 // Remove the operation regardless of the result
1164 mOperationMap.removeOperation(token);
1165 mAuthTokenTable.MarkCompleted(handle);
1166
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001167 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1168 // it if there was a communication error indicated by the ErrorCode.
1169 if (!rc.isOk()) {
1170 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001171 }
1172}
1173
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001174KeyStoreServiceReturnCode KeyStoreService::abort(const sp<IBinder>& token) {
1175 km_device_t dev;
1176 uint64_t handle;
1177 KeyPurpose purpose;
1178 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001179 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001180 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001181 }
1182 mOperationMap.removeOperation(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001183
1184 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->abort(handle));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001185 mAuthTokenTable.MarkCompleted(handle);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001186 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001187}
1188
1189bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001190 km_device_t dev;
1191 uint64_t handle;
1192 const KeyCharacteristics* characteristics;
1193 KeyPurpose purpose;
1194 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001195 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1196 return false;
1197 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001198 const HardwareAuthToken* authToken = NULL;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001199 mOperationMap.getOperationAuthToken(token, &authToken);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001200 AuthorizationSet ignored;
1201 auto authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1202 return authResult.isOk();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001203}
1204
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001205KeyStoreServiceReturnCode KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
1206 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1207 // receive a HardwareAuthToken, rather than an opaque byte array.
1208
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001209 if (!checkBinderPermission(P_ADD_AUTH)) {
1210 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001211 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001212 }
1213 if (length != sizeof(hw_auth_token_t)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001214 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001215 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001216
1217 hw_auth_token_t authToken;
1218 memcpy(reinterpret_cast<void*>(&authToken), token, sizeof(hw_auth_token_t));
1219 if (authToken.version != 0) {
1220 return ErrorCode::INVALID_ARGUMENT;
1221 }
1222
1223 std::unique_ptr<HardwareAuthToken> hidlAuthToken(new HardwareAuthToken);
1224 hidlAuthToken->challenge = authToken.challenge;
1225 hidlAuthToken->userId = authToken.user_id;
1226 hidlAuthToken->authenticatorId = authToken.authenticator_id;
1227 hidlAuthToken->authenticatorType = authToken.authenticator_type;
1228 hidlAuthToken->timestamp = authToken.timestamp;
1229 static_assert(
1230 std::is_same<decltype(hidlAuthToken->hmac),
1231 ::android::hardware::hidl_array<uint8_t, sizeof(authToken.hmac)>>::value,
1232 "This function assumes token HMAC is 32 bytes, but it might not be.");
1233 std::copy(authToken.hmac, authToken.hmac + sizeof(authToken.hmac), hidlAuthToken->hmac.data());
1234
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001235 // The table takes ownership of authToken.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001236 mAuthTokenTable.AddAuthenticationToken(hidlAuthToken.release());
1237 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001238}
1239
Janis Danisevskis7612fd42016-09-01 11:50:02 +01001240constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
1241
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001242bool isDeviceIdAttestationRequested(const hidl_vec<KeyParameter>& params) {
1243 for (size_t i = 0; i < params.size(); ++i) {
1244 switch (params[i].tag) {
1245 case Tag::ATTESTATION_ID_BRAND:
1246 case Tag::ATTESTATION_ID_DEVICE:
1247 case Tag::ATTESTATION_ID_PRODUCT:
1248 case Tag::ATTESTATION_ID_SERIAL:
1249 case Tag::ATTESTATION_ID_IMEI:
1250 case Tag::ATTESTATION_ID_MEID:
1251 return true;
1252 default:
1253 break;
1254 }
1255 }
1256 return false;
1257}
1258
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001259KeyStoreServiceReturnCode KeyStoreService::attestKey(const String16& name,
1260 const hidl_vec<KeyParameter>& params,
1261 hidl_vec<hidl_vec<uint8_t>>* outChain) {
1262 if (!outChain) {
1263 return ErrorCode::OUTPUT_PARAMETER_NULL;
1264 }
Shawn Willden50eb1b22016-01-21 12:41:23 -07001265
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001266 if (!checkAllowedOperationParams(params)) {
1267 return ErrorCode::INVALID_ARGUMENT;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001268 }
1269
1270 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1271
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001272 bool attestingDeviceIds = isDeviceIdAttestationRequested(params);
1273 if (attestingDeviceIds) {
1274 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1275 if (binder == 0) {
1276 return ErrorCode::CANNOT_ATTEST_IDS;
1277 }
1278 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1279 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1280 IPCThreadState::self()->getCallingPid(), callingUid)) {
1281 return ErrorCode::CANNOT_ATTEST_IDS;
1282 }
1283 }
1284
Shawn Willden50eb1b22016-01-21 12:41:23 -07001285 Blob keyBlob;
1286 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001287 KeyStoreServiceReturnCode responseCode =
Shawn Willden50eb1b22016-01-21 12:41:23 -07001288 mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001289 if (!responseCode.isOk()) {
Shawn Willden50eb1b22016-01-21 12:41:23 -07001290 return responseCode;
1291 }
1292
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001293 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
Janis Danisevskis011675d2016-09-01 11:41:29 +01001294 if (!asn1_attestation_id_result.isOk()) {
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001295 ALOGE("failed to gather attestation_id");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001296 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001297 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001298 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001299
1300 /*
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001301 * The attestation application ID cannot be longer than
1302 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, so we truncate if too long.
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001303 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001304 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE)
1305 asn1_attestation_id.resize(KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE);
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001306
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001307 AuthorizationSet mutableParams = params;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001308
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001309 mutableParams.push_back(TAG_ATTESTATION_APPLICATION_ID, blob2hidlVec(asn1_attestation_id));
1310
1311 KeyStoreServiceReturnCode error;
1312 auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1313 error = ret;
1314 if (!error.isOk()) {
1315 return;
1316 }
1317 if (outChain) *outChain = certChain;
1318 };
1319
1320 auto hidlKey = blob2hidlVec(keyBlob);
1321 auto& dev = mKeyStore->getDevice(keyBlob);
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001322 KeyStoreServiceReturnCode attestationRc =
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001323 KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001324
1325 KeyStoreServiceReturnCode deletionRc;
1326 if (attestingDeviceIds) {
1327 // When performing device id attestation, treat the key as ephemeral and delete it straight
1328 // away.
1329 deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001330 }
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001331
1332 if (!attestationRc.isOk()) {
1333 return attestationRc;
1334 }
1335 if (!error.isOk()) {
1336 return error;
1337 }
1338 return deletionRc;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001339}
1340
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001341KeyStoreServiceReturnCode KeyStoreService::onDeviceOffBody() {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001342 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1343 mAuthTokenTable.onDeviceOffBody();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001344 return ResponseCode::NO_ERROR;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001345}
1346
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001347/**
1348 * Prune the oldest pruneable operation.
1349 */
1350bool KeyStoreService::pruneOperation() {
1351 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1352 ALOGD("Trying to prune operation %p", oldest.get());
1353 size_t op_count_before_abort = mOperationMap.getOperationCount();
1354 // We mostly ignore errors from abort() because all we care about is whether at least
1355 // one operation has been removed.
1356 int abort_error = abort(oldest);
1357 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1358 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1359 return false;
1360 }
1361 return true;
1362}
1363
1364/**
1365 * Get the effective target uid for a binder operation that takes an
1366 * optional uid as the target.
1367 */
1368uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1369 if (targetUid == UID_SELF) {
1370 return IPCThreadState::self()->getCallingUid();
1371 }
1372 return static_cast<uid_t>(targetUid);
1373}
1374
1375/**
1376 * Check if the caller of the current binder method has the required
1377 * permission and if acting on other uids the grants to do so.
1378 */
1379bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1380 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1381 pid_t spid = IPCThreadState::self()->getCallingPid();
1382 if (!has_permission(callingUid, permission, spid)) {
1383 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1384 return false;
1385 }
1386 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1387 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1388 return false;
1389 }
1390 return true;
1391}
1392
1393/**
1394 * Check if the caller of the current binder method has the required
1395 * permission and the target uid is the caller or the caller is system.
1396 */
1397bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1398 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1399 pid_t spid = IPCThreadState::self()->getCallingPid();
1400 if (!has_permission(callingUid, permission, spid)) {
1401 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1402 return false;
1403 }
1404 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1405}
1406
1407/**
1408 * Check if the caller of the current binder method has the required
1409 * permission or the target of the operation is the caller's uid. This is
1410 * for operation where the permission is only for cross-uid activity and all
1411 * uids are allowed to act on their own (ie: clearing all entries for a
1412 * given uid).
1413 */
1414bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1415 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1416 if (getEffectiveUid(targetUid) == callingUid) {
1417 return true;
1418 } else {
1419 return checkBinderPermission(permission, targetUid);
1420 }
1421}
1422
1423/**
1424 * Helper method to check that the caller has the required permission as
1425 * well as the keystore is in the unlocked state if checkUnlocked is true.
1426 *
1427 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1428 * otherwise the state of keystore when not unlocked and checkUnlocked is
1429 * true.
1430 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001431KeyStoreServiceReturnCode
1432KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1433 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001434 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001435 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001436 }
1437 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1438 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001439 // All State values coincide with ResponseCodes
1440 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001441 }
1442
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001443 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001444}
1445
1446bool KeyStoreService::isKeystoreUnlocked(State state) {
1447 switch (state) {
1448 case ::STATE_NO_ERROR:
1449 return true;
1450 case ::STATE_UNINITIALIZED:
1451 case ::STATE_LOCKED:
1452 return false;
1453 }
1454 return false;
1455}
1456
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001457/**
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001458 * Check that all KeyParameter's provided by the application are
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001459 * allowed. Any parameter that keystore adds itself should be disallowed here.
1460 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001461bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1462 for (size_t i = 0; i < params.size(); ++i) {
1463 switch (params[i].tag) {
1464 case Tag::AUTH_TOKEN:
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001465 // fall through intended
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001466 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001467 return false;
1468 default:
1469 break;
1470 }
1471 }
1472 return true;
1473}
1474
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001475ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
1476 km_device_t* dev,
1477 const AuthorizationSet& params,
1478 KeyCharacteristics* out) {
1479 hidl_vec<uint8_t> appId;
1480 hidl_vec<uint8_t> appData;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001481 for (auto param : params) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001482 if (param.tag == Tag::APPLICATION_ID) {
1483 appId = authorizationValue(TAG_APPLICATION_ID, param).value();
1484 } else if (param.tag == Tag::APPLICATION_DATA) {
1485 appData = authorizationValue(TAG_APPLICATION_DATA, param).value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001486 }
1487 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001488 ErrorCode error = ErrorCode::OK;
1489
1490 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
1491 error = ret;
1492 if (error != ErrorCode::OK) {
1493 return;
1494 }
1495 if (out) *out = keyCharacteristics;
1496 };
1497
1498 ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appData, hidlCb));
1499 if (rc != ErrorCode::OK) {
1500 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001501 }
1502 return error;
1503}
1504
1505/**
1506 * Get the auth token for this operation from the auth token table.
1507 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001508 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001509 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1510 * authorization token exists for that operation and
1511 * failOnTokenMissing is false.
1512 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1513 * token for the operation
1514 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001515KeyStoreServiceReturnCode KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics,
1516 uint64_t handle, KeyPurpose purpose,
1517 const HardwareAuthToken** authToken,
1518 bool failOnTokenMissing) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001519
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001520 AuthorizationSet allCharacteristics;
1521 for (size_t i = 0; i < characteristics.softwareEnforced.size(); i++) {
1522 allCharacteristics.push_back(characteristics.softwareEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001523 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001524 for (size_t i = 0; i < characteristics.teeEnforced.size(); i++) {
1525 allCharacteristics.push_back(characteristics.teeEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001526 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001527 AuthTokenTable::Error err =
1528 mAuthTokenTable.FindAuthorization(allCharacteristics, purpose, handle, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001529 switch (err) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001530 case AuthTokenTable::OK:
1531 case AuthTokenTable::AUTH_NOT_REQUIRED:
1532 return ResponseCode::NO_ERROR;
1533 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1534 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
1535 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
1536 return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1537 case AuthTokenTable::OP_HANDLE_REQUIRED:
1538 return failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
1539 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001540 default:
1541 ALOGE("Unexpected FindAuthorization return value %d", err);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001542 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001543 }
1544}
1545
1546/**
1547 * Add the auth token for the operation to the param list if the operation
1548 * requires authorization. Uses the cached result in the OperationMap if available
1549 * otherwise gets the token from the AuthTokenTable and caches the result.
1550 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001551 * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001552 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1553 * authenticated.
1554 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1555 * operation token.
1556 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001557KeyStoreServiceReturnCode KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
1558 AuthorizationSet* params) {
1559 const HardwareAuthToken* authToken = nullptr;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001560 mOperationMap.getOperationAuthToken(token, &authToken);
1561 if (!authToken) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001562 km_device_t dev;
1563 uint64_t handle;
1564 const KeyCharacteristics* characteristics = nullptr;
1565 KeyPurpose purpose;
1566 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001567 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001568 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001569 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001570 auto result = getAuthToken(*characteristics, handle, purpose, &authToken);
1571 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001572 return result;
1573 }
1574 if (authToken) {
1575 mOperationMap.setOperationAuthToken(token, authToken);
1576 }
1577 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001578 addAuthTokenToParams(params, authToken);
1579 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001580}
1581
1582/**
1583 * Translate a result value to a legacy return value. All keystore errors are
1584 * preserved and keymaster errors become SYSTEM_ERRORs
1585 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001586KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001587 if (result > 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001588 return static_cast<ResponseCode>(result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001589 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001590 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001591}
1592
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001593static NullOr<const Algorithm&>
1594getKeyAlgoritmFromKeyCharacteristics(const KeyCharacteristics& characteristics) {
1595 for (size_t i = 0; i < characteristics.teeEnforced.size(); ++i) {
1596 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.teeEnforced[i]);
1597 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001598 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001599 for (size_t i = 0; i < characteristics.softwareEnforced.size(); ++i) {
1600 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.softwareEnforced[i]);
1601 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001602 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001603 return {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001604}
1605
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001606void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001607 // All legacy keys are DIGEST_NONE/PAD_NONE.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001608 params->push_back(TAG_DIGEST, Digest::NONE);
1609 params->push_back(TAG_PADDING, PaddingMode::NONE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001610
1611 // Look up the algorithm of the key.
1612 KeyCharacteristics characteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001613 auto rc = getKeyCharacteristics(name, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF,
1614 &characteristics);
1615 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001616 ALOGE("Failed to get key characteristics");
1617 return;
1618 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001619 auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
1620 if (!algorithm.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001621 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1622 return;
1623 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001624 params->push_back(TAG_ALGORITHM, algorithm.value());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001625}
1626
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001627KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
1628 const hidl_vec<uint8_t>& data,
1629 hidl_vec<uint8_t>* out,
1630 const hidl_vec<uint8_t>& signature,
1631 KeyPurpose purpose) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001632
1633 std::basic_stringstream<uint8_t> outBuffer;
1634 OperationResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001635 AuthorizationSet inArgs;
1636 addLegacyBeginParams(name, &inArgs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001637 sp<IBinder> appToken(new BBinder);
1638 sp<IBinder> token;
1639
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001640 begin(appToken, name, purpose, true, inArgs.hidl_data(), hidl_vec<uint8_t>(), UID_SELF,
1641 &result);
1642 if (!result.resultCode.isOk()) {
1643 if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001644 ALOGW("Key not found");
1645 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001646 ALOGW("Error in begin: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001647 }
1648 return translateResultToLegacyResult(result.resultCode);
1649 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001650 inArgs.Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001651 token = result.token;
1652 size_t consumed = 0;
1653 size_t lastConsumed = 0;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001654 hidl_vec<uint8_t> data_view;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001655 do {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001656 data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
1657 update(token, inArgs.hidl_data(), data_view, &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001658 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001659 ALOGW("Error in update: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001660 return translateResultToLegacyResult(result.resultCode);
1661 }
1662 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001663 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001664 }
1665 lastConsumed = result.inputConsumed;
1666 consumed += lastConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001667 } while (consumed < data.size() && lastConsumed > 0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001668
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001669 if (consumed != data.size()) {
1670 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
1671 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001672 }
1673
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001674 finish(token, inArgs.hidl_data(), signature, hidl_vec<uint8_t>(), &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001675 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001676 ALOGW("Error in finish: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001677 return translateResultToLegacyResult(result.resultCode);
1678 }
1679 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001680 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001681 }
1682
1683 if (out) {
1684 auto buf = outBuffer.str();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001685 out->resize(buf.size());
1686 memcpy(&(*out)[0], buf.data(), out->size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001687 }
1688
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001689 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001690}
1691
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001692KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
1693 const AuthorizationSet& params,
1694 Blob* blob) {
Shawn Willden98c59162016-03-20 09:10:18 -06001695 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
1696 String8 name8(name);
1697 ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001698 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willden98c59162016-03-20 09:10:18 -06001699 return responseCode;
1700 }
1701
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001702 auto hidlKey = blob2hidlVec(*blob);
1703 auto& dev = mKeyStore->getDevice(*blob);
Shawn Willden98c59162016-03-20 09:10:18 -06001704
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001705 KeyStoreServiceReturnCode error;
1706 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
1707 error = ret;
1708 if (!error.isOk()) {
1709 return;
1710 }
1711
1712 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1713 error = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(uid));
1714 if (!error.isOk()) {
1715 return;
1716 }
1717
1718 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
1719 0 /* infoLength */, ::TYPE_KEYMASTER_10);
1720 newBlob.setFallback(blob->isFallback());
1721 newBlob.setEncrypted(blob->isEncrypted());
1722
1723 error = mKeyStore->put(filename.string(), &newBlob, get_user_id(uid));
1724 if (!error.isOk()) {
1725 return;
1726 }
1727
1728 // Re-read blob for caller. We can't use newBlob because writing it modified it.
1729 error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1730 };
1731
1732 KeyStoreServiceReturnCode rc =
1733 KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
1734 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001735 return rc;
1736 }
1737
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001738 return error;
Shawn Willden98c59162016-03-20 09:10:18 -06001739}
1740
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001741} // namespace android