blob: 1a60be429e0dce272ed220b42be96712ac944a7e [file] [log] [blame]
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Janis Danisevskis011675d2016-09-01 11:41:29 +010017#define LOG_TAG "keystore"
18
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070019#include "key_store_service.h"
20
21#include <fcntl.h>
22#include <sys/stat.h>
23
Janis Danisevskis7612fd42016-09-01 11:50:02 +010024#include <algorithm>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070025#include <sstream>
26
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010027#include <binder/IInterface.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070028#include <binder/IPCThreadState.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010029#include <binder/IPermissionController.h>
30#include <binder/IServiceManager.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070031
32#include <private/android_filesystem_config.h>
33
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010034#include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070035
36#include "defaults.h"
Janis Danisevskis18f27ad2016-06-01 13:57:40 -070037#include "keystore_attestation_id.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010038#include "keystore_keymaster_enforcement.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070039#include "keystore_utils.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010040#include <keystore/keystore_hidl_support.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070041
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010042namespace keystore {
Shawn Willden07aebe72017-02-28 13:53:24 -070043
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010044using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070045
Shawn Willden07aebe72017-02-28 13:53:24 -070046namespace {
47
48constexpr size_t MAX_OPERATIONS = 15;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070049
50struct BIGNUM_Delete {
51 void operator()(BIGNUM* p) const { BN_free(p); }
52};
53typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
54
Shawn Willden07aebe72017-02-28 13:53:24 -070055bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
56 return params.end() != std::find_if(params.begin(), params.end(),
57 [&](auto& param) { return param.tag == tag; });
58}
59
60bool isAuthenticationBound(const hidl_vec<KeyParameter>& params) {
61 return !containsTag(params, Tag::NO_AUTH_REQUIRED);
62}
63
64} // anonymous namespace
65
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070066void KeyStoreService::binderDied(const wp<IBinder>& who) {
67 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -070068 for (const auto& token : operations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070069 abort(token);
70 }
71}
72
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010073KeyStoreServiceReturnCode KeyStoreService::getState(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070074 if (!checkBinderPermission(P_GET_STATE)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010075 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070076 }
77
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010078 return ResponseCode(mKeyStore->getState(userId));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070079}
80
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010081KeyStoreServiceReturnCode KeyStoreService::get(const String16& name, int32_t uid,
82 hidl_vec<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070083 uid_t targetUid = getEffectiveUid(uid);
84 if (!checkBinderPermission(P_GET, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010085 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070086 }
87
88 String8 name8(name);
89 Blob keyBlob;
90
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010091 KeyStoreServiceReturnCode rc =
92 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
93 if (!rc.isOk()) {
94 if (item) *item = hidl_vec<uint8_t>();
95 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070096 }
97
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010098 // Do not replace this with "if (item) *item = blob2hidlVec(keyBlob)"!
99 // blob2hidlVec creates a hidl_vec<uint8_t> that references, but not owns, the data in keyBlob
100 // the subsequent assignment (*item = resultBlob) makes a deep copy, so that *item will own the
101 // corresponding resources.
102 auto resultBlob = blob2hidlVec(keyBlob);
103 if (item) {
104 *item = resultBlob;
105 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700106
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100107 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700108}
109
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100110KeyStoreServiceReturnCode KeyStoreService::insert(const String16& name,
111 const hidl_vec<uint8_t>& item, int targetUid,
112 int32_t flags) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700113 targetUid = getEffectiveUid(targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100114 auto result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700115 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100116 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700117 return result;
118 }
119
120 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400121 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_GENERIC));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700122
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100123 Blob keyBlob(&item[0], item.size(), NULL, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700124 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
125
126 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
127}
128
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100129KeyStoreServiceReturnCode KeyStoreService::del(const String16& name, int targetUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700130 targetUid = getEffectiveUid(targetUid);
131 if (!checkBinderPermission(P_DELETE, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100132 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700133 }
134 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000135 ALOGI("del %s %d", name8.string(), targetUid);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400136 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100137 ResponseCode result = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
138 if (result != ResponseCode::NO_ERROR) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400139 return result;
140 }
141
142 // Also delete any characteristics files
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100143 String8 chrFilename(
144 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400145 return mKeyStore->del(chrFilename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700146}
147
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100148KeyStoreServiceReturnCode KeyStoreService::exist(const String16& name, int targetUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700149 targetUid = getEffectiveUid(targetUid);
150 if (!checkBinderPermission(P_EXIST, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100151 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700152 }
153
154 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400155 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700156
157 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100158 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
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::list(const String16& prefix, int targetUid,
164 Vector<String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700165 targetUid = getEffectiveUid(targetUid);
166 if (!checkBinderPermission(P_LIST, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100167 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700168 }
169 const String8 prefix8(prefix);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400170 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid, TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700171
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100172 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
173 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700174 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100175 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700176}
177
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100178KeyStoreServiceReturnCode KeyStoreService::reset() {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700179 if (!checkBinderPermission(P_RESET)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100180 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700181 }
182
183 uid_t callingUid = IPCThreadState::self()->getCallingUid();
184 mKeyStore->resetUser(get_user_id(callingUid), false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100185 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700186}
187
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100188KeyStoreServiceReturnCode KeyStoreService::onUserPasswordChanged(int32_t userId,
189 const String16& password) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700190 if (!checkBinderPermission(P_PASSWORD)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100191 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700192 }
193
194 const String8 password8(password);
195 // Flush the auth token table to prevent stale tokens from sticking
196 // around.
197 mAuthTokenTable.Clear();
198
199 if (password.size() == 0) {
200 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
201 mKeyStore->resetUser(userId, true);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100202 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700203 } else {
204 switch (mKeyStore->getState(userId)) {
205 case ::STATE_UNINITIALIZED: {
206 // generate master key, encrypt with password, write to file,
207 // initialize mMasterKey*.
208 return mKeyStore->initializeUser(password8, userId);
209 }
210 case ::STATE_NO_ERROR: {
211 // rewrite master key with new password.
212 return mKeyStore->writeMasterKey(password8, userId);
213 }
214 case ::STATE_LOCKED: {
215 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
216 mKeyStore->resetUser(userId, true);
217 return mKeyStore->initializeUser(password8, userId);
218 }
219 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100220 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700221 }
222}
223
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100224KeyStoreServiceReturnCode KeyStoreService::onUserAdded(int32_t userId, int32_t parentId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700225 if (!checkBinderPermission(P_USER_CHANGED)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100226 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700227 }
228
229 // Sanity check that the new user has an empty keystore.
230 if (!mKeyStore->isEmpty(userId)) {
231 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
232 }
233 // Unconditionally clear the keystore, just to be safe.
234 mKeyStore->resetUser(userId, false);
235 if (parentId != -1) {
236 // This profile must share the same master key password as the parent profile. Because the
237 // password of the parent profile is not known here, the best we can do is copy the parent's
238 // master key and master key file. This makes this profile use the same master key as the
239 // parent profile, forever.
240 return mKeyStore->copyMasterKey(parentId, userId);
241 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100242 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700243 }
244}
245
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100246KeyStoreServiceReturnCode KeyStoreService::onUserRemoved(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700247 if (!checkBinderPermission(P_USER_CHANGED)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100248 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700249 }
250
251 mKeyStore->resetUser(userId, false);
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::lock(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700256 if (!checkBinderPermission(P_LOCK)) {
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_NO_ERROR) {
262 ALOGD("calling lock in state: %d", state);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100263 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700264 }
265
266 mKeyStore->lock(userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100267 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700268}
269
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100270KeyStoreServiceReturnCode KeyStoreService::unlock(int32_t userId, const String16& pw) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700271 if (!checkBinderPermission(P_UNLOCK)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100272 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700273 }
274
275 State state = mKeyStore->getState(userId);
276 if (state != ::STATE_LOCKED) {
277 switch (state) {
278 case ::STATE_NO_ERROR:
279 ALOGI("calling unlock when already unlocked, ignoring.");
280 break;
281 case ::STATE_UNINITIALIZED:
282 ALOGE("unlock called on uninitialized keystore.");
283 break;
284 default:
285 ALOGE("unlock called on keystore in unknown state: %d", state);
286 break;
287 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100288 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700289 }
290
291 const String8 password8(pw);
292 // read master key, decrypt with password, initialize mMasterKey*.
293 return mKeyStore->readMasterKey(password8, userId);
294}
295
296bool KeyStoreService::isEmpty(int32_t userId) {
297 if (!checkBinderPermission(P_IS_EMPTY)) {
298 return false;
299 }
300
301 return mKeyStore->isEmpty(userId);
302}
303
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100304KeyStoreServiceReturnCode KeyStoreService::generate(const String16& name, int32_t targetUid,
305 int32_t keyType, int32_t keySize, int32_t flags,
306 Vector<sp<KeystoreArg>>* args) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700307 targetUid = getEffectiveUid(targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100308 auto result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700309 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100310 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700311 return result;
312 }
313
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100314 keystore::AuthorizationSet params;
315 add_legacy_key_authorizations(keyType, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700316
317 switch (keyType) {
318 case EVP_PKEY_EC: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100319 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700320 if (keySize == -1) {
321 keySize = EC_DEFAULT_KEY_SIZE;
322 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
323 ALOGI("invalid key size %d", keySize);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100324 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700325 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100326 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700327 break;
328 }
329 case EVP_PKEY_RSA: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100330 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700331 if (keySize == -1) {
332 keySize = RSA_DEFAULT_KEY_SIZE;
333 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
334 ALOGI("invalid key size %d", keySize);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100335 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700336 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100337 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700338 unsigned long exponent = RSA_DEFAULT_EXPONENT;
339 if (args->size() > 1) {
340 ALOGI("invalid number of arguments: %zu", args->size());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100341 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700342 } else if (args->size() == 1) {
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700343 const sp<KeystoreArg>& expArg = args->itemAt(0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700344 if (expArg != NULL) {
345 Unique_BIGNUM pubExpBn(BN_bin2bn(
346 reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
347 if (pubExpBn.get() == NULL) {
348 ALOGI("Could not convert public exponent to BN");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100349 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700350 }
351 exponent = BN_get_word(pubExpBn.get());
352 if (exponent == 0xFFFFFFFFL) {
353 ALOGW("cannot represent public exponent as a long value");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100354 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700355 }
356 } else {
357 ALOGW("public exponent not read");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100358 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700359 }
360 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100361 params.push_back(TAG_RSA_PUBLIC_EXPONENT, exponent);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700362 break;
363 }
364 default: {
365 ALOGW("Unsupported key type %d", keyType);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100366 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700367 }
368 }
369
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100370 auto rc = generateKey(name, params.hidl_data(), hidl_vec<uint8_t>(), targetUid, flags,
371 /*outCharacteristics*/ NULL);
372 if (!rc.isOk()) {
373 ALOGW("generate failed: %d", int32_t(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700374 }
375 return translateResultToLegacyResult(rc);
376}
377
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100378KeyStoreServiceReturnCode KeyStoreService::import(const String16& name,
379 const hidl_vec<uint8_t>& data, int targetUid,
380 int32_t flags) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700381
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100382 const uint8_t* ptr = &data[0];
383
384 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, data.size()));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700385 if (!pkcs8.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100386 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700387 }
388 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
389 if (!pkey.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100390 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700391 }
392 int type = EVP_PKEY_type(pkey->type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100393 AuthorizationSet params;
394 add_legacy_key_authorizations(type, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700395 switch (type) {
396 case EVP_PKEY_RSA:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100397 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700398 break;
399 case EVP_PKEY_EC:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100400 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700401 break;
402 default:
403 ALOGW("Unsupported key type %d", type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100404 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700405 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100406
407 auto rc = importKey(name, params.hidl_data(), KeyFormat::PKCS8, data, targetUid, flags,
408 /*outCharacteristics*/ NULL);
409
410 if (!rc.isOk()) {
411 ALOGW("importKey failed: %d", int32_t(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700412 }
413 return translateResultToLegacyResult(rc);
414}
415
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100416KeyStoreServiceReturnCode KeyStoreService::sign(const String16& name, const hidl_vec<uint8_t>& data,
417 hidl_vec<uint8_t>* out) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700418 if (!checkBinderPermission(P_SIGN)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100419 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700420 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100421 return doLegacySignVerify(name, data, out, hidl_vec<uint8_t>(), KeyPurpose::SIGN);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700422}
423
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100424KeyStoreServiceReturnCode KeyStoreService::verify(const String16& name,
425 const hidl_vec<uint8_t>& data,
426 const hidl_vec<uint8_t>& signature) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700427 if (!checkBinderPermission(P_VERIFY)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100428 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700429 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100430 return doLegacySignVerify(name, data, nullptr, signature, KeyPurpose::VERIFY);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700431}
432
433/*
434 * TODO: The abstraction between things stored in hardware and regular blobs
435 * of data stored on the filesystem should be moved down to keystore itself.
436 * Unfortunately the Java code that calls this has naming conventions that it
437 * knows about. Ideally keystore shouldn't be used to store random blobs of
438 * data.
439 *
440 * Until that happens, it's necessary to have a separate "get_pubkey" and
441 * "del_key" since the Java code doesn't really communicate what it's
442 * intentions are.
443 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100444KeyStoreServiceReturnCode KeyStoreService::get_pubkey(const String16& name,
445 hidl_vec<uint8_t>* pubKey) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700446 ExportResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100447 exportKey(name, KeyFormat::X509, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF, &result);
448 if (!result.resultCode.isOk()) {
449 ALOGW("export failed: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700450 return translateResultToLegacyResult(result.resultCode);
451 }
452
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100453 if (pubKey) *pubKey = std::move(result.exportData);
454 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700455}
456
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100457KeyStoreServiceReturnCode KeyStoreService::grant(const String16& name, int32_t granteeUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700458 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100459 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
460 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700461 return result;
462 }
463
464 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400465 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700466
467 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100468 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700469 }
470
471 mKeyStore->addGrant(filename.string(), granteeUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100472 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700473}
474
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100475KeyStoreServiceReturnCode KeyStoreService::ungrant(const String16& name, int32_t granteeUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700476 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100477 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
478 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700479 return result;
480 }
481
482 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400483 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700484
485 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100486 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700487 }
488
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100489 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ResponseCode::NO_ERROR
490 : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700491}
492
493int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
494 uid_t targetUid = getEffectiveUid(uid);
495 if (!checkBinderPermission(P_GET, targetUid)) {
496 ALOGW("permission denied for %d: getmtime", targetUid);
497 return -1L;
498 }
499
500 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400501 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700502
503 if (access(filename.string(), R_OK) == -1) {
504 ALOGW("could not access %s for getmtime", filename.string());
505 return -1L;
506 }
507
508 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
509 if (fd < 0) {
510 ALOGW("could not open %s for getmtime", filename.string());
511 return -1L;
512 }
513
514 struct stat s;
515 int ret = fstat(fd, &s);
516 close(fd);
517 if (ret == -1) {
518 ALOGW("could not stat %s for getmtime", filename.string());
519 return -1L;
520 }
521
522 return static_cast<int64_t>(s.st_mtime);
523}
524
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400525// TODO(tuckeris): This is dead code, remove it. Don't bother copying over key characteristics here
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100526KeyStoreServiceReturnCode KeyStoreService::duplicate(const String16& srcKey, int32_t srcUid,
527 const String16& destKey, int32_t destUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700528 uid_t callingUid = IPCThreadState::self()->getCallingUid();
529 pid_t spid = IPCThreadState::self()->getCallingPid();
530 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
531 ALOGW("permission denied for %d: duplicate", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100532 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700533 }
534
535 State state = mKeyStore->getState(get_user_id(callingUid));
536 if (!isKeystoreUnlocked(state)) {
537 ALOGD("calling duplicate in state: %d", state);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100538 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700539 }
540
541 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
542 srcUid = callingUid;
543 } else if (!is_granted_to(callingUid, srcUid)) {
544 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100545 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700546 }
547
548 if (destUid == -1) {
549 destUid = callingUid;
550 }
551
552 if (srcUid != destUid) {
553 if (static_cast<uid_t>(srcUid) != callingUid) {
554 ALOGD("can only duplicate from caller to other or to same uid: "
555 "calling=%d, srcUid=%d, destUid=%d",
556 callingUid, srcUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100557 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700558 }
559
560 if (!is_granted_to(callingUid, destUid)) {
561 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100562 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700563 }
564 }
565
566 String8 source8(srcKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400567 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700568
569 String8 target8(destKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400570 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700571
572 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
573 ALOGD("destination already exists: %s", targetFile.string());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100574 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700575 }
576
577 Blob keyBlob;
578 ResponseCode responseCode =
579 mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, get_user_id(srcUid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100580 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700581 return responseCode;
582 }
583
584 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
585}
586
587int32_t KeyStoreService::is_hardware_backed(const String16& keyType) {
588 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
589}
590
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100591KeyStoreServiceReturnCode KeyStoreService::clear_uid(int64_t targetUid64) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700592 uid_t targetUid = getEffectiveUid(targetUid64);
593 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100594 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700595 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000596 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700597
598 String8 prefix = String8::format("%u_", targetUid);
599 Vector<String16> aliases;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100600 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
601 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700602 }
603
604 for (uint32_t i = 0; i < aliases.size(); i++) {
605 String8 name8(aliases[i]);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400606 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700607 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400608
609 // del() will fail silently if no cached characteristics are present for this alias.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100610 String8 chr_filename(
611 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400612 mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700613 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100614 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700615}
616
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100617KeyStoreServiceReturnCode KeyStoreService::addRngEntropy(const hidl_vec<uint8_t>& entropy) {
618 const auto& device = mKeyStore->getDevice();
619 return KS_HANDLE_HIDL_ERROR(device->addRngEntropy(entropy));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700620}
621
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100622KeyStoreServiceReturnCode KeyStoreService::generateKey(const String16& name,
623 const hidl_vec<KeyParameter>& params,
624 const hidl_vec<uint8_t>& entropy, int uid,
625 int flags,
626 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700627 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100628 KeyStoreServiceReturnCode rc =
629 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
630 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700631 return rc;
632 }
633
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100634 bool usingFallback = false;
635 auto& dev = mKeyStore->getDevice();
636 AuthorizationSet keyCharacteristics = params;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400637
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700638 // TODO: Seed from Linux RNG before this.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100639 rc = addRngEntropy(entropy);
640 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700641 return rc;
642 }
643
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100644 KeyStoreServiceReturnCode error;
645 auto hidl_cb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
646 const KeyCharacteristics& keyCharacteristics) {
647 error = ret;
648 if (!error.isOk()) {
649 return;
650 }
651 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700652
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100653 // Write the key
654 String8 name8(name);
655 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700656
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100657 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
658 keyBlob.setFallback(usingFallback);
Shawn Willden07aebe72017-02-28 13:53:24 -0700659 if (isAuthenticationBound(params)) {
660 keyBlob.setSuperEncrypted(true);
661 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100662 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700663
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100664 error = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
665 };
666
667 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(params, hidl_cb));
668 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400669 return rc;
670 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100671 if (!error.isOk()) {
672 ALOGE("Failed to generate key -> falling back to software keymaster");
673 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000674 auto fallback = mKeyStore->getFallbackDevice();
675 if (!fallback.isOk()) {
676 return error;
677 }
678 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->generateKey(params, hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100679 if (!rc.isOk()) {
680 return rc;
681 }
682 if (!error.isOk()) {
683 return error;
684 }
685 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400686
687 // Write the characteristics:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100688 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400689 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
690
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100691 std::stringstream kc_stream;
692 keyCharacteristics.Serialize(&kc_stream);
693 if (kc_stream.bad()) {
694 return ResponseCode::SYSTEM_ERROR;
695 }
696 auto kc_buf = kc_stream.str();
697 Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
698 ::TYPE_KEY_CHARACTERISTICS);
699 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400700 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
701
702 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700703}
704
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100705KeyStoreServiceReturnCode
706KeyStoreService::getKeyCharacteristics(const String16& name, const hidl_vec<uint8_t>& clientId,
707 const hidl_vec<uint8_t>& appData, int32_t uid,
708 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700709 if (!outCharacteristics) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100710 return ErrorCode::UNEXPECTED_NULL_POINTER;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700711 }
712
713 uid_t targetUid = getEffectiveUid(uid);
714 uid_t callingUid = IPCThreadState::self()->getCallingUid();
715 if (!is_granted_to(callingUid, targetUid)) {
716 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
717 targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100718 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700719 }
720
721 Blob keyBlob;
722 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700723
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100724 KeyStoreServiceReturnCode rc =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700725 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100726 if (!rc.isOk()) {
727 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700728 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100729
730 auto hidlKeyBlob = blob2hidlVec(keyBlob);
731 auto& dev = mKeyStore->getDevice(keyBlob);
732
733 KeyStoreServiceReturnCode error;
734
735 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
736 error = ret;
737 if (!error.isOk()) {
738 return;
Shawn Willden98c59162016-03-20 09:10:18 -0600739 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100740 *outCharacteristics = keyCharacteristics;
741 };
742
743 rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(hidlKeyBlob, clientId, appData, hidlCb));
744 if (!rc.isOk()) {
745 return rc;
746 }
747
748 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
749 AuthorizationSet upgradeParams;
750 if (clientId.size()) {
751 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
752 }
753 if (appData.size()) {
754 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
Shawn Willden98c59162016-03-20 09:10:18 -0600755 }
756 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100757 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -0600758 return rc;
759 }
Shawn Willden715d0232016-01-21 00:45:13 -0700760
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100761 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
762
763 rc = KS_HANDLE_HIDL_ERROR(
764 dev->getKeyCharacteristics(upgradedHidlKeyBlob, clientId, appData, hidlCb));
765 if (!rc.isOk()) {
766 return rc;
767 }
768 // Note that, on success, "error" will have been updated by the hidlCB callback.
769 // So it is fine to return "error" below.
770 }
771 return error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700772}
773
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100774KeyStoreServiceReturnCode
775KeyStoreService::importKey(const String16& name, const hidl_vec<KeyParameter>& params,
776 KeyFormat format, const hidl_vec<uint8_t>& keyData, int uid, int flags,
777 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700778 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100779 KeyStoreServiceReturnCode rc =
780 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
781 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700782 return rc;
783 }
784
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100785 bool usingFallback = false;
786 auto& dev = mKeyStore->getDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700787
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700788 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700789
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100790 KeyStoreServiceReturnCode error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700791
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100792 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
793 const KeyCharacteristics& keyCharacteristics) {
794 error = ret;
795 if (!error.isOk()) {
796 return;
797 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700798
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100799 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
800
801 // Write the key:
802 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
803
804 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
805 ksBlob.setFallback(usingFallback);
Shawn Willden07aebe72017-02-28 13:53:24 -0700806 if (isAuthenticationBound(params)) {
807 ksBlob.setSuperEncrypted(true);
808 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100809 ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
810
811 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
812 };
813
814 rc = KS_HANDLE_HIDL_ERROR(dev->importKey(params, format, keyData, hidlCb));
815 // possible hidl error
816 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400817 return rc;
818 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100819 // now check error from callback
820 if (!error.isOk()) {
821 ALOGE("Failed to import key -> falling back to software keymaster");
822 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000823 auto fallback = mKeyStore->getFallbackDevice();
824 if (!fallback.isOk()) {
825 return error;
826 }
827 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->importKey(params, format, keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100828 // possible hidl error
829 if (!rc.isOk()) {
830 return rc;
831 }
832 // now check error from callback
833 if (!error.isOk()) {
834 return error;
835 }
836 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400837
838 // Write the characteristics:
839 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
840
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100841 AuthorizationSet opParams = params;
842 std::stringstream kcStream;
843 opParams.Serialize(&kcStream);
844 if (kcStream.bad()) return ResponseCode::SYSTEM_ERROR;
845 auto kcBuf = kcStream.str();
846
847 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
848 ::TYPE_KEY_CHARACTERISTICS);
849 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400850 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
851
852 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700853}
854
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100855void KeyStoreService::exportKey(const String16& name, KeyFormat format,
856 const hidl_vec<uint8_t>& clientId, const hidl_vec<uint8_t>& appData,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700857 int32_t uid, ExportResult* result) {
858
859 uid_t targetUid = getEffectiveUid(uid);
860 uid_t callingUid = IPCThreadState::self()->getCallingUid();
861 if (!is_granted_to(callingUid, targetUid)) {
862 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100863 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700864 return;
865 }
866
867 Blob keyBlob;
868 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700869
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100870 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
871 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700872 return;
873 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100874
875 auto key = blob2hidlVec(keyBlob);
876 auto& dev = mKeyStore->getDevice(keyBlob);
877
878 auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
879 result->resultCode = ret;
880 if (!result->resultCode.isOk()) {
Ji Wang2c142312016-10-14 17:21:10 +0800881 return;
882 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100883 result->exportData = keyMaterial;
884 };
885 KeyStoreServiceReturnCode rc =
886 KS_HANDLE_HIDL_ERROR(dev->exportKey(format, key, clientId, appData, hidlCb));
887 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
888 // callback hidlCb.
889 if (!rc.isOk()) {
890 result->resultCode = rc;
Ji Wang2c142312016-10-14 17:21:10 +0800891 }
892
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100893 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
894 AuthorizationSet upgradeParams;
895 if (clientId.size()) {
896 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
897 }
898 if (appData.size()) {
899 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
900 }
901 result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
902 if (!result->resultCode.isOk()) {
903 return;
904 }
905
906 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
907
908 result->resultCode = KS_HANDLE_HIDL_ERROR(
909 dev->exportKey(format, upgradedHidlKeyBlob, clientId, appData, hidlCb));
910 if (!result->resultCode.isOk()) {
911 return;
912 }
913 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700914}
915
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000916static inline void addAuthTokenToParams(AuthorizationSet* params, const HardwareAuthToken* token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100917 if (token) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000918 params->push_back(TAG_AUTH_TOKEN, authToken2HidlVec(*token));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100919 }
920}
921
922void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, KeyPurpose purpose,
923 bool pruneable, const hidl_vec<KeyParameter>& params,
924 const hidl_vec<uint8_t>& entropy, int32_t uid,
925 OperationResult* result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700926 uid_t callingUid = IPCThreadState::self()->getCallingUid();
927 uid_t targetUid = getEffectiveUid(uid);
928 if (!is_granted_to(callingUid, targetUid)) {
929 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100930 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700931 return;
932 }
933 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
934 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100935 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700936 return;
937 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100938 if (!checkAllowedOperationParams(params)) {
939 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700940 return;
941 }
942 Blob keyBlob;
943 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100944 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Shawn Willden07aebe72017-02-28 13:53:24 -0700945 if (result->resultCode == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
946 result->resultCode = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
947 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100948 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700949 return;
950 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100951
952 auto key = blob2hidlVec(keyBlob);
953 auto& dev = mKeyStore->getDevice(keyBlob);
954 AuthorizationSet opParams = params;
955 KeyCharacteristics characteristics;
956 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
957
958 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
959 result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
960 if (!result->resultCode.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -0600961 return;
962 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100963 key = blob2hidlVec(keyBlob);
964 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
Shawn Willden98c59162016-03-20 09:10:18 -0600965 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100966 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700967 return;
968 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100969
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000970 const HardwareAuthToken* authToken = NULL;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400971
972 // Merge these characteristics with the ones cached when the key was generated or imported
973 Blob charBlob;
974 AuthorizationSet persistedCharacteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100975 result->resultCode =
976 mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
977 if (result->resultCode.isOk()) {
978 // TODO write one shot stream buffer to avoid copying (twice here)
979 std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
980 charBlob.getLength());
981 std::stringstream charStream(charBuffer);
982 persistedCharacteristics.Deserialize(&charStream);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400983 } else {
984 ALOGD("Unable to read cached characteristics for key");
985 }
986
987 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100988 AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
989 AuthorizationSet teeEnforced = characteristics.teeEnforced;
990 persistedCharacteristics.Union(softwareEnforced);
991 persistedCharacteristics.Subtract(teeEnforced);
992 characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400993
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100994 result->resultCode = getAuthToken(characteristics, 0, purpose, &authToken,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700995 /*failOnTokenMissing*/ false);
996 // If per-operation auth is needed we need to begin the operation and
997 // the client will need to authorize that operation before calling
998 // update. Any other auth issues stop here.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100999 if (!result->resultCode.isOk() && result->resultCode != ResponseCode::OP_AUTH_NEEDED) return;
1000
1001 addAuthTokenToParams(&opParams, authToken);
1002
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001003 // Add entropy to the device first.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001004 if (entropy.size()) {
1005 result->resultCode = addRngEntropy(entropy);
1006 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001007 return;
1008 }
1009 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001010
1011 // Create a keyid for this key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001012 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001013 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
1014 ALOGE("Failed to create a key ID for authorization checking.");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001015 result->resultCode = ErrorCode::UNKNOWN_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001016 return;
1017 }
1018
1019 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001020 AuthorizationSet key_auths = characteristics.teeEnforced;
1021 key_auths.append(&characteristics.softwareEnforced[0],
1022 &characteristics.softwareEnforced[characteristics.softwareEnforced.size()]);
1023
1024 result->resultCode = enforcement_policy.AuthorizeOperation(
1025 purpose, keyid, key_auths, opParams, 0 /* op_handle */, true /* is_begin_operation */);
1026 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001027 return;
1028 }
1029
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001030 // If there are more than MAX_OPERATIONS, abort the oldest operation that was started as
1031 // pruneable.
1032 while (mOperationMap.getOperationCount() >= MAX_OPERATIONS) {
1033 ALOGD("Reached or exceeded concurrent operations limit");
1034 if (!pruneOperation()) {
1035 break;
1036 }
1037 }
1038
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001039 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1040 uint64_t operationHandle) {
1041 result->resultCode = ret;
1042 if (!result->resultCode.isOk()) {
1043 return;
1044 }
1045 result->handle = operationHandle;
1046 result->outParams = outParams;
1047 };
1048
1049 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
1050 if (rc != ErrorCode::OK) {
1051 ALOGW("Got error %d from begin()", rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001052 }
1053
1054 // If there are too many operations abort the oldest operation that was
1055 // started as pruneable and try again.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001056 while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1057 ALOGW("Ran out of operation handles");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001058 if (!pruneOperation()) {
1059 break;
1060 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001061 rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001062 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001063 if (rc != ErrorCode::OK) {
1064 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001065 return;
1066 }
1067
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001068 // Note: The operation map takes possession of the contents of "characteristics".
1069 // It is safe to use characteristics after the following line but it will be empty.
1070 sp<IBinder> operationToken = mOperationMap.addOperation(
1071 result->handle, keyid, purpose, dev, appToken, std::move(characteristics), pruneable);
1072 assert(characteristics.teeEnforced.size() == 0);
1073 assert(characteristics.softwareEnforced.size() == 0);
1074
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001075 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001076 mOperationMap.setOperationAuthToken(operationToken, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001077 }
1078 // Return the authentication lookup result. If this is a per operation
1079 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1080 // application should get an auth token using the handle before the
1081 // first call to update, which will fail if keystore hasn't received the
1082 // auth token.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001083 // All fields but "token" were set in the begin operation's callback.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001084 result->token = operationToken;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001085}
1086
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001087void KeyStoreService::update(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1088 const hidl_vec<uint8_t>& data, OperationResult* result) {
1089 if (!checkAllowedOperationParams(params)) {
1090 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001091 return;
1092 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001093 km_device_t dev;
1094 uint64_t handle;
1095 KeyPurpose purpose;
1096 km_id_t keyid;
1097 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001098 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001099 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001100 return;
1101 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001102 AuthorizationSet opParams = params;
1103 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1104 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001105 return;
1106 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001107
1108 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001109 AuthorizationSet key_auths(characteristics->teeEnforced);
1110 key_auths.append(&characteristics->softwareEnforced[0],
1111 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001112 result->resultCode = enforcement_policy.AuthorizeOperation(
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001113 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1114 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001115 return;
1116 }
1117
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001118 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
1119 const hidl_vec<KeyParameter>& outParams, const hidl_vec<uint8_t>& output) {
1120 result->resultCode = ret;
1121 if (!result->resultCode.isOk()) {
1122 return;
1123 }
1124 result->inputConsumed = inputConsumed;
1125 result->outParams = outParams;
1126 result->data = output;
1127 };
1128
Janis Danisevskisb0245ee2017-01-25 15:43:01 +00001129 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->update(handle, opParams.hidl_data(),
1130 data, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001131 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1132 // it if there was a communication error indicated by the ErrorCode.
1133 if (!rc.isOk()) {
1134 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001135 }
1136}
1137
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001138void KeyStoreService::finish(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1139 const hidl_vec<uint8_t>& signature, const hidl_vec<uint8_t>& entropy,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001140 OperationResult* result) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001141 if (!checkAllowedOperationParams(params)) {
1142 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001143 return;
1144 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001145 km_device_t dev;
1146 uint64_t handle;
1147 KeyPurpose purpose;
1148 km_id_t keyid;
1149 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001150 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001151 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001152 return;
1153 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001154 AuthorizationSet opParams = params;
1155 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1156 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001157 return;
1158 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001159
1160 if (entropy.size()) {
1161 result->resultCode = addRngEntropy(entropy);
1162 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001163 return;
1164 }
1165 }
1166
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001167 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001168 AuthorizationSet key_auths(characteristics->teeEnforced);
1169 key_auths.append(&characteristics->softwareEnforced[0],
1170 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
1171 result->resultCode = enforcement_policy.AuthorizeOperation(
1172 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1173 if (!result->resultCode.isOk()) return;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001174
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001175 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1176 const hidl_vec<uint8_t>& output) {
1177 result->resultCode = ret;
1178 if (!result->resultCode.isOk()) {
1179 return;
1180 }
1181 result->outParams = outParams;
1182 result->data = output;
1183 };
1184
1185 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->finish(
1186 handle, opParams.hidl_data(),
1187 hidl_vec<uint8_t>() /* TODO(swillden): wire up input to finish() */, signature, hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001188 // Remove the operation regardless of the result
1189 mOperationMap.removeOperation(token);
1190 mAuthTokenTable.MarkCompleted(handle);
1191
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001192 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1193 // it if there was a communication error indicated by the ErrorCode.
1194 if (!rc.isOk()) {
1195 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001196 }
1197}
1198
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001199KeyStoreServiceReturnCode KeyStoreService::abort(const sp<IBinder>& token) {
1200 km_device_t dev;
1201 uint64_t handle;
1202 KeyPurpose purpose;
1203 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001204 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001205 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001206 }
1207 mOperationMap.removeOperation(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001208
1209 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->abort(handle));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001210 mAuthTokenTable.MarkCompleted(handle);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001211 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001212}
1213
1214bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001215 km_device_t dev;
1216 uint64_t handle;
1217 const KeyCharacteristics* characteristics;
1218 KeyPurpose purpose;
1219 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001220 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1221 return false;
1222 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001223 const HardwareAuthToken* authToken = NULL;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001224 mOperationMap.getOperationAuthToken(token, &authToken);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001225 AuthorizationSet ignored;
1226 auto authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1227 return authResult.isOk();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001228}
1229
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001230KeyStoreServiceReturnCode KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001231 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1232 // receive a HardwareAuthToken, rather than an opaque byte array.
1233
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001234 if (!checkBinderPermission(P_ADD_AUTH)) {
1235 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001236 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001237 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001238 if (length != sizeof(hw_auth_token_t)) {
1239 return ErrorCode::INVALID_ARGUMENT;
1240 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001241
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001242 hw_auth_token_t authToken;
1243 memcpy(reinterpret_cast<void*>(&authToken), token, sizeof(hw_auth_token_t));
1244 if (authToken.version != 0) {
1245 return ErrorCode::INVALID_ARGUMENT;
1246 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001247
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001248 std::unique_ptr<HardwareAuthToken> hidlAuthToken(new HardwareAuthToken);
1249 hidlAuthToken->challenge = authToken.challenge;
1250 hidlAuthToken->userId = authToken.user_id;
1251 hidlAuthToken->authenticatorId = authToken.authenticator_id;
1252 hidlAuthToken->authenticatorType = authToken.authenticator_type;
1253 hidlAuthToken->timestamp = authToken.timestamp;
1254 static_assert(
1255 std::is_same<decltype(hidlAuthToken->hmac),
1256 ::android::hardware::hidl_array<uint8_t, sizeof(authToken.hmac)>>::value,
1257 "This function assumes token HMAC is 32 bytes, but it might not be.");
1258 std::copy(authToken.hmac, authToken.hmac + sizeof(authToken.hmac), hidlAuthToken->hmac.data());
1259
1260 // The table takes ownership of authToken.
1261 mAuthTokenTable.AddAuthenticationToken(hidlAuthToken.release());
1262 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001263}
1264
Janis Danisevskis7612fd42016-09-01 11:50:02 +01001265constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
1266
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001267bool isDeviceIdAttestationRequested(const hidl_vec<KeyParameter>& params) {
1268 for (size_t i = 0; i < params.size(); ++i) {
1269 switch (params[i].tag) {
1270 case Tag::ATTESTATION_ID_BRAND:
1271 case Tag::ATTESTATION_ID_DEVICE:
1272 case Tag::ATTESTATION_ID_PRODUCT:
1273 case Tag::ATTESTATION_ID_SERIAL:
1274 case Tag::ATTESTATION_ID_IMEI:
1275 case Tag::ATTESTATION_ID_MEID:
Bartosz Fabianowski634a1aa2017-03-20 14:02:32 +01001276 case Tag::ATTESTATION_ID_MANUFACTURER:
1277 case Tag::ATTESTATION_ID_MODEL:
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001278 return true;
1279 default:
1280 break;
1281 }
1282 }
1283 return false;
1284}
1285
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001286KeyStoreServiceReturnCode KeyStoreService::attestKey(const String16& name,
1287 const hidl_vec<KeyParameter>& params,
1288 hidl_vec<hidl_vec<uint8_t>>* outChain) {
1289 if (!outChain) {
1290 return ErrorCode::OUTPUT_PARAMETER_NULL;
1291 }
Shawn Willden50eb1b22016-01-21 12:41:23 -07001292
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001293 if (!checkAllowedOperationParams(params)) {
1294 return ErrorCode::INVALID_ARGUMENT;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001295 }
1296
1297 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1298
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001299 bool attestingDeviceIds = isDeviceIdAttestationRequested(params);
1300 if (attestingDeviceIds) {
1301 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1302 if (binder == 0) {
1303 return ErrorCode::CANNOT_ATTEST_IDS;
1304 }
1305 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1306 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1307 IPCThreadState::self()->getCallingPid(), callingUid)) {
1308 return ErrorCode::CANNOT_ATTEST_IDS;
1309 }
1310 }
1311
Shawn Willden50eb1b22016-01-21 12:41:23 -07001312 Blob keyBlob;
1313 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001314 KeyStoreServiceReturnCode responseCode =
Shawn Willden50eb1b22016-01-21 12:41:23 -07001315 mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001316 if (!responseCode.isOk()) {
Shawn Willden50eb1b22016-01-21 12:41:23 -07001317 return responseCode;
1318 }
1319
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001320 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
Janis Danisevskis011675d2016-09-01 11:41:29 +01001321 if (!asn1_attestation_id_result.isOk()) {
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001322 ALOGE("failed to gather attestation_id");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001323 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001324 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001325 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001326
1327 /*
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001328 * The attestation application ID cannot be longer than
1329 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, so we truncate if too long.
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001330 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001331 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE)
1332 asn1_attestation_id.resize(KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE);
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001333
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001334 AuthorizationSet mutableParams = params;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001335
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001336 mutableParams.push_back(TAG_ATTESTATION_APPLICATION_ID, blob2hidlVec(asn1_attestation_id));
1337
1338 KeyStoreServiceReturnCode error;
1339 auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1340 error = ret;
1341 if (!error.isOk()) {
1342 return;
1343 }
1344 if (outChain) *outChain = certChain;
1345 };
1346
1347 auto hidlKey = blob2hidlVec(keyBlob);
1348 auto& dev = mKeyStore->getDevice(keyBlob);
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001349 KeyStoreServiceReturnCode attestationRc =
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001350 KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001351
1352 KeyStoreServiceReturnCode deletionRc;
1353 if (attestingDeviceIds) {
1354 // When performing device id attestation, treat the key as ephemeral and delete it straight
1355 // away.
1356 deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001357 }
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001358
1359 if (!attestationRc.isOk()) {
1360 return attestationRc;
1361 }
1362 if (!error.isOk()) {
1363 return error;
1364 }
1365 return deletionRc;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001366}
1367
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001368KeyStoreServiceReturnCode KeyStoreService::onDeviceOffBody() {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001369 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1370 mAuthTokenTable.onDeviceOffBody();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001371 return ResponseCode::NO_ERROR;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001372}
1373
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001374/**
1375 * Prune the oldest pruneable operation.
1376 */
1377bool KeyStoreService::pruneOperation() {
1378 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1379 ALOGD("Trying to prune operation %p", oldest.get());
1380 size_t op_count_before_abort = mOperationMap.getOperationCount();
1381 // We mostly ignore errors from abort() because all we care about is whether at least
1382 // one operation has been removed.
1383 int abort_error = abort(oldest);
1384 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1385 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1386 return false;
1387 }
1388 return true;
1389}
1390
1391/**
1392 * Get the effective target uid for a binder operation that takes an
1393 * optional uid as the target.
1394 */
1395uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1396 if (targetUid == UID_SELF) {
1397 return IPCThreadState::self()->getCallingUid();
1398 }
1399 return static_cast<uid_t>(targetUid);
1400}
1401
1402/**
1403 * Check if the caller of the current binder method has the required
1404 * permission and if acting on other uids the grants to do so.
1405 */
1406bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1407 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1408 pid_t spid = IPCThreadState::self()->getCallingPid();
1409 if (!has_permission(callingUid, permission, spid)) {
1410 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1411 return false;
1412 }
1413 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1414 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1415 return false;
1416 }
1417 return true;
1418}
1419
1420/**
1421 * Check if the caller of the current binder method has the required
1422 * permission and the target uid is the caller or the caller is system.
1423 */
1424bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1425 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1426 pid_t spid = IPCThreadState::self()->getCallingPid();
1427 if (!has_permission(callingUid, permission, spid)) {
1428 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1429 return false;
1430 }
1431 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1432}
1433
1434/**
1435 * Check if the caller of the current binder method has the required
1436 * permission or the target of the operation is the caller's uid. This is
1437 * for operation where the permission is only for cross-uid activity and all
1438 * uids are allowed to act on their own (ie: clearing all entries for a
1439 * given uid).
1440 */
1441bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1442 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1443 if (getEffectiveUid(targetUid) == callingUid) {
1444 return true;
1445 } else {
1446 return checkBinderPermission(permission, targetUid);
1447 }
1448}
1449
1450/**
1451 * Helper method to check that the caller has the required permission as
1452 * well as the keystore is in the unlocked state if checkUnlocked is true.
1453 *
1454 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1455 * otherwise the state of keystore when not unlocked and checkUnlocked is
1456 * true.
1457 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001458KeyStoreServiceReturnCode
1459KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1460 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001461 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001462 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001463 }
1464 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1465 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001466 // All State values coincide with ResponseCodes
1467 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001468 }
1469
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001470 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001471}
1472
1473bool KeyStoreService::isKeystoreUnlocked(State state) {
1474 switch (state) {
1475 case ::STATE_NO_ERROR:
1476 return true;
1477 case ::STATE_UNINITIALIZED:
1478 case ::STATE_LOCKED:
1479 return false;
1480 }
1481 return false;
1482}
1483
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001484/**
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001485 * Check that all KeyParameter's provided by the application are
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001486 * allowed. Any parameter that keystore adds itself should be disallowed here.
1487 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001488bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1489 for (size_t i = 0; i < params.size(); ++i) {
1490 switch (params[i].tag) {
1491 case Tag::AUTH_TOKEN:
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001492 // fall through intended
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001493 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001494 return false;
1495 default:
1496 break;
1497 }
1498 }
1499 return true;
1500}
1501
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001502ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
1503 km_device_t* dev,
1504 const AuthorizationSet& params,
1505 KeyCharacteristics* out) {
1506 hidl_vec<uint8_t> appId;
1507 hidl_vec<uint8_t> appData;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001508 for (auto param : params) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001509 if (param.tag == Tag::APPLICATION_ID) {
1510 appId = authorizationValue(TAG_APPLICATION_ID, param).value();
1511 } else if (param.tag == Tag::APPLICATION_DATA) {
1512 appData = authorizationValue(TAG_APPLICATION_DATA, param).value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001513 }
1514 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001515 ErrorCode error = ErrorCode::OK;
1516
1517 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
1518 error = ret;
1519 if (error != ErrorCode::OK) {
1520 return;
1521 }
1522 if (out) *out = keyCharacteristics;
1523 };
1524
1525 ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appData, hidlCb));
1526 if (rc != ErrorCode::OK) {
1527 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001528 }
1529 return error;
1530}
1531
1532/**
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001533 * Get the auth token for this operation from the auth token table.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001534 *
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001535 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
1536 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1537 * authorization token exists for that operation and
1538 * failOnTokenMissing is false.
1539 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1540 * token for the operation
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001541 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001542KeyStoreServiceReturnCode KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics,
1543 uint64_t handle, KeyPurpose purpose,
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001544 const HardwareAuthToken** authToken,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001545 bool failOnTokenMissing) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001546
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001547 AuthorizationSet allCharacteristics;
1548 for (size_t i = 0; i < characteristics.softwareEnforced.size(); i++) {
1549 allCharacteristics.push_back(characteristics.softwareEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001550 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001551 for (size_t i = 0; i < characteristics.teeEnforced.size(); i++) {
1552 allCharacteristics.push_back(characteristics.teeEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001553 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001554 AuthTokenTable::Error err =
1555 mAuthTokenTable.FindAuthorization(allCharacteristics, purpose, handle, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001556 switch (err) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001557 case AuthTokenTable::OK:
1558 case AuthTokenTable::AUTH_NOT_REQUIRED:
1559 return ResponseCode::NO_ERROR;
1560 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1561 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
1562 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
1563 return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1564 case AuthTokenTable::OP_HANDLE_REQUIRED:
1565 return failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
1566 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001567 default:
1568 ALOGE("Unexpected FindAuthorization return value %d", err);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001569 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001570 }
1571}
1572
1573/**
1574 * Add the auth token for the operation to the param list if the operation
1575 * requires authorization. Uses the cached result in the OperationMap if available
1576 * otherwise gets the token from the AuthTokenTable and caches the result.
1577 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001578 * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001579 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1580 * authenticated.
1581 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1582 * operation token.
1583 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001584KeyStoreServiceReturnCode KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
1585 AuthorizationSet* params) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001586 const HardwareAuthToken* authToken = nullptr;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001587 mOperationMap.getOperationAuthToken(token, &authToken);
1588 if (!authToken) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001589 km_device_t dev;
1590 uint64_t handle;
1591 const KeyCharacteristics* characteristics = nullptr;
1592 KeyPurpose purpose;
1593 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001594 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001595 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001596 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001597 auto result = getAuthToken(*characteristics, handle, purpose, &authToken);
1598 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001599 return result;
1600 }
1601 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001602 mOperationMap.setOperationAuthToken(token, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001603 }
1604 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001605 addAuthTokenToParams(params, authToken);
1606 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001607}
1608
1609/**
1610 * Translate a result value to a legacy return value. All keystore errors are
1611 * preserved and keymaster errors become SYSTEM_ERRORs
1612 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001613KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001614 if (result > 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001615 return static_cast<ResponseCode>(result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001616 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001617 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001618}
1619
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001620static NullOr<const Algorithm&>
1621getKeyAlgoritmFromKeyCharacteristics(const KeyCharacteristics& characteristics) {
1622 for (size_t i = 0; i < characteristics.teeEnforced.size(); ++i) {
1623 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.teeEnforced[i]);
1624 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001625 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001626 for (size_t i = 0; i < characteristics.softwareEnforced.size(); ++i) {
1627 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.softwareEnforced[i]);
1628 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001629 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001630 return {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001631}
1632
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001633void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001634 // All legacy keys are DIGEST_NONE/PAD_NONE.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001635 params->push_back(TAG_DIGEST, Digest::NONE);
1636 params->push_back(TAG_PADDING, PaddingMode::NONE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001637
1638 // Look up the algorithm of the key.
1639 KeyCharacteristics characteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001640 auto rc = getKeyCharacteristics(name, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF,
1641 &characteristics);
1642 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001643 ALOGE("Failed to get key characteristics");
1644 return;
1645 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001646 auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
1647 if (!algorithm.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001648 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1649 return;
1650 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001651 params->push_back(TAG_ALGORITHM, algorithm.value());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001652}
1653
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001654KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
1655 const hidl_vec<uint8_t>& data,
1656 hidl_vec<uint8_t>* out,
1657 const hidl_vec<uint8_t>& signature,
1658 KeyPurpose purpose) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001659
1660 std::basic_stringstream<uint8_t> outBuffer;
1661 OperationResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001662 AuthorizationSet inArgs;
1663 addLegacyBeginParams(name, &inArgs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001664 sp<IBinder> appToken(new BBinder);
1665 sp<IBinder> token;
1666
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001667 begin(appToken, name, purpose, true, inArgs.hidl_data(), hidl_vec<uint8_t>(), UID_SELF,
1668 &result);
1669 if (!result.resultCode.isOk()) {
1670 if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001671 ALOGW("Key not found");
1672 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001673 ALOGW("Error in begin: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001674 }
1675 return translateResultToLegacyResult(result.resultCode);
1676 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001677 inArgs.Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001678 token = result.token;
1679 size_t consumed = 0;
1680 size_t lastConsumed = 0;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001681 hidl_vec<uint8_t> data_view;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001682 do {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001683 data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
1684 update(token, inArgs.hidl_data(), data_view, &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001685 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001686 ALOGW("Error in update: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001687 return translateResultToLegacyResult(result.resultCode);
1688 }
1689 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001690 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001691 }
1692 lastConsumed = result.inputConsumed;
1693 consumed += lastConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001694 } while (consumed < data.size() && lastConsumed > 0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001695
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001696 if (consumed != data.size()) {
1697 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
1698 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001699 }
1700
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001701 finish(token, inArgs.hidl_data(), signature, hidl_vec<uint8_t>(), &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001702 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001703 ALOGW("Error in finish: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001704 return translateResultToLegacyResult(result.resultCode);
1705 }
1706 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001707 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001708 }
1709
1710 if (out) {
1711 auto buf = outBuffer.str();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001712 out->resize(buf.size());
1713 memcpy(&(*out)[0], buf.data(), out->size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001714 }
1715
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001716 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001717}
1718
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001719KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
1720 const AuthorizationSet& params,
1721 Blob* blob) {
Shawn Willden98c59162016-03-20 09:10:18 -06001722 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
1723 String8 name8(name);
1724 ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001725 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willden98c59162016-03-20 09:10:18 -06001726 return responseCode;
1727 }
Rubin Xu7675c9f2017-03-15 19:26:52 +00001728 ALOGI("upgradeKeyBlob %s %d", name8.string(), uid);
Shawn Willden98c59162016-03-20 09:10:18 -06001729
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001730 auto hidlKey = blob2hidlVec(*blob);
1731 auto& dev = mKeyStore->getDevice(*blob);
Shawn Willden98c59162016-03-20 09:10:18 -06001732
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001733 KeyStoreServiceReturnCode error;
1734 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
1735 error = ret;
1736 if (!error.isOk()) {
1737 return;
1738 }
1739
1740 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1741 error = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(uid));
1742 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001743 ALOGI("upgradeKeyBlob keystore->del failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001744 return;
1745 }
1746
1747 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
1748 0 /* infoLength */, ::TYPE_KEYMASTER_10);
1749 newBlob.setFallback(blob->isFallback());
1750 newBlob.setEncrypted(blob->isEncrypted());
1751
1752 error = mKeyStore->put(filename.string(), &newBlob, get_user_id(uid));
1753 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001754 ALOGI("upgradeKeyBlob keystore->put failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001755 return;
1756 }
1757
1758 // Re-read blob for caller. We can't use newBlob because writing it modified it.
1759 error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1760 };
1761
1762 KeyStoreServiceReturnCode rc =
1763 KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
1764 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001765 return rc;
1766 }
1767
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001768 return error;
Shawn Willden98c59162016-03-20 09:10:18 -06001769}
1770
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001771} // namespace android