blob: cd81674f0e41cdccb562bd114cebae7a8da39c83 [file] [log] [blame]
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Janis Danisevskis011675d2016-09-01 11:41:29 +010017#define LOG_TAG "keystore"
18
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070019#include "key_store_service.h"
20
21#include <fcntl.h>
22#include <sys/stat.h>
23
Janis Danisevskis7612fd42016-09-01 11:50:02 +010024#include <algorithm>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070025#include <sstream>
26
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010027#include <binder/IInterface.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070028#include <binder/IPCThreadState.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010029#include <binder/IPermissionController.h>
30#include <binder/IServiceManager.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070031
32#include <private/android_filesystem_config.h>
33
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010034#include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070035
36#include "defaults.h"
Janis Danisevskis18f27ad2016-06-01 13:57:40 -070037#include "keystore_attestation_id.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010038#include "keystore_keymaster_enforcement.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070039#include "keystore_utils.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010040#include <keystore/keystore_hidl_support.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070041
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010042namespace keystore {
43using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070044
45const size_t MAX_OPERATIONS = 15;
46
47struct BIGNUM_Delete {
48 void operator()(BIGNUM* p) const { BN_free(p); }
49};
50typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
51
52void KeyStoreService::binderDied(const wp<IBinder>& who) {
53 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -070054 for (const auto& token : operations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070055 abort(token);
56 }
57}
58
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010059KeyStoreServiceReturnCode KeyStoreService::getState(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070060 if (!checkBinderPermission(P_GET_STATE)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010061 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070062 }
63
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010064 return ResponseCode(mKeyStore->getState(userId));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070065}
66
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010067KeyStoreServiceReturnCode KeyStoreService::get(const String16& name, int32_t uid,
68 hidl_vec<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070069 uid_t targetUid = getEffectiveUid(uid);
70 if (!checkBinderPermission(P_GET, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010071 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070072 }
73
74 String8 name8(name);
75 Blob keyBlob;
76
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010077 KeyStoreServiceReturnCode rc =
78 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
79 if (!rc.isOk()) {
80 if (item) *item = hidl_vec<uint8_t>();
81 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070082 }
83
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010084 // Do not replace this with "if (item) *item = blob2hidlVec(keyBlob)"!
85 // blob2hidlVec creates a hidl_vec<uint8_t> that references, but not owns, the data in keyBlob
86 // the subsequent assignment (*item = resultBlob) makes a deep copy, so that *item will own the
87 // corresponding resources.
88 auto resultBlob = blob2hidlVec(keyBlob);
89 if (item) {
90 *item = resultBlob;
91 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070092
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010093 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070094}
95
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010096KeyStoreServiceReturnCode KeyStoreService::insert(const String16& name,
97 const hidl_vec<uint8_t>& item, int targetUid,
98 int32_t flags) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070099 targetUid = getEffectiveUid(targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100100 auto result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700101 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100102 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700103 return result;
104 }
105
106 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400107 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_GENERIC));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700108
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100109 Blob keyBlob(&item[0], item.size(), NULL, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700110 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
111
112 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
113}
114
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100115KeyStoreServiceReturnCode KeyStoreService::del(const String16& name, int targetUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700116 targetUid = getEffectiveUid(targetUid);
117 if (!checkBinderPermission(P_DELETE, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100118 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700119 }
120 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000121 ALOGI("del %s %d", name8.string(), targetUid);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400122 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100123 ResponseCode result = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
124 if (result != ResponseCode::NO_ERROR) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400125 return result;
126 }
127
128 // Also delete any characteristics files
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100129 String8 chrFilename(
130 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400131 return mKeyStore->del(chrFilename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700132}
133
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100134KeyStoreServiceReturnCode KeyStoreService::exist(const String16& name, int targetUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700135 targetUid = getEffectiveUid(targetUid);
136 if (!checkBinderPermission(P_EXIST, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100137 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700138 }
139
140 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400141 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700142
143 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100144 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700145 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100146 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700147}
148
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100149KeyStoreServiceReturnCode KeyStoreService::list(const String16& prefix, int targetUid,
150 Vector<String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700151 targetUid = getEffectiveUid(targetUid);
152 if (!checkBinderPermission(P_LIST, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100153 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700154 }
155 const String8 prefix8(prefix);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400156 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid, TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700157
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100158 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
159 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700160 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100161 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700162}
163
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100164KeyStoreServiceReturnCode KeyStoreService::reset() {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700165 if (!checkBinderPermission(P_RESET)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100166 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700167 }
168
169 uid_t callingUid = IPCThreadState::self()->getCallingUid();
170 mKeyStore->resetUser(get_user_id(callingUid), false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100171 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700172}
173
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100174KeyStoreServiceReturnCode KeyStoreService::onUserPasswordChanged(int32_t userId,
175 const String16& password) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700176 if (!checkBinderPermission(P_PASSWORD)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100177 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700178 }
179
180 const String8 password8(password);
181 // Flush the auth token table to prevent stale tokens from sticking
182 // around.
183 mAuthTokenTable.Clear();
184
185 if (password.size() == 0) {
186 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
187 mKeyStore->resetUser(userId, true);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100188 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700189 } else {
190 switch (mKeyStore->getState(userId)) {
191 case ::STATE_UNINITIALIZED: {
192 // generate master key, encrypt with password, write to file,
193 // initialize mMasterKey*.
194 return mKeyStore->initializeUser(password8, userId);
195 }
196 case ::STATE_NO_ERROR: {
197 // rewrite master key with new password.
198 return mKeyStore->writeMasterKey(password8, userId);
199 }
200 case ::STATE_LOCKED: {
201 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
202 mKeyStore->resetUser(userId, true);
203 return mKeyStore->initializeUser(password8, userId);
204 }
205 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100206 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700207 }
208}
209
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100210KeyStoreServiceReturnCode KeyStoreService::onUserAdded(int32_t userId, int32_t parentId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700211 if (!checkBinderPermission(P_USER_CHANGED)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100212 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700213 }
214
215 // Sanity check that the new user has an empty keystore.
216 if (!mKeyStore->isEmpty(userId)) {
217 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
218 }
219 // Unconditionally clear the keystore, just to be safe.
220 mKeyStore->resetUser(userId, false);
221 if (parentId != -1) {
222 // This profile must share the same master key password as the parent profile. Because the
223 // password of the parent profile is not known here, the best we can do is copy the parent's
224 // master key and master key file. This makes this profile use the same master key as the
225 // parent profile, forever.
226 return mKeyStore->copyMasterKey(parentId, userId);
227 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100228 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700229 }
230}
231
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100232KeyStoreServiceReturnCode KeyStoreService::onUserRemoved(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700233 if (!checkBinderPermission(P_USER_CHANGED)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100234 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700235 }
236
237 mKeyStore->resetUser(userId, false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100238 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700239}
240
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100241KeyStoreServiceReturnCode KeyStoreService::lock(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700242 if (!checkBinderPermission(P_LOCK)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100243 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700244 }
245
246 State state = mKeyStore->getState(userId);
247 if (state != ::STATE_NO_ERROR) {
248 ALOGD("calling lock in state: %d", state);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100249 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700250 }
251
252 mKeyStore->lock(userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100253 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700254}
255
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100256KeyStoreServiceReturnCode KeyStoreService::unlock(int32_t userId, const String16& pw) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700257 if (!checkBinderPermission(P_UNLOCK)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100258 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700259 }
260
261 State state = mKeyStore->getState(userId);
262 if (state != ::STATE_LOCKED) {
263 switch (state) {
264 case ::STATE_NO_ERROR:
265 ALOGI("calling unlock when already unlocked, ignoring.");
266 break;
267 case ::STATE_UNINITIALIZED:
268 ALOGE("unlock called on uninitialized keystore.");
269 break;
270 default:
271 ALOGE("unlock called on keystore in unknown state: %d", state);
272 break;
273 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100274 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700275 }
276
277 const String8 password8(pw);
278 // read master key, decrypt with password, initialize mMasterKey*.
279 return mKeyStore->readMasterKey(password8, userId);
280}
281
282bool KeyStoreService::isEmpty(int32_t userId) {
283 if (!checkBinderPermission(P_IS_EMPTY)) {
284 return false;
285 }
286
287 return mKeyStore->isEmpty(userId);
288}
289
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100290KeyStoreServiceReturnCode KeyStoreService::generate(const String16& name, int32_t targetUid,
291 int32_t keyType, int32_t keySize, int32_t flags,
292 Vector<sp<KeystoreArg>>* args) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700293 targetUid = getEffectiveUid(targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100294 auto result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700295 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100296 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700297 return result;
298 }
299
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100300 keystore::AuthorizationSet params;
301 add_legacy_key_authorizations(keyType, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700302
303 switch (keyType) {
304 case EVP_PKEY_EC: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100305 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700306 if (keySize == -1) {
307 keySize = EC_DEFAULT_KEY_SIZE;
308 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
309 ALOGI("invalid key size %d", keySize);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100310 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700311 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100312 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700313 break;
314 }
315 case EVP_PKEY_RSA: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100316 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700317 if (keySize == -1) {
318 keySize = RSA_DEFAULT_KEY_SIZE;
319 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
320 ALOGI("invalid key size %d", keySize);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100321 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700322 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100323 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700324 unsigned long exponent = RSA_DEFAULT_EXPONENT;
325 if (args->size() > 1) {
326 ALOGI("invalid number of arguments: %zu", args->size());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100327 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700328 } else if (args->size() == 1) {
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700329 const sp<KeystoreArg>& expArg = args->itemAt(0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700330 if (expArg != NULL) {
331 Unique_BIGNUM pubExpBn(BN_bin2bn(
332 reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
333 if (pubExpBn.get() == NULL) {
334 ALOGI("Could not convert public exponent to BN");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100335 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700336 }
337 exponent = BN_get_word(pubExpBn.get());
338 if (exponent == 0xFFFFFFFFL) {
339 ALOGW("cannot represent public exponent as a long value");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100340 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700341 }
342 } else {
343 ALOGW("public exponent not read");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100344 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700345 }
346 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100347 params.push_back(TAG_RSA_PUBLIC_EXPONENT, exponent);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700348 break;
349 }
350 default: {
351 ALOGW("Unsupported key type %d", keyType);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100352 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700353 }
354 }
355
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100356 auto rc = generateKey(name, params.hidl_data(), hidl_vec<uint8_t>(), targetUid, flags,
357 /*outCharacteristics*/ NULL);
358 if (!rc.isOk()) {
359 ALOGW("generate failed: %d", int32_t(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700360 }
361 return translateResultToLegacyResult(rc);
362}
363
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100364KeyStoreServiceReturnCode KeyStoreService::import(const String16& name,
365 const hidl_vec<uint8_t>& data, int targetUid,
366 int32_t flags) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700367
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100368 const uint8_t* ptr = &data[0];
369
370 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, data.size()));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700371 if (!pkcs8.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100372 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700373 }
374 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
375 if (!pkey.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100376 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700377 }
378 int type = EVP_PKEY_type(pkey->type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100379 AuthorizationSet params;
380 add_legacy_key_authorizations(type, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700381 switch (type) {
382 case EVP_PKEY_RSA:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100383 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700384 break;
385 case EVP_PKEY_EC:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100386 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700387 break;
388 default:
389 ALOGW("Unsupported key type %d", type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100390 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700391 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100392
393 auto rc = importKey(name, params.hidl_data(), KeyFormat::PKCS8, data, targetUid, flags,
394 /*outCharacteristics*/ NULL);
395
396 if (!rc.isOk()) {
397 ALOGW("importKey failed: %d", int32_t(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700398 }
399 return translateResultToLegacyResult(rc);
400}
401
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100402KeyStoreServiceReturnCode KeyStoreService::sign(const String16& name, const hidl_vec<uint8_t>& data,
403 hidl_vec<uint8_t>* out) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700404 if (!checkBinderPermission(P_SIGN)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100405 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700406 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100407 return doLegacySignVerify(name, data, out, hidl_vec<uint8_t>(), KeyPurpose::SIGN);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700408}
409
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100410KeyStoreServiceReturnCode KeyStoreService::verify(const String16& name,
411 const hidl_vec<uint8_t>& data,
412 const hidl_vec<uint8_t>& signature) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700413 if (!checkBinderPermission(P_VERIFY)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100414 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700415 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100416 return doLegacySignVerify(name, data, nullptr, signature, KeyPurpose::VERIFY);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700417}
418
419/*
420 * TODO: The abstraction between things stored in hardware and regular blobs
421 * of data stored on the filesystem should be moved down to keystore itself.
422 * Unfortunately the Java code that calls this has naming conventions that it
423 * knows about. Ideally keystore shouldn't be used to store random blobs of
424 * data.
425 *
426 * Until that happens, it's necessary to have a separate "get_pubkey" and
427 * "del_key" since the Java code doesn't really communicate what it's
428 * intentions are.
429 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100430KeyStoreServiceReturnCode KeyStoreService::get_pubkey(const String16& name,
431 hidl_vec<uint8_t>* pubKey) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700432 ExportResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100433 exportKey(name, KeyFormat::X509, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF, &result);
434 if (!result.resultCode.isOk()) {
435 ALOGW("export failed: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700436 return translateResultToLegacyResult(result.resultCode);
437 }
438
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100439 if (pubKey) *pubKey = std::move(result.exportData);
440 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700441}
442
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100443KeyStoreServiceReturnCode KeyStoreService::grant(const String16& name, int32_t granteeUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700444 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100445 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
446 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700447 return result;
448 }
449
450 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400451 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700452
453 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100454 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700455 }
456
457 mKeyStore->addGrant(filename.string(), granteeUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100458 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700459}
460
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100461KeyStoreServiceReturnCode KeyStoreService::ungrant(const String16& name, int32_t granteeUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700462 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100463 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
464 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700465 return result;
466 }
467
468 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400469 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700470
471 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100472 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700473 }
474
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100475 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ResponseCode::NO_ERROR
476 : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700477}
478
479int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
480 uid_t targetUid = getEffectiveUid(uid);
481 if (!checkBinderPermission(P_GET, targetUid)) {
482 ALOGW("permission denied for %d: getmtime", targetUid);
483 return -1L;
484 }
485
486 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400487 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700488
489 if (access(filename.string(), R_OK) == -1) {
490 ALOGW("could not access %s for getmtime", filename.string());
491 return -1L;
492 }
493
494 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
495 if (fd < 0) {
496 ALOGW("could not open %s for getmtime", filename.string());
497 return -1L;
498 }
499
500 struct stat s;
501 int ret = fstat(fd, &s);
502 close(fd);
503 if (ret == -1) {
504 ALOGW("could not stat %s for getmtime", filename.string());
505 return -1L;
506 }
507
508 return static_cast<int64_t>(s.st_mtime);
509}
510
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400511// TODO(tuckeris): This is dead code, remove it. Don't bother copying over key characteristics here
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100512KeyStoreServiceReturnCode KeyStoreService::duplicate(const String16& srcKey, int32_t srcUid,
513 const String16& destKey, int32_t destUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700514 uid_t callingUid = IPCThreadState::self()->getCallingUid();
515 pid_t spid = IPCThreadState::self()->getCallingPid();
516 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
517 ALOGW("permission denied for %d: duplicate", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100518 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700519 }
520
521 State state = mKeyStore->getState(get_user_id(callingUid));
522 if (!isKeystoreUnlocked(state)) {
523 ALOGD("calling duplicate in state: %d", state);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100524 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700525 }
526
527 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
528 srcUid = callingUid;
529 } else if (!is_granted_to(callingUid, srcUid)) {
530 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100531 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700532 }
533
534 if (destUid == -1) {
535 destUid = callingUid;
536 }
537
538 if (srcUid != destUid) {
539 if (static_cast<uid_t>(srcUid) != callingUid) {
540 ALOGD("can only duplicate from caller to other or to same uid: "
541 "calling=%d, srcUid=%d, destUid=%d",
542 callingUid, srcUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100543 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700544 }
545
546 if (!is_granted_to(callingUid, destUid)) {
547 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100548 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700549 }
550 }
551
552 String8 source8(srcKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400553 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700554
555 String8 target8(destKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400556 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700557
558 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
559 ALOGD("destination already exists: %s", targetFile.string());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100560 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700561 }
562
563 Blob keyBlob;
564 ResponseCode responseCode =
565 mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, get_user_id(srcUid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100566 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700567 return responseCode;
568 }
569
570 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
571}
572
573int32_t KeyStoreService::is_hardware_backed(const String16& keyType) {
574 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
575}
576
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100577KeyStoreServiceReturnCode KeyStoreService::clear_uid(int64_t targetUid64) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700578 uid_t targetUid = getEffectiveUid(targetUid64);
579 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100580 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700581 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000582 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700583
584 String8 prefix = String8::format("%u_", targetUid);
585 Vector<String16> aliases;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100586 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
587 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700588 }
589
590 for (uint32_t i = 0; i < aliases.size(); i++) {
591 String8 name8(aliases[i]);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400592 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700593 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400594
595 // del() will fail silently if no cached characteristics are present for this alias.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100596 String8 chr_filename(
597 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400598 mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700599 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100600 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700601}
602
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100603KeyStoreServiceReturnCode KeyStoreService::addRngEntropy(const hidl_vec<uint8_t>& entropy) {
604 const auto& device = mKeyStore->getDevice();
605 return KS_HANDLE_HIDL_ERROR(device->addRngEntropy(entropy));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700606}
607
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100608KeyStoreServiceReturnCode KeyStoreService::generateKey(const String16& name,
609 const hidl_vec<KeyParameter>& params,
610 const hidl_vec<uint8_t>& entropy, int uid,
611 int flags,
612 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700613 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100614 KeyStoreServiceReturnCode rc =
615 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
616 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700617 return rc;
618 }
619
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100620 bool usingFallback = false;
621 auto& dev = mKeyStore->getDevice();
622 AuthorizationSet keyCharacteristics = params;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400623
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700624 // TODO: Seed from Linux RNG before this.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100625 rc = addRngEntropy(entropy);
626 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700627 return rc;
628 }
629
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100630 KeyStoreServiceReturnCode error;
631 auto hidl_cb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
632 const KeyCharacteristics& keyCharacteristics) {
633 error = ret;
634 if (!error.isOk()) {
635 return;
636 }
637 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700638
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100639 // Write the key
640 String8 name8(name);
641 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700642
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100643 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
644 keyBlob.setFallback(usingFallback);
645 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700646
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100647 error = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
648 };
649
650 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(params, hidl_cb));
651 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400652 return rc;
653 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100654 if (!error.isOk()) {
655 ALOGE("Failed to generate key -> falling back to software keymaster");
656 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000657 auto fallback = mKeyStore->getFallbackDevice();
658 if (!fallback.isOk()) {
659 return error;
660 }
661 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->generateKey(params, hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100662 if (!rc.isOk()) {
663 return rc;
664 }
665 if (!error.isOk()) {
666 return error;
667 }
668 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400669
670 // Write the characteristics:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100671 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400672 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
673
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100674 std::stringstream kc_stream;
675 keyCharacteristics.Serialize(&kc_stream);
676 if (kc_stream.bad()) {
677 return ResponseCode::SYSTEM_ERROR;
678 }
679 auto kc_buf = kc_stream.str();
680 Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
681 ::TYPE_KEY_CHARACTERISTICS);
682 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400683 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
684
685 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700686}
687
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100688KeyStoreServiceReturnCode
689KeyStoreService::getKeyCharacteristics(const String16& name, const hidl_vec<uint8_t>& clientId,
690 const hidl_vec<uint8_t>& appData, int32_t uid,
691 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700692 if (!outCharacteristics) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100693 return ErrorCode::UNEXPECTED_NULL_POINTER;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700694 }
695
696 uid_t targetUid = getEffectiveUid(uid);
697 uid_t callingUid = IPCThreadState::self()->getCallingUid();
698 if (!is_granted_to(callingUid, targetUid)) {
699 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
700 targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100701 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700702 }
703
704 Blob keyBlob;
705 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700706
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100707 KeyStoreServiceReturnCode rc =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700708 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100709 if (!rc.isOk()) {
710 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700711 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100712
713 auto hidlKeyBlob = blob2hidlVec(keyBlob);
714 auto& dev = mKeyStore->getDevice(keyBlob);
715
716 KeyStoreServiceReturnCode error;
717
718 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
719 error = ret;
720 if (!error.isOk()) {
721 return;
Shawn Willden98c59162016-03-20 09:10:18 -0600722 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100723 *outCharacteristics = keyCharacteristics;
724 };
725
726 rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(hidlKeyBlob, clientId, appData, hidlCb));
727 if (!rc.isOk()) {
728 return rc;
729 }
730
731 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
732 AuthorizationSet upgradeParams;
733 if (clientId.size()) {
734 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
735 }
736 if (appData.size()) {
737 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
Shawn Willden98c59162016-03-20 09:10:18 -0600738 }
739 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100740 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -0600741 return rc;
742 }
Shawn Willden715d0232016-01-21 00:45:13 -0700743
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100744 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
745
746 rc = KS_HANDLE_HIDL_ERROR(
747 dev->getKeyCharacteristics(upgradedHidlKeyBlob, clientId, appData, hidlCb));
748 if (!rc.isOk()) {
749 return rc;
750 }
751 // Note that, on success, "error" will have been updated by the hidlCB callback.
752 // So it is fine to return "error" below.
753 }
754 return error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700755}
756
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100757KeyStoreServiceReturnCode
758KeyStoreService::importKey(const String16& name, const hidl_vec<KeyParameter>& params,
759 KeyFormat format, const hidl_vec<uint8_t>& keyData, int uid, int flags,
760 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700761 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100762 KeyStoreServiceReturnCode rc =
763 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
764 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700765 return rc;
766 }
767
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100768 bool usingFallback = false;
769 auto& dev = mKeyStore->getDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700770
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700771 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700772
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100773 KeyStoreServiceReturnCode error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700774
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100775 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
776 const KeyCharacteristics& keyCharacteristics) {
777 error = ret;
778 if (!error.isOk()) {
779 return;
780 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700781
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100782 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
783
784 // Write the key:
785 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
786
787 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
788 ksBlob.setFallback(usingFallback);
789 ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
790
791 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
792 };
793
794 rc = KS_HANDLE_HIDL_ERROR(dev->importKey(params, format, keyData, hidlCb));
795 // possible hidl error
796 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400797 return rc;
798 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100799 // now check error from callback
800 if (!error.isOk()) {
801 ALOGE("Failed to import key -> falling back to software keymaster");
802 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000803 auto fallback = mKeyStore->getFallbackDevice();
804 if (!fallback.isOk()) {
805 return error;
806 }
807 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->importKey(params, format, keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100808 // possible hidl error
809 if (!rc.isOk()) {
810 return rc;
811 }
812 // now check error from callback
813 if (!error.isOk()) {
814 return error;
815 }
816 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400817
818 // Write the characteristics:
819 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
820
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100821 AuthorizationSet opParams = params;
822 std::stringstream kcStream;
823 opParams.Serialize(&kcStream);
824 if (kcStream.bad()) return ResponseCode::SYSTEM_ERROR;
825 auto kcBuf = kcStream.str();
826
827 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
828 ::TYPE_KEY_CHARACTERISTICS);
829 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400830 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
831
832 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700833}
834
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100835void KeyStoreService::exportKey(const String16& name, KeyFormat format,
836 const hidl_vec<uint8_t>& clientId, const hidl_vec<uint8_t>& appData,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700837 int32_t uid, ExportResult* result) {
838
839 uid_t targetUid = getEffectiveUid(uid);
840 uid_t callingUid = IPCThreadState::self()->getCallingUid();
841 if (!is_granted_to(callingUid, targetUid)) {
842 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100843 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700844 return;
845 }
846
847 Blob keyBlob;
848 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700849
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100850 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
851 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700852 return;
853 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100854
855 auto key = blob2hidlVec(keyBlob);
856 auto& dev = mKeyStore->getDevice(keyBlob);
857
858 auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
859 result->resultCode = ret;
860 if (!result->resultCode.isOk()) {
Ji Wang2c142312016-10-14 17:21:10 +0800861 return;
862 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100863 result->exportData = keyMaterial;
864 };
865 KeyStoreServiceReturnCode rc =
866 KS_HANDLE_HIDL_ERROR(dev->exportKey(format, key, clientId, appData, hidlCb));
867 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
868 // callback hidlCb.
869 if (!rc.isOk()) {
870 result->resultCode = rc;
Ji Wang2c142312016-10-14 17:21:10 +0800871 }
872
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100873 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
874 AuthorizationSet upgradeParams;
875 if (clientId.size()) {
876 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
877 }
878 if (appData.size()) {
879 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
880 }
881 result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
882 if (!result->resultCode.isOk()) {
883 return;
884 }
885
886 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
887
888 result->resultCode = KS_HANDLE_HIDL_ERROR(
889 dev->exportKey(format, upgradedHidlKeyBlob, clientId, appData, hidlCb));
890 if (!result->resultCode.isOk()) {
891 return;
892 }
893 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700894}
895
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100896static inline void addAuthTokenToParams(AuthorizationSet* params, const HardwareAuthToken* token) {
897 if (token) {
898 params->push_back(TAG_AUTH_TOKEN, authToken2HidlVec(*token));
899 }
900}
901
902void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, KeyPurpose purpose,
903 bool pruneable, const hidl_vec<KeyParameter>& params,
904 const hidl_vec<uint8_t>& entropy, int32_t uid,
905 OperationResult* result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700906 uid_t callingUid = IPCThreadState::self()->getCallingUid();
907 uid_t targetUid = getEffectiveUid(uid);
908 if (!is_granted_to(callingUid, targetUid)) {
909 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100910 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700911 return;
912 }
913 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
914 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100915 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700916 return;
917 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100918 if (!checkAllowedOperationParams(params)) {
919 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700920 return;
921 }
922 Blob keyBlob;
923 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100924 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
925 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700926 return;
927 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100928
929 auto key = blob2hidlVec(keyBlob);
930 auto& dev = mKeyStore->getDevice(keyBlob);
931 AuthorizationSet opParams = params;
932 KeyCharacteristics characteristics;
933 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
934
935 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
936 result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
937 if (!result->resultCode.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -0600938 return;
939 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100940 key = blob2hidlVec(keyBlob);
941 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
Shawn Willden98c59162016-03-20 09:10:18 -0600942 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100943 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700944 return;
945 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100946
947 const HardwareAuthToken* authToken = NULL;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400948
949 // Merge these characteristics with the ones cached when the key was generated or imported
950 Blob charBlob;
951 AuthorizationSet persistedCharacteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100952 result->resultCode =
953 mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
954 if (result->resultCode.isOk()) {
955 // TODO write one shot stream buffer to avoid copying (twice here)
956 std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
957 charBlob.getLength());
958 std::stringstream charStream(charBuffer);
959 persistedCharacteristics.Deserialize(&charStream);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400960 } else {
961 ALOGD("Unable to read cached characteristics for key");
962 }
963
964 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100965 AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
966 AuthorizationSet teeEnforced = characteristics.teeEnforced;
967 persistedCharacteristics.Union(softwareEnforced);
968 persistedCharacteristics.Subtract(teeEnforced);
969 characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400970
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100971 result->resultCode = getAuthToken(characteristics, 0, purpose, &authToken,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700972 /*failOnTokenMissing*/ false);
973 // If per-operation auth is needed we need to begin the operation and
974 // the client will need to authorize that operation before calling
975 // update. Any other auth issues stop here.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100976 if (!result->resultCode.isOk() && result->resultCode != ResponseCode::OP_AUTH_NEEDED) return;
977
978 addAuthTokenToParams(&opParams, authToken);
979
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700980 // Add entropy to the device first.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100981 if (entropy.size()) {
982 result->resultCode = addRngEntropy(entropy);
983 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700984 return;
985 }
986 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700987
988 // Create a keyid for this key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100989 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700990 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
991 ALOGE("Failed to create a key ID for authorization checking.");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100992 result->resultCode = ErrorCode::UNKNOWN_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700993 return;
994 }
995
996 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100997 AuthorizationSet key_auths = characteristics.teeEnforced;
998 key_auths.append(&characteristics.softwareEnforced[0],
999 &characteristics.softwareEnforced[characteristics.softwareEnforced.size()]);
1000
1001 result->resultCode = enforcement_policy.AuthorizeOperation(
1002 purpose, keyid, key_auths, opParams, 0 /* op_handle */, true /* is_begin_operation */);
1003 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001004 return;
1005 }
1006
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001007 // If there are more than MAX_OPERATIONS, abort the oldest operation that was started as
1008 // pruneable.
1009 while (mOperationMap.getOperationCount() >= MAX_OPERATIONS) {
1010 ALOGD("Reached or exceeded concurrent operations limit");
1011 if (!pruneOperation()) {
1012 break;
1013 }
1014 }
1015
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001016 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1017 uint64_t operationHandle) {
1018 result->resultCode = ret;
1019 if (!result->resultCode.isOk()) {
1020 return;
1021 }
1022 result->handle = operationHandle;
1023 result->outParams = outParams;
1024 };
1025
1026 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
1027 if (rc != ErrorCode::OK) {
1028 ALOGW("Got error %d from begin()", rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001029 }
1030
1031 // If there are too many operations abort the oldest operation that was
1032 // started as pruneable and try again.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001033 while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1034 ALOGW("Ran out of operation handles");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001035 if (!pruneOperation()) {
1036 break;
1037 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001038 rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001039 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001040 if (rc != ErrorCode::OK) {
1041 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001042 return;
1043 }
1044
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001045 // Note: The operation map takes possession of the contents of "characteristics".
1046 // It is safe to use characteristics after the following line but it will be empty.
1047 sp<IBinder> operationToken = mOperationMap.addOperation(
1048 result->handle, keyid, purpose, dev, appToken, std::move(characteristics), pruneable);
1049 assert(characteristics.teeEnforced.size() == 0);
1050 assert(characteristics.softwareEnforced.size() == 0);
1051
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001052 if (authToken) {
1053 mOperationMap.setOperationAuthToken(operationToken, authToken);
1054 }
1055 // Return the authentication lookup result. If this is a per operation
1056 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1057 // application should get an auth token using the handle before the
1058 // first call to update, which will fail if keystore hasn't received the
1059 // auth token.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001060 // All fields but "token" were set in the begin operation's callback.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001061 result->token = operationToken;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001062}
1063
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001064void KeyStoreService::update(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1065 const hidl_vec<uint8_t>& data, OperationResult* result) {
1066 if (!checkAllowedOperationParams(params)) {
1067 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001068 return;
1069 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001070 km_device_t dev;
1071 uint64_t handle;
1072 KeyPurpose purpose;
1073 km_id_t keyid;
1074 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001075 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001076 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001077 return;
1078 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001079 AuthorizationSet opParams = params;
1080 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1081 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001082 return;
1083 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001084
1085 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001086 AuthorizationSet key_auths(characteristics->teeEnforced);
1087 key_auths.append(&characteristics->softwareEnforced[0],
1088 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001089 result->resultCode = enforcement_policy.AuthorizeOperation(
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001090 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1091 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001092 return;
1093 }
1094
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001095 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
1096 const hidl_vec<KeyParameter>& outParams, const hidl_vec<uint8_t>& output) {
1097 result->resultCode = ret;
1098 if (!result->resultCode.isOk()) {
1099 return;
1100 }
1101 result->inputConsumed = inputConsumed;
1102 result->outParams = outParams;
1103 result->data = output;
1104 };
1105
Janis Danisevskisb0245ee2017-01-25 15:43:01 +00001106 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->update(handle, opParams.hidl_data(),
1107 data, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001108 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1109 // it if there was a communication error indicated by the ErrorCode.
1110 if (!rc.isOk()) {
1111 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001112 }
1113}
1114
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001115void KeyStoreService::finish(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1116 const hidl_vec<uint8_t>& signature, const hidl_vec<uint8_t>& entropy,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001117 OperationResult* result) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001118 if (!checkAllowedOperationParams(params)) {
1119 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001120 return;
1121 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001122 km_device_t dev;
1123 uint64_t handle;
1124 KeyPurpose purpose;
1125 km_id_t keyid;
1126 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001127 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001128 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001129 return;
1130 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001131 AuthorizationSet opParams = params;
1132 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1133 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001134 return;
1135 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001136
1137 if (entropy.size()) {
1138 result->resultCode = addRngEntropy(entropy);
1139 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001140 return;
1141 }
1142 }
1143
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001144 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001145 AuthorizationSet key_auths(characteristics->teeEnforced);
1146 key_auths.append(&characteristics->softwareEnforced[0],
1147 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
1148 result->resultCode = enforcement_policy.AuthorizeOperation(
1149 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1150 if (!result->resultCode.isOk()) return;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001151
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001152 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1153 const hidl_vec<uint8_t>& output) {
1154 result->resultCode = ret;
1155 if (!result->resultCode.isOk()) {
1156 return;
1157 }
1158 result->outParams = outParams;
1159 result->data = output;
1160 };
1161
1162 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->finish(
1163 handle, opParams.hidl_data(),
1164 hidl_vec<uint8_t>() /* TODO(swillden): wire up input to finish() */, signature, hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001165 // Remove the operation regardless of the result
1166 mOperationMap.removeOperation(token);
1167 mAuthTokenTable.MarkCompleted(handle);
1168
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001169 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1170 // it if there was a communication error indicated by the ErrorCode.
1171 if (!rc.isOk()) {
1172 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001173 }
1174}
1175
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001176KeyStoreServiceReturnCode KeyStoreService::abort(const sp<IBinder>& token) {
1177 km_device_t dev;
1178 uint64_t handle;
1179 KeyPurpose purpose;
1180 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001181 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001182 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001183 }
1184 mOperationMap.removeOperation(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001185
1186 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->abort(handle));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001187 mAuthTokenTable.MarkCompleted(handle);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001188 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001189}
1190
1191bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001192 km_device_t dev;
1193 uint64_t handle;
1194 const KeyCharacteristics* characteristics;
1195 KeyPurpose purpose;
1196 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001197 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1198 return false;
1199 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001200 const HardwareAuthToken* authToken = NULL;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001201 mOperationMap.getOperationAuthToken(token, &authToken);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001202 AuthorizationSet ignored;
1203 auto authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1204 return authResult.isOk();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001205}
1206
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001207KeyStoreServiceReturnCode KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
1208 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1209 // receive a HardwareAuthToken, rather than an opaque byte array.
1210
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001211 if (!checkBinderPermission(P_ADD_AUTH)) {
1212 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001213 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001214 }
1215 if (length != sizeof(hw_auth_token_t)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001216 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001217 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001218
1219 hw_auth_token_t authToken;
1220 memcpy(reinterpret_cast<void*>(&authToken), token, sizeof(hw_auth_token_t));
1221 if (authToken.version != 0) {
1222 return ErrorCode::INVALID_ARGUMENT;
1223 }
1224
1225 std::unique_ptr<HardwareAuthToken> hidlAuthToken(new HardwareAuthToken);
1226 hidlAuthToken->challenge = authToken.challenge;
1227 hidlAuthToken->userId = authToken.user_id;
1228 hidlAuthToken->authenticatorId = authToken.authenticator_id;
1229 hidlAuthToken->authenticatorType = authToken.authenticator_type;
1230 hidlAuthToken->timestamp = authToken.timestamp;
1231 static_assert(
1232 std::is_same<decltype(hidlAuthToken->hmac),
1233 ::android::hardware::hidl_array<uint8_t, sizeof(authToken.hmac)>>::value,
1234 "This function assumes token HMAC is 32 bytes, but it might not be.");
1235 std::copy(authToken.hmac, authToken.hmac + sizeof(authToken.hmac), hidlAuthToken->hmac.data());
1236
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001237 // The table takes ownership of authToken.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001238 mAuthTokenTable.AddAuthenticationToken(hidlAuthToken.release());
1239 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001240}
1241
Janis Danisevskis7612fd42016-09-01 11:50:02 +01001242constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
1243
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001244bool isDeviceIdAttestationRequested(const hidl_vec<KeyParameter>& params) {
1245 for (size_t i = 0; i < params.size(); ++i) {
1246 switch (params[i].tag) {
1247 case Tag::ATTESTATION_ID_BRAND:
1248 case Tag::ATTESTATION_ID_DEVICE:
1249 case Tag::ATTESTATION_ID_PRODUCT:
1250 case Tag::ATTESTATION_ID_SERIAL:
1251 case Tag::ATTESTATION_ID_IMEI:
1252 case Tag::ATTESTATION_ID_MEID:
Bartosz Fabianowski634a1aa2017-03-20 14:02:32 +01001253 case Tag::ATTESTATION_ID_MANUFACTURER:
1254 case Tag::ATTESTATION_ID_MODEL:
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001255 return true;
1256 default:
1257 break;
1258 }
1259 }
1260 return false;
1261}
1262
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001263KeyStoreServiceReturnCode KeyStoreService::attestKey(const String16& name,
1264 const hidl_vec<KeyParameter>& params,
1265 hidl_vec<hidl_vec<uint8_t>>* outChain) {
1266 if (!outChain) {
1267 return ErrorCode::OUTPUT_PARAMETER_NULL;
1268 }
Shawn Willden50eb1b22016-01-21 12:41:23 -07001269
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001270 if (!checkAllowedOperationParams(params)) {
1271 return ErrorCode::INVALID_ARGUMENT;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001272 }
1273
1274 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1275
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001276 bool attestingDeviceIds = isDeviceIdAttestationRequested(params);
1277 if (attestingDeviceIds) {
1278 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1279 if (binder == 0) {
1280 return ErrorCode::CANNOT_ATTEST_IDS;
1281 }
1282 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1283 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1284 IPCThreadState::self()->getCallingPid(), callingUid)) {
1285 return ErrorCode::CANNOT_ATTEST_IDS;
1286 }
1287 }
1288
Shawn Willden50eb1b22016-01-21 12:41:23 -07001289 Blob keyBlob;
1290 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001291 KeyStoreServiceReturnCode responseCode =
Shawn Willden50eb1b22016-01-21 12:41:23 -07001292 mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001293 if (!responseCode.isOk()) {
Shawn Willden50eb1b22016-01-21 12:41:23 -07001294 return responseCode;
1295 }
1296
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001297 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
Janis Danisevskis011675d2016-09-01 11:41:29 +01001298 if (!asn1_attestation_id_result.isOk()) {
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001299 ALOGE("failed to gather attestation_id");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001300 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001301 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001302 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001303
1304 /*
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001305 * The attestation application ID cannot be longer than
1306 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, so we truncate if too long.
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001307 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001308 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE)
1309 asn1_attestation_id.resize(KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE);
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001310
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001311 AuthorizationSet mutableParams = params;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001312
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001313 mutableParams.push_back(TAG_ATTESTATION_APPLICATION_ID, blob2hidlVec(asn1_attestation_id));
1314
1315 KeyStoreServiceReturnCode error;
1316 auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1317 error = ret;
1318 if (!error.isOk()) {
1319 return;
1320 }
1321 if (outChain) *outChain = certChain;
1322 };
1323
1324 auto hidlKey = blob2hidlVec(keyBlob);
1325 auto& dev = mKeyStore->getDevice(keyBlob);
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001326 KeyStoreServiceReturnCode attestationRc =
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001327 KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001328
1329 KeyStoreServiceReturnCode deletionRc;
1330 if (attestingDeviceIds) {
1331 // When performing device id attestation, treat the key as ephemeral and delete it straight
1332 // away.
1333 deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001334 }
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001335
1336 if (!attestationRc.isOk()) {
1337 return attestationRc;
1338 }
1339 if (!error.isOk()) {
1340 return error;
1341 }
1342 return deletionRc;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001343}
1344
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001345KeyStoreServiceReturnCode KeyStoreService::onDeviceOffBody() {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001346 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1347 mAuthTokenTable.onDeviceOffBody();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001348 return ResponseCode::NO_ERROR;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001349}
1350
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001351/**
1352 * Prune the oldest pruneable operation.
1353 */
1354bool KeyStoreService::pruneOperation() {
1355 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1356 ALOGD("Trying to prune operation %p", oldest.get());
1357 size_t op_count_before_abort = mOperationMap.getOperationCount();
1358 // We mostly ignore errors from abort() because all we care about is whether at least
1359 // one operation has been removed.
1360 int abort_error = abort(oldest);
1361 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1362 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1363 return false;
1364 }
1365 return true;
1366}
1367
1368/**
1369 * Get the effective target uid for a binder operation that takes an
1370 * optional uid as the target.
1371 */
1372uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1373 if (targetUid == UID_SELF) {
1374 return IPCThreadState::self()->getCallingUid();
1375 }
1376 return static_cast<uid_t>(targetUid);
1377}
1378
1379/**
1380 * Check if the caller of the current binder method has the required
1381 * permission and if acting on other uids the grants to do so.
1382 */
1383bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1384 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1385 pid_t spid = IPCThreadState::self()->getCallingPid();
1386 if (!has_permission(callingUid, permission, spid)) {
1387 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1388 return false;
1389 }
1390 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1391 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1392 return false;
1393 }
1394 return true;
1395}
1396
1397/**
1398 * Check if the caller of the current binder method has the required
1399 * permission and the target uid is the caller or the caller is system.
1400 */
1401bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1402 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1403 pid_t spid = IPCThreadState::self()->getCallingPid();
1404 if (!has_permission(callingUid, permission, spid)) {
1405 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1406 return false;
1407 }
1408 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1409}
1410
1411/**
1412 * Check if the caller of the current binder method has the required
1413 * permission or the target of the operation is the caller's uid. This is
1414 * for operation where the permission is only for cross-uid activity and all
1415 * uids are allowed to act on their own (ie: clearing all entries for a
1416 * given uid).
1417 */
1418bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1419 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1420 if (getEffectiveUid(targetUid) == callingUid) {
1421 return true;
1422 } else {
1423 return checkBinderPermission(permission, targetUid);
1424 }
1425}
1426
1427/**
1428 * Helper method to check that the caller has the required permission as
1429 * well as the keystore is in the unlocked state if checkUnlocked is true.
1430 *
1431 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1432 * otherwise the state of keystore when not unlocked and checkUnlocked is
1433 * true.
1434 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001435KeyStoreServiceReturnCode
1436KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1437 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001438 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001439 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001440 }
1441 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1442 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001443 // All State values coincide with ResponseCodes
1444 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001445 }
1446
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001447 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001448}
1449
1450bool KeyStoreService::isKeystoreUnlocked(State state) {
1451 switch (state) {
1452 case ::STATE_NO_ERROR:
1453 return true;
1454 case ::STATE_UNINITIALIZED:
1455 case ::STATE_LOCKED:
1456 return false;
1457 }
1458 return false;
1459}
1460
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001461/**
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001462 * Check that all KeyParameter's provided by the application are
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001463 * allowed. Any parameter that keystore adds itself should be disallowed here.
1464 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001465bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1466 for (size_t i = 0; i < params.size(); ++i) {
1467 switch (params[i].tag) {
1468 case Tag::AUTH_TOKEN:
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001469 // fall through intended
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001470 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001471 return false;
1472 default:
1473 break;
1474 }
1475 }
1476 return true;
1477}
1478
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001479ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
1480 km_device_t* dev,
1481 const AuthorizationSet& params,
1482 KeyCharacteristics* out) {
1483 hidl_vec<uint8_t> appId;
1484 hidl_vec<uint8_t> appData;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001485 for (auto param : params) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001486 if (param.tag == Tag::APPLICATION_ID) {
1487 appId = authorizationValue(TAG_APPLICATION_ID, param).value();
1488 } else if (param.tag == Tag::APPLICATION_DATA) {
1489 appData = authorizationValue(TAG_APPLICATION_DATA, param).value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001490 }
1491 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001492 ErrorCode error = ErrorCode::OK;
1493
1494 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
1495 error = ret;
1496 if (error != ErrorCode::OK) {
1497 return;
1498 }
1499 if (out) *out = keyCharacteristics;
1500 };
1501
1502 ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appData, hidlCb));
1503 if (rc != ErrorCode::OK) {
1504 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001505 }
1506 return error;
1507}
1508
1509/**
1510 * Get the auth token for this operation from the auth token table.
1511 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001512 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001513 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1514 * authorization token exists for that operation and
1515 * failOnTokenMissing is false.
1516 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1517 * token for the operation
1518 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001519KeyStoreServiceReturnCode KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics,
1520 uint64_t handle, KeyPurpose purpose,
1521 const HardwareAuthToken** authToken,
1522 bool failOnTokenMissing) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001523
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001524 AuthorizationSet allCharacteristics;
1525 for (size_t i = 0; i < characteristics.softwareEnforced.size(); i++) {
1526 allCharacteristics.push_back(characteristics.softwareEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001527 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001528 for (size_t i = 0; i < characteristics.teeEnforced.size(); i++) {
1529 allCharacteristics.push_back(characteristics.teeEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001530 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001531 AuthTokenTable::Error err =
1532 mAuthTokenTable.FindAuthorization(allCharacteristics, purpose, handle, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001533 switch (err) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001534 case AuthTokenTable::OK:
1535 case AuthTokenTable::AUTH_NOT_REQUIRED:
1536 return ResponseCode::NO_ERROR;
1537 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1538 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
1539 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
1540 return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1541 case AuthTokenTable::OP_HANDLE_REQUIRED:
1542 return failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
1543 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001544 default:
1545 ALOGE("Unexpected FindAuthorization return value %d", err);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001546 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001547 }
1548}
1549
1550/**
1551 * Add the auth token for the operation to the param list if the operation
1552 * requires authorization. Uses the cached result in the OperationMap if available
1553 * otherwise gets the token from the AuthTokenTable and caches the result.
1554 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001555 * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001556 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1557 * authenticated.
1558 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1559 * operation token.
1560 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001561KeyStoreServiceReturnCode KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
1562 AuthorizationSet* params) {
1563 const HardwareAuthToken* authToken = nullptr;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001564 mOperationMap.getOperationAuthToken(token, &authToken);
1565 if (!authToken) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001566 km_device_t dev;
1567 uint64_t handle;
1568 const KeyCharacteristics* characteristics = nullptr;
1569 KeyPurpose purpose;
1570 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001571 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001572 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001573 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001574 auto result = getAuthToken(*characteristics, handle, purpose, &authToken);
1575 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001576 return result;
1577 }
1578 if (authToken) {
1579 mOperationMap.setOperationAuthToken(token, authToken);
1580 }
1581 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001582 addAuthTokenToParams(params, authToken);
1583 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001584}
1585
1586/**
1587 * Translate a result value to a legacy return value. All keystore errors are
1588 * preserved and keymaster errors become SYSTEM_ERRORs
1589 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001590KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001591 if (result > 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001592 return static_cast<ResponseCode>(result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001593 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001594 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001595}
1596
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001597static NullOr<const Algorithm&>
1598getKeyAlgoritmFromKeyCharacteristics(const KeyCharacteristics& characteristics) {
1599 for (size_t i = 0; i < characteristics.teeEnforced.size(); ++i) {
1600 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.teeEnforced[i]);
1601 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001602 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001603 for (size_t i = 0; i < characteristics.softwareEnforced.size(); ++i) {
1604 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.softwareEnforced[i]);
1605 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001606 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001607 return {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001608}
1609
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001610void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001611 // All legacy keys are DIGEST_NONE/PAD_NONE.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001612 params->push_back(TAG_DIGEST, Digest::NONE);
1613 params->push_back(TAG_PADDING, PaddingMode::NONE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001614
1615 // Look up the algorithm of the key.
1616 KeyCharacteristics characteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001617 auto rc = getKeyCharacteristics(name, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF,
1618 &characteristics);
1619 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001620 ALOGE("Failed to get key characteristics");
1621 return;
1622 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001623 auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
1624 if (!algorithm.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001625 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1626 return;
1627 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001628 params->push_back(TAG_ALGORITHM, algorithm.value());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001629}
1630
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001631KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
1632 const hidl_vec<uint8_t>& data,
1633 hidl_vec<uint8_t>* out,
1634 const hidl_vec<uint8_t>& signature,
1635 KeyPurpose purpose) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001636
1637 std::basic_stringstream<uint8_t> outBuffer;
1638 OperationResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001639 AuthorizationSet inArgs;
1640 addLegacyBeginParams(name, &inArgs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001641 sp<IBinder> appToken(new BBinder);
1642 sp<IBinder> token;
1643
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001644 begin(appToken, name, purpose, true, inArgs.hidl_data(), hidl_vec<uint8_t>(), UID_SELF,
1645 &result);
1646 if (!result.resultCode.isOk()) {
1647 if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001648 ALOGW("Key not found");
1649 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001650 ALOGW("Error in begin: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001651 }
1652 return translateResultToLegacyResult(result.resultCode);
1653 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001654 inArgs.Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001655 token = result.token;
1656 size_t consumed = 0;
1657 size_t lastConsumed = 0;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001658 hidl_vec<uint8_t> data_view;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001659 do {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001660 data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
1661 update(token, inArgs.hidl_data(), data_view, &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001662 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001663 ALOGW("Error in update: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001664 return translateResultToLegacyResult(result.resultCode);
1665 }
1666 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001667 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001668 }
1669 lastConsumed = result.inputConsumed;
1670 consumed += lastConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001671 } while (consumed < data.size() && lastConsumed > 0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001672
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001673 if (consumed != data.size()) {
1674 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
1675 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001676 }
1677
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001678 finish(token, inArgs.hidl_data(), signature, hidl_vec<uint8_t>(), &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001679 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001680 ALOGW("Error in finish: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001681 return translateResultToLegacyResult(result.resultCode);
1682 }
1683 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001684 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001685 }
1686
1687 if (out) {
1688 auto buf = outBuffer.str();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001689 out->resize(buf.size());
1690 memcpy(&(*out)[0], buf.data(), out->size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001691 }
1692
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001693 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001694}
1695
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001696KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
1697 const AuthorizationSet& params,
1698 Blob* blob) {
Shawn Willden98c59162016-03-20 09:10:18 -06001699 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
1700 String8 name8(name);
1701 ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001702 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willden98c59162016-03-20 09:10:18 -06001703 return responseCode;
1704 }
Rubin Xu7675c9f2017-03-15 19:26:52 +00001705 ALOGI("upgradeKeyBlob %s %d", name8.string(), uid);
Shawn Willden98c59162016-03-20 09:10:18 -06001706
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001707 auto hidlKey = blob2hidlVec(*blob);
1708 auto& dev = mKeyStore->getDevice(*blob);
Shawn Willden98c59162016-03-20 09:10:18 -06001709
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001710 KeyStoreServiceReturnCode error;
1711 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
1712 error = ret;
1713 if (!error.isOk()) {
1714 return;
1715 }
1716
1717 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1718 error = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(uid));
1719 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001720 ALOGI("upgradeKeyBlob keystore->del failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001721 return;
1722 }
1723
1724 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
1725 0 /* infoLength */, ::TYPE_KEYMASTER_10);
1726 newBlob.setFallback(blob->isFallback());
1727 newBlob.setEncrypted(blob->isEncrypted());
1728
1729 error = mKeyStore->put(filename.string(), &newBlob, get_user_id(uid));
1730 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001731 ALOGI("upgradeKeyBlob keystore->put failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001732 return;
1733 }
1734
1735 // Re-read blob for caller. We can't use newBlob because writing it modified it.
1736 error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1737 };
1738
1739 KeyStoreServiceReturnCode rc =
1740 KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
1741 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001742 return rc;
1743 }
1744
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001745 return error;
Shawn Willden98c59162016-03-20 09:10:18 -06001746}
1747
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001748} // namespace android