blob: 434ddddfd4deb790fdbf6578bbfbb35c6cb700a6 [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
Shawn Willdene2a7b522017-04-11 09:27:40 -060045namespace {
46
47constexpr size_t kMaxOperations = 15;
48constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
49const char* kTimestampFilePath = "timestamp";
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070050
51struct BIGNUM_Delete {
52 void operator()(BIGNUM* p) const { BN_free(p); }
53};
54typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
55
Shawn Willdene2a7b522017-04-11 09:27:40 -060056bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
57 return params.end() != std::find_if(params.begin(), params.end(),
58 [&](auto& param) { return param.tag == tag; });
59}
60
61std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
62 struct stat sbuf;
63 if (stat(kTimestampFilePath, &sbuf) == 0) {
64 double diff_secs = difftime(time(NULL), sbuf.st_ctime);
65 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
66 }
67
68 if (errno != ENOENT) {
69 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
70 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
71 }
72
73 int fd = creat(kTimestampFilePath, 0600);
74 if (fd < 0) {
75 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
76 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
77 }
78
79 if (close(fd)) {
80 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
81 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
82 }
83
84 return {ResponseCode::NO_ERROR, true};
85}
86
87} // anonymous namespace
88
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070089void KeyStoreService::binderDied(const wp<IBinder>& who) {
90 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -070091 for (const auto& token : operations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070092 abort(token);
93 }
94}
95
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010096KeyStoreServiceReturnCode KeyStoreService::getState(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070097 if (!checkBinderPermission(P_GET_STATE)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010098 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070099 }
100
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100101 return ResponseCode(mKeyStore->getState(userId));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700102}
103
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100104KeyStoreServiceReturnCode KeyStoreService::get(const String16& name, int32_t uid,
105 hidl_vec<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700106 uid_t targetUid = getEffectiveUid(uid);
107 if (!checkBinderPermission(P_GET, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100108 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700109 }
110
111 String8 name8(name);
112 Blob keyBlob;
113
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100114 KeyStoreServiceReturnCode rc =
115 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
116 if (!rc.isOk()) {
117 if (item) *item = hidl_vec<uint8_t>();
118 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700119 }
120
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100121 // Do not replace this with "if (item) *item = blob2hidlVec(keyBlob)"!
122 // blob2hidlVec creates a hidl_vec<uint8_t> that references, but not owns, the data in keyBlob
123 // the subsequent assignment (*item = resultBlob) makes a deep copy, so that *item will own the
124 // corresponding resources.
125 auto resultBlob = blob2hidlVec(keyBlob);
126 if (item) {
127 *item = resultBlob;
128 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700129
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100130 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700131}
132
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100133KeyStoreServiceReturnCode KeyStoreService::insert(const String16& name,
134 const hidl_vec<uint8_t>& item, int targetUid,
135 int32_t flags) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700136 targetUid = getEffectiveUid(targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100137 auto result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700138 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100139 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700140 return result;
141 }
142
143 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400144 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_GENERIC));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700145
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100146 Blob keyBlob(&item[0], item.size(), NULL, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700147 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
148
149 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
150}
151
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100152KeyStoreServiceReturnCode KeyStoreService::del(const String16& name, int targetUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700153 targetUid = getEffectiveUid(targetUid);
154 if (!checkBinderPermission(P_DELETE, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100155 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700156 }
157 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000158 ALOGI("del %s %d", name8.string(), targetUid);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400159 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100160 ResponseCode result = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
161 if (result != ResponseCode::NO_ERROR) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400162 return result;
163 }
164
165 // Also delete any characteristics files
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100166 String8 chrFilename(
167 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400168 return mKeyStore->del(chrFilename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700169}
170
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100171KeyStoreServiceReturnCode KeyStoreService::exist(const String16& name, int targetUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700172 targetUid = getEffectiveUid(targetUid);
173 if (!checkBinderPermission(P_EXIST, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100174 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700175 }
176
177 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400178 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700179
180 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100181 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700182 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100183 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700184}
185
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100186KeyStoreServiceReturnCode KeyStoreService::list(const String16& prefix, int targetUid,
187 Vector<String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700188 targetUid = getEffectiveUid(targetUid);
189 if (!checkBinderPermission(P_LIST, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100190 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700191 }
192 const String8 prefix8(prefix);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400193 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid, TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700194
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100195 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
196 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700197 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100198 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700199}
200
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100201KeyStoreServiceReturnCode KeyStoreService::reset() {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700202 if (!checkBinderPermission(P_RESET)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100203 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700204 }
205
206 uid_t callingUid = IPCThreadState::self()->getCallingUid();
207 mKeyStore->resetUser(get_user_id(callingUid), false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100208 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700209}
210
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100211KeyStoreServiceReturnCode KeyStoreService::onUserPasswordChanged(int32_t userId,
212 const String16& password) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700213 if (!checkBinderPermission(P_PASSWORD)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100214 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700215 }
216
217 const String8 password8(password);
218 // Flush the auth token table to prevent stale tokens from sticking
219 // around.
220 mAuthTokenTable.Clear();
221
222 if (password.size() == 0) {
223 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
224 mKeyStore->resetUser(userId, true);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100225 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700226 } else {
227 switch (mKeyStore->getState(userId)) {
228 case ::STATE_UNINITIALIZED: {
229 // generate master key, encrypt with password, write to file,
230 // initialize mMasterKey*.
231 return mKeyStore->initializeUser(password8, userId);
232 }
233 case ::STATE_NO_ERROR: {
234 // rewrite master key with new password.
235 return mKeyStore->writeMasterKey(password8, userId);
236 }
237 case ::STATE_LOCKED: {
238 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
239 mKeyStore->resetUser(userId, true);
240 return mKeyStore->initializeUser(password8, userId);
241 }
242 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100243 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700244 }
245}
246
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100247KeyStoreServiceReturnCode KeyStoreService::onUserAdded(int32_t userId, int32_t parentId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700248 if (!checkBinderPermission(P_USER_CHANGED)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100249 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700250 }
251
252 // Sanity check that the new user has an empty keystore.
253 if (!mKeyStore->isEmpty(userId)) {
254 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
255 }
256 // Unconditionally clear the keystore, just to be safe.
257 mKeyStore->resetUser(userId, false);
258 if (parentId != -1) {
259 // This profile must share the same master key password as the parent profile. Because the
260 // password of the parent profile is not known here, the best we can do is copy the parent's
261 // master key and master key file. This makes this profile use the same master key as the
262 // parent profile, forever.
263 return mKeyStore->copyMasterKey(parentId, userId);
264 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100265 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700266 }
267}
268
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100269KeyStoreServiceReturnCode KeyStoreService::onUserRemoved(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700270 if (!checkBinderPermission(P_USER_CHANGED)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100271 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700272 }
273
274 mKeyStore->resetUser(userId, false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100275 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700276}
277
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100278KeyStoreServiceReturnCode KeyStoreService::lock(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700279 if (!checkBinderPermission(P_LOCK)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100280 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700281 }
282
283 State state = mKeyStore->getState(userId);
284 if (state != ::STATE_NO_ERROR) {
285 ALOGD("calling lock in state: %d", state);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100286 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700287 }
288
289 mKeyStore->lock(userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100290 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700291}
292
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100293KeyStoreServiceReturnCode KeyStoreService::unlock(int32_t userId, const String16& pw) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700294 if (!checkBinderPermission(P_UNLOCK)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100295 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700296 }
297
298 State state = mKeyStore->getState(userId);
299 if (state != ::STATE_LOCKED) {
300 switch (state) {
301 case ::STATE_NO_ERROR:
302 ALOGI("calling unlock when already unlocked, ignoring.");
303 break;
304 case ::STATE_UNINITIALIZED:
305 ALOGE("unlock called on uninitialized keystore.");
306 break;
307 default:
308 ALOGE("unlock called on keystore in unknown state: %d", state);
309 break;
310 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100311 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700312 }
313
314 const String8 password8(pw);
315 // read master key, decrypt with password, initialize mMasterKey*.
316 return mKeyStore->readMasterKey(password8, userId);
317}
318
319bool KeyStoreService::isEmpty(int32_t userId) {
320 if (!checkBinderPermission(P_IS_EMPTY)) {
321 return false;
322 }
323
324 return mKeyStore->isEmpty(userId);
325}
326
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100327KeyStoreServiceReturnCode KeyStoreService::generate(const String16& name, int32_t targetUid,
328 int32_t keyType, int32_t keySize, int32_t flags,
329 Vector<sp<KeystoreArg>>* args) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700330 targetUid = getEffectiveUid(targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100331 auto result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700332 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100333 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700334 return result;
335 }
336
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100337 keystore::AuthorizationSet params;
338 add_legacy_key_authorizations(keyType, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700339
340 switch (keyType) {
341 case EVP_PKEY_EC: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100342 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700343 if (keySize == -1) {
344 keySize = EC_DEFAULT_KEY_SIZE;
345 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
346 ALOGI("invalid key size %d", keySize);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100347 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700348 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100349 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700350 break;
351 }
352 case EVP_PKEY_RSA: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100353 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700354 if (keySize == -1) {
355 keySize = RSA_DEFAULT_KEY_SIZE;
356 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
357 ALOGI("invalid key size %d", keySize);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100358 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700359 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100360 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700361 unsigned long exponent = RSA_DEFAULT_EXPONENT;
362 if (args->size() > 1) {
363 ALOGI("invalid number of arguments: %zu", args->size());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100364 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700365 } else if (args->size() == 1) {
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700366 const sp<KeystoreArg>& expArg = args->itemAt(0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700367 if (expArg != NULL) {
368 Unique_BIGNUM pubExpBn(BN_bin2bn(
369 reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
370 if (pubExpBn.get() == NULL) {
371 ALOGI("Could not convert public exponent to BN");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100372 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700373 }
374 exponent = BN_get_word(pubExpBn.get());
375 if (exponent == 0xFFFFFFFFL) {
376 ALOGW("cannot represent public exponent as a long value");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100377 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700378 }
379 } else {
380 ALOGW("public exponent not read");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100381 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700382 }
383 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100384 params.push_back(TAG_RSA_PUBLIC_EXPONENT, exponent);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700385 break;
386 }
387 default: {
388 ALOGW("Unsupported key type %d", keyType);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100389 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700390 }
391 }
392
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100393 auto rc = generateKey(name, params.hidl_data(), hidl_vec<uint8_t>(), targetUid, flags,
394 /*outCharacteristics*/ NULL);
395 if (!rc.isOk()) {
396 ALOGW("generate failed: %d", int32_t(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700397 }
398 return translateResultToLegacyResult(rc);
399}
400
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100401KeyStoreServiceReturnCode KeyStoreService::import(const String16& name,
402 const hidl_vec<uint8_t>& data, int targetUid,
403 int32_t flags) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700404
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100405 const uint8_t* ptr = &data[0];
406
407 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, data.size()));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700408 if (!pkcs8.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100409 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700410 }
411 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
412 if (!pkey.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100413 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700414 }
415 int type = EVP_PKEY_type(pkey->type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100416 AuthorizationSet params;
417 add_legacy_key_authorizations(type, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700418 switch (type) {
419 case EVP_PKEY_RSA:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100420 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700421 break;
422 case EVP_PKEY_EC:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100423 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700424 break;
425 default:
426 ALOGW("Unsupported key type %d", type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100427 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700428 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100429
430 auto rc = importKey(name, params.hidl_data(), KeyFormat::PKCS8, data, targetUid, flags,
431 /*outCharacteristics*/ NULL);
432
433 if (!rc.isOk()) {
434 ALOGW("importKey failed: %d", int32_t(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700435 }
436 return translateResultToLegacyResult(rc);
437}
438
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100439KeyStoreServiceReturnCode KeyStoreService::sign(const String16& name, const hidl_vec<uint8_t>& data,
440 hidl_vec<uint8_t>* out) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700441 if (!checkBinderPermission(P_SIGN)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100442 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700443 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100444 return doLegacySignVerify(name, data, out, hidl_vec<uint8_t>(), KeyPurpose::SIGN);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700445}
446
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100447KeyStoreServiceReturnCode KeyStoreService::verify(const String16& name,
448 const hidl_vec<uint8_t>& data,
449 const hidl_vec<uint8_t>& signature) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700450 if (!checkBinderPermission(P_VERIFY)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100451 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700452 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100453 return doLegacySignVerify(name, data, nullptr, signature, KeyPurpose::VERIFY);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700454}
455
456/*
457 * TODO: The abstraction between things stored in hardware and regular blobs
458 * of data stored on the filesystem should be moved down to keystore itself.
459 * Unfortunately the Java code that calls this has naming conventions that it
460 * knows about. Ideally keystore shouldn't be used to store random blobs of
461 * data.
462 *
463 * Until that happens, it's necessary to have a separate "get_pubkey" and
464 * "del_key" since the Java code doesn't really communicate what it's
465 * intentions are.
466 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100467KeyStoreServiceReturnCode KeyStoreService::get_pubkey(const String16& name,
468 hidl_vec<uint8_t>* pubKey) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700469 ExportResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100470 exportKey(name, KeyFormat::X509, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF, &result);
471 if (!result.resultCode.isOk()) {
472 ALOGW("export failed: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700473 return translateResultToLegacyResult(result.resultCode);
474 }
475
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100476 if (pubKey) *pubKey = std::move(result.exportData);
477 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700478}
479
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100480KeyStoreServiceReturnCode KeyStoreService::grant(const String16& name, int32_t granteeUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700481 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100482 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
483 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700484 return result;
485 }
486
487 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400488 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700489
490 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100491 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700492 }
493
494 mKeyStore->addGrant(filename.string(), granteeUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100495 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700496}
497
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100498KeyStoreServiceReturnCode KeyStoreService::ungrant(const String16& name, int32_t granteeUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700499 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100500 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
501 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700502 return result;
503 }
504
505 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400506 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700507
508 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100509 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700510 }
511
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100512 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ResponseCode::NO_ERROR
513 : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700514}
515
516int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
517 uid_t targetUid = getEffectiveUid(uid);
518 if (!checkBinderPermission(P_GET, targetUid)) {
519 ALOGW("permission denied for %d: getmtime", targetUid);
520 return -1L;
521 }
522
523 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400524 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700525
526 if (access(filename.string(), R_OK) == -1) {
527 ALOGW("could not access %s for getmtime", filename.string());
528 return -1L;
529 }
530
531 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
532 if (fd < 0) {
533 ALOGW("could not open %s for getmtime", filename.string());
534 return -1L;
535 }
536
537 struct stat s;
538 int ret = fstat(fd, &s);
539 close(fd);
540 if (ret == -1) {
541 ALOGW("could not stat %s for getmtime", filename.string());
542 return -1L;
543 }
544
545 return static_cast<int64_t>(s.st_mtime);
546}
547
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400548// TODO(tuckeris): This is dead code, remove it. Don't bother copying over key characteristics here
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100549KeyStoreServiceReturnCode KeyStoreService::duplicate(const String16& srcKey, int32_t srcUid,
550 const String16& destKey, int32_t destUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700551 uid_t callingUid = IPCThreadState::self()->getCallingUid();
552 pid_t spid = IPCThreadState::self()->getCallingPid();
553 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
554 ALOGW("permission denied for %d: duplicate", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100555 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700556 }
557
558 State state = mKeyStore->getState(get_user_id(callingUid));
559 if (!isKeystoreUnlocked(state)) {
560 ALOGD("calling duplicate in state: %d", state);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100561 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700562 }
563
564 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
565 srcUid = callingUid;
566 } else if (!is_granted_to(callingUid, srcUid)) {
567 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100568 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700569 }
570
571 if (destUid == -1) {
572 destUid = callingUid;
573 }
574
575 if (srcUid != destUid) {
576 if (static_cast<uid_t>(srcUid) != callingUid) {
577 ALOGD("can only duplicate from caller to other or to same uid: "
578 "calling=%d, srcUid=%d, destUid=%d",
579 callingUid, srcUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100580 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700581 }
582
583 if (!is_granted_to(callingUid, destUid)) {
584 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100585 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700586 }
587 }
588
589 String8 source8(srcKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400590 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700591
592 String8 target8(destKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400593 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700594
595 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
596 ALOGD("destination already exists: %s", targetFile.string());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100597 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700598 }
599
600 Blob keyBlob;
601 ResponseCode responseCode =
602 mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, get_user_id(srcUid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100603 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700604 return responseCode;
605 }
606
607 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
608}
609
610int32_t KeyStoreService::is_hardware_backed(const String16& keyType) {
611 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
612}
613
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100614KeyStoreServiceReturnCode KeyStoreService::clear_uid(int64_t targetUid64) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700615 uid_t targetUid = getEffectiveUid(targetUid64);
616 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100617 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700618 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000619 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700620
621 String8 prefix = String8::format("%u_", targetUid);
622 Vector<String16> aliases;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100623 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
624 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700625 }
626
627 for (uint32_t i = 0; i < aliases.size(); i++) {
628 String8 name8(aliases[i]);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400629 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700630 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400631
632 // del() will fail silently if no cached characteristics are present for this alias.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100633 String8 chr_filename(
634 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400635 mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700636 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100637 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700638}
639
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100640KeyStoreServiceReturnCode KeyStoreService::addRngEntropy(const hidl_vec<uint8_t>& entropy) {
641 const auto& device = mKeyStore->getDevice();
642 return KS_HANDLE_HIDL_ERROR(device->addRngEntropy(entropy));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700643}
644
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100645KeyStoreServiceReturnCode KeyStoreService::generateKey(const String16& name,
646 const hidl_vec<KeyParameter>& params,
647 const hidl_vec<uint8_t>& entropy, int uid,
648 int flags,
649 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700650 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100651 KeyStoreServiceReturnCode rc =
652 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
653 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700654 return rc;
655 }
656
Shawn Willdene2a7b522017-04-11 09:27:40 -0600657 if (containsTag(params, Tag::INCLUDE_UNIQUE_ID)) {
658 if (!checkBinderPermission(P_GEN_UNIQUE_ID)) return ResponseCode::PERMISSION_DENIED;
659 }
660
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100661 bool usingFallback = false;
662 auto& dev = mKeyStore->getDevice();
663 AuthorizationSet keyCharacteristics = params;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400664
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700665 // TODO: Seed from Linux RNG before this.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100666 rc = addRngEntropy(entropy);
667 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700668 return rc;
669 }
670
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100671 KeyStoreServiceReturnCode error;
672 auto hidl_cb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
673 const KeyCharacteristics& keyCharacteristics) {
674 error = ret;
675 if (!error.isOk()) {
676 return;
677 }
678 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700679
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100680 // Write the key
681 String8 name8(name);
682 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700683
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100684 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
685 keyBlob.setFallback(usingFallback);
686 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700687
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100688 error = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
689 };
690
691 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(params, hidl_cb));
692 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400693 return rc;
694 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100695 if (!error.isOk()) {
696 ALOGE("Failed to generate key -> falling back to software keymaster");
697 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000698 auto fallback = mKeyStore->getFallbackDevice();
699 if (!fallback.isOk()) {
700 return error;
701 }
702 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->generateKey(params, hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100703 if (!rc.isOk()) {
704 return rc;
705 }
706 if (!error.isOk()) {
707 return error;
708 }
709 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400710
711 // Write the characteristics:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100712 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400713 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
714
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100715 std::stringstream kc_stream;
716 keyCharacteristics.Serialize(&kc_stream);
717 if (kc_stream.bad()) {
718 return ResponseCode::SYSTEM_ERROR;
719 }
720 auto kc_buf = kc_stream.str();
721 Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
722 ::TYPE_KEY_CHARACTERISTICS);
723 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400724 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
725
726 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700727}
728
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100729KeyStoreServiceReturnCode
730KeyStoreService::getKeyCharacteristics(const String16& name, const hidl_vec<uint8_t>& clientId,
731 const hidl_vec<uint8_t>& appData, int32_t uid,
732 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700733 if (!outCharacteristics) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100734 return ErrorCode::UNEXPECTED_NULL_POINTER;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700735 }
736
737 uid_t targetUid = getEffectiveUid(uid);
738 uid_t callingUid = IPCThreadState::self()->getCallingUid();
739 if (!is_granted_to(callingUid, targetUid)) {
740 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
741 targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100742 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700743 }
744
745 Blob keyBlob;
746 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700747
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100748 KeyStoreServiceReturnCode rc =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700749 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100750 if (!rc.isOk()) {
751 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700752 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100753
754 auto hidlKeyBlob = blob2hidlVec(keyBlob);
755 auto& dev = mKeyStore->getDevice(keyBlob);
756
757 KeyStoreServiceReturnCode error;
758
759 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
760 error = ret;
761 if (!error.isOk()) {
762 return;
Shawn Willden98c59162016-03-20 09:10:18 -0600763 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100764 *outCharacteristics = keyCharacteristics;
765 };
766
767 rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(hidlKeyBlob, clientId, appData, hidlCb));
768 if (!rc.isOk()) {
769 return rc;
770 }
771
772 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
773 AuthorizationSet upgradeParams;
774 if (clientId.size()) {
775 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
776 }
777 if (appData.size()) {
778 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
Shawn Willden98c59162016-03-20 09:10:18 -0600779 }
780 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100781 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -0600782 return rc;
783 }
Shawn Willden715d0232016-01-21 00:45:13 -0700784
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100785 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
786
787 rc = KS_HANDLE_HIDL_ERROR(
788 dev->getKeyCharacteristics(upgradedHidlKeyBlob, clientId, appData, hidlCb));
789 if (!rc.isOk()) {
790 return rc;
791 }
792 // Note that, on success, "error" will have been updated by the hidlCB callback.
793 // So it is fine to return "error" below.
794 }
795 return error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700796}
797
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100798KeyStoreServiceReturnCode
799KeyStoreService::importKey(const String16& name, const hidl_vec<KeyParameter>& params,
800 KeyFormat format, const hidl_vec<uint8_t>& keyData, int uid, int flags,
801 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700802 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100803 KeyStoreServiceReturnCode rc =
804 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
805 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700806 return rc;
807 }
808
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100809 bool usingFallback = false;
810 auto& dev = mKeyStore->getDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700811
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700812 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700813
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100814 KeyStoreServiceReturnCode error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700815
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100816 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
817 const KeyCharacteristics& keyCharacteristics) {
818 error = ret;
819 if (!error.isOk()) {
820 return;
821 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700822
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100823 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
824
825 // Write the key:
826 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
827
828 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
829 ksBlob.setFallback(usingFallback);
830 ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
831
832 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
833 };
834
835 rc = KS_HANDLE_HIDL_ERROR(dev->importKey(params, format, keyData, hidlCb));
836 // possible hidl error
837 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400838 return rc;
839 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100840 // now check error from callback
841 if (!error.isOk()) {
842 ALOGE("Failed to import key -> falling back to software keymaster");
843 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000844 auto fallback = mKeyStore->getFallbackDevice();
845 if (!fallback.isOk()) {
846 return error;
847 }
848 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->importKey(params, format, keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100849 // possible hidl error
850 if (!rc.isOk()) {
851 return rc;
852 }
853 // now check error from callback
854 if (!error.isOk()) {
855 return error;
856 }
857 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400858
859 // Write the characteristics:
860 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
861
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100862 AuthorizationSet opParams = params;
863 std::stringstream kcStream;
864 opParams.Serialize(&kcStream);
865 if (kcStream.bad()) return ResponseCode::SYSTEM_ERROR;
866 auto kcBuf = kcStream.str();
867
868 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
869 ::TYPE_KEY_CHARACTERISTICS);
870 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400871 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
872
873 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700874}
875
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100876void KeyStoreService::exportKey(const String16& name, KeyFormat format,
877 const hidl_vec<uint8_t>& clientId, const hidl_vec<uint8_t>& appData,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700878 int32_t uid, ExportResult* result) {
879
880 uid_t targetUid = getEffectiveUid(uid);
881 uid_t callingUid = IPCThreadState::self()->getCallingUid();
882 if (!is_granted_to(callingUid, targetUid)) {
883 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100884 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700885 return;
886 }
887
888 Blob keyBlob;
889 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700890
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100891 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
892 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700893 return;
894 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100895
896 auto key = blob2hidlVec(keyBlob);
897 auto& dev = mKeyStore->getDevice(keyBlob);
898
899 auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
900 result->resultCode = ret;
901 if (!result->resultCode.isOk()) {
Ji Wang2c142312016-10-14 17:21:10 +0800902 return;
903 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100904 result->exportData = keyMaterial;
905 };
906 KeyStoreServiceReturnCode rc =
907 KS_HANDLE_HIDL_ERROR(dev->exportKey(format, key, clientId, appData, hidlCb));
908 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
909 // callback hidlCb.
910 if (!rc.isOk()) {
911 result->resultCode = rc;
Ji Wang2c142312016-10-14 17:21:10 +0800912 }
913
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100914 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
915 AuthorizationSet upgradeParams;
916 if (clientId.size()) {
917 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
918 }
919 if (appData.size()) {
920 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
921 }
922 result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
923 if (!result->resultCode.isOk()) {
924 return;
925 }
926
927 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
928
929 result->resultCode = KS_HANDLE_HIDL_ERROR(
930 dev->exportKey(format, upgradedHidlKeyBlob, clientId, appData, hidlCb));
931 if (!result->resultCode.isOk()) {
932 return;
933 }
934 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700935}
936
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000937static inline void addAuthTokenToParams(AuthorizationSet* params, const HardwareAuthToken* token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100938 if (token) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000939 params->push_back(TAG_AUTH_TOKEN, authToken2HidlVec(*token));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100940 }
941}
942
943void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, KeyPurpose purpose,
944 bool pruneable, const hidl_vec<KeyParameter>& params,
945 const hidl_vec<uint8_t>& entropy, int32_t uid,
946 OperationResult* result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700947 uid_t callingUid = IPCThreadState::self()->getCallingUid();
948 uid_t targetUid = getEffectiveUid(uid);
949 if (!is_granted_to(callingUid, targetUid)) {
950 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100951 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700952 return;
953 }
954 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
955 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100956 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700957 return;
958 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100959 if (!checkAllowedOperationParams(params)) {
960 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700961 return;
962 }
963 Blob keyBlob;
964 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100965 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
966 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700967 return;
968 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100969
970 auto key = blob2hidlVec(keyBlob);
971 auto& dev = mKeyStore->getDevice(keyBlob);
972 AuthorizationSet opParams = params;
973 KeyCharacteristics characteristics;
974 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
975
976 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
977 result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
978 if (!result->resultCode.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -0600979 return;
980 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100981 key = blob2hidlVec(keyBlob);
982 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
Shawn Willden98c59162016-03-20 09:10:18 -0600983 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100984 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700985 return;
986 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100987
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000988 const HardwareAuthToken* authToken = NULL;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400989
990 // Merge these characteristics with the ones cached when the key was generated or imported
991 Blob charBlob;
992 AuthorizationSet persistedCharacteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100993 result->resultCode =
994 mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
995 if (result->resultCode.isOk()) {
996 // TODO write one shot stream buffer to avoid copying (twice here)
997 std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
998 charBlob.getLength());
999 std::stringstream charStream(charBuffer);
1000 persistedCharacteristics.Deserialize(&charStream);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001001 } else {
1002 ALOGD("Unable to read cached characteristics for key");
1003 }
1004
1005 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001006 AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
1007 AuthorizationSet teeEnforced = characteristics.teeEnforced;
1008 persistedCharacteristics.Union(softwareEnforced);
1009 persistedCharacteristics.Subtract(teeEnforced);
1010 characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001011
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001012 result->resultCode = getAuthToken(characteristics, 0, purpose, &authToken,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001013 /*failOnTokenMissing*/ false);
1014 // If per-operation auth is needed we need to begin the operation and
1015 // the client will need to authorize that operation before calling
1016 // update. Any other auth issues stop here.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001017 if (!result->resultCode.isOk() && result->resultCode != ResponseCode::OP_AUTH_NEEDED) return;
1018
1019 addAuthTokenToParams(&opParams, authToken);
1020
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001021 // Add entropy to the device first.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001022 if (entropy.size()) {
1023 result->resultCode = addRngEntropy(entropy);
1024 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001025 return;
1026 }
1027 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001028
1029 // Create a keyid for this key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001030 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001031 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
1032 ALOGE("Failed to create a key ID for authorization checking.");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001033 result->resultCode = ErrorCode::UNKNOWN_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001034 return;
1035 }
1036
1037 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001038 AuthorizationSet key_auths = characteristics.teeEnforced;
1039 key_auths.append(&characteristics.softwareEnforced[0],
1040 &characteristics.softwareEnforced[characteristics.softwareEnforced.size()]);
1041
1042 result->resultCode = enforcement_policy.AuthorizeOperation(
1043 purpose, keyid, key_auths, opParams, 0 /* op_handle */, true /* is_begin_operation */);
1044 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001045 return;
1046 }
1047
Shawn Willdene2a7b522017-04-11 09:27:40 -06001048 // If there are more than kMaxOperations, abort the oldest operation that was started as
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001049 // pruneable.
Shawn Willdene2a7b522017-04-11 09:27:40 -06001050 while (mOperationMap.getOperationCount() >= kMaxOperations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001051 ALOGD("Reached or exceeded concurrent operations limit");
1052 if (!pruneOperation()) {
1053 break;
1054 }
1055 }
1056
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001057 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1058 uint64_t operationHandle) {
1059 result->resultCode = ret;
1060 if (!result->resultCode.isOk()) {
1061 return;
1062 }
1063 result->handle = operationHandle;
1064 result->outParams = outParams;
1065 };
1066
1067 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
1068 if (rc != ErrorCode::OK) {
1069 ALOGW("Got error %d from begin()", rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001070 }
1071
1072 // If there are too many operations abort the oldest operation that was
1073 // started as pruneable and try again.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001074 while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1075 ALOGW("Ran out of operation handles");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001076 if (!pruneOperation()) {
1077 break;
1078 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001079 rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001080 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001081 if (rc != ErrorCode::OK) {
1082 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001083 return;
1084 }
1085
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001086 // Note: The operation map takes possession of the contents of "characteristics".
1087 // It is safe to use characteristics after the following line but it will be empty.
1088 sp<IBinder> operationToken = mOperationMap.addOperation(
1089 result->handle, keyid, purpose, dev, appToken, std::move(characteristics), pruneable);
1090 assert(characteristics.teeEnforced.size() == 0);
1091 assert(characteristics.softwareEnforced.size() == 0);
1092
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001093 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001094 mOperationMap.setOperationAuthToken(operationToken, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001095 }
1096 // Return the authentication lookup result. If this is a per operation
1097 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1098 // application should get an auth token using the handle before the
1099 // first call to update, which will fail if keystore hasn't received the
1100 // auth token.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001101 // All fields but "token" were set in the begin operation's callback.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001102 result->token = operationToken;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001103}
1104
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001105void KeyStoreService::update(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1106 const hidl_vec<uint8_t>& data, OperationResult* result) {
1107 if (!checkAllowedOperationParams(params)) {
1108 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001109 return;
1110 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001111 km_device_t dev;
1112 uint64_t handle;
1113 KeyPurpose purpose;
1114 km_id_t keyid;
1115 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001116 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001117 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001118 return;
1119 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001120 AuthorizationSet opParams = params;
1121 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1122 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001123 return;
1124 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001125
1126 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001127 AuthorizationSet key_auths(characteristics->teeEnforced);
1128 key_auths.append(&characteristics->softwareEnforced[0],
1129 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001130 result->resultCode = enforcement_policy.AuthorizeOperation(
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001131 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1132 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001133 return;
1134 }
1135
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001136 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
1137 const hidl_vec<KeyParameter>& outParams, const hidl_vec<uint8_t>& output) {
1138 result->resultCode = ret;
1139 if (!result->resultCode.isOk()) {
1140 return;
1141 }
1142 result->inputConsumed = inputConsumed;
1143 result->outParams = outParams;
1144 result->data = output;
1145 };
1146
Janis Danisevskisb0245ee2017-01-25 15:43:01 +00001147 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->update(handle, opParams.hidl_data(),
1148 data, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001149 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1150 // it if there was a communication error indicated by the ErrorCode.
1151 if (!rc.isOk()) {
1152 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001153 }
1154}
1155
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001156void KeyStoreService::finish(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1157 const hidl_vec<uint8_t>& signature, const hidl_vec<uint8_t>& entropy,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001158 OperationResult* result) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001159 if (!checkAllowedOperationParams(params)) {
1160 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001161 return;
1162 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001163 km_device_t dev;
1164 uint64_t handle;
1165 KeyPurpose purpose;
1166 km_id_t keyid;
1167 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001168 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001169 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001170 return;
1171 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001172 AuthorizationSet opParams = params;
1173 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1174 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001175 return;
1176 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001177
1178 if (entropy.size()) {
1179 result->resultCode = addRngEntropy(entropy);
1180 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001181 return;
1182 }
1183 }
1184
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001185 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001186 AuthorizationSet key_auths(characteristics->teeEnforced);
1187 key_auths.append(&characteristics->softwareEnforced[0],
1188 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
1189 result->resultCode = enforcement_policy.AuthorizeOperation(
1190 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1191 if (!result->resultCode.isOk()) return;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001192
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001193 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1194 const hidl_vec<uint8_t>& output) {
1195 result->resultCode = ret;
1196 if (!result->resultCode.isOk()) {
1197 return;
1198 }
1199 result->outParams = outParams;
1200 result->data = output;
1201 };
1202
1203 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->finish(
1204 handle, opParams.hidl_data(),
1205 hidl_vec<uint8_t>() /* TODO(swillden): wire up input to finish() */, signature, hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001206 // Remove the operation regardless of the result
1207 mOperationMap.removeOperation(token);
1208 mAuthTokenTable.MarkCompleted(handle);
1209
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001210 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1211 // it if there was a communication error indicated by the ErrorCode.
1212 if (!rc.isOk()) {
1213 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001214 }
1215}
1216
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001217KeyStoreServiceReturnCode KeyStoreService::abort(const sp<IBinder>& token) {
1218 km_device_t dev;
1219 uint64_t handle;
1220 KeyPurpose purpose;
1221 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001222 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001223 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001224 }
1225 mOperationMap.removeOperation(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001226
1227 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->abort(handle));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001228 mAuthTokenTable.MarkCompleted(handle);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001229 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001230}
1231
1232bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001233 km_device_t dev;
1234 uint64_t handle;
1235 const KeyCharacteristics* characteristics;
1236 KeyPurpose purpose;
1237 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001238 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1239 return false;
1240 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001241 const HardwareAuthToken* authToken = NULL;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001242 mOperationMap.getOperationAuthToken(token, &authToken);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001243 AuthorizationSet ignored;
1244 auto authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1245 return authResult.isOk();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001246}
1247
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001248KeyStoreServiceReturnCode KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001249 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1250 // receive a HardwareAuthToken, rather than an opaque byte array.
1251
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001252 if (!checkBinderPermission(P_ADD_AUTH)) {
1253 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001254 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001255 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001256 if (length != sizeof(hw_auth_token_t)) {
1257 return ErrorCode::INVALID_ARGUMENT;
1258 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001259
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001260 hw_auth_token_t authToken;
1261 memcpy(reinterpret_cast<void*>(&authToken), token, sizeof(hw_auth_token_t));
1262 if (authToken.version != 0) {
1263 return ErrorCode::INVALID_ARGUMENT;
1264 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001265
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001266 std::unique_ptr<HardwareAuthToken> hidlAuthToken(new HardwareAuthToken);
1267 hidlAuthToken->challenge = authToken.challenge;
1268 hidlAuthToken->userId = authToken.user_id;
1269 hidlAuthToken->authenticatorId = authToken.authenticator_id;
1270 hidlAuthToken->authenticatorType = authToken.authenticator_type;
1271 hidlAuthToken->timestamp = authToken.timestamp;
1272 static_assert(
1273 std::is_same<decltype(hidlAuthToken->hmac),
1274 ::android::hardware::hidl_array<uint8_t, sizeof(authToken.hmac)>>::value,
1275 "This function assumes token HMAC is 32 bytes, but it might not be.");
1276 std::copy(authToken.hmac, authToken.hmac + sizeof(authToken.hmac), hidlAuthToken->hmac.data());
1277
1278 // The table takes ownership of authToken.
1279 mAuthTokenTable.AddAuthenticationToken(hidlAuthToken.release());
1280 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001281}
1282
Janis Danisevskis7612fd42016-09-01 11:50:02 +01001283constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
1284
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001285bool isDeviceIdAttestationRequested(const hidl_vec<KeyParameter>& params) {
1286 for (size_t i = 0; i < params.size(); ++i) {
1287 switch (params[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -06001288 case Tag::ATTESTATION_ID_BRAND:
1289 case Tag::ATTESTATION_ID_DEVICE:
1290 case Tag::ATTESTATION_ID_IMEI:
1291 case Tag::ATTESTATION_ID_MANUFACTURER:
1292 case Tag::ATTESTATION_ID_MEID:
1293 case Tag::ATTESTATION_ID_MODEL:
1294 case Tag::ATTESTATION_ID_PRODUCT:
1295 case Tag::ATTESTATION_ID_SERIAL:
1296 return true;
1297 default:
1298 break;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001299 }
1300 }
1301 return false;
1302}
1303
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001304KeyStoreServiceReturnCode KeyStoreService::attestKey(const String16& name,
1305 const hidl_vec<KeyParameter>& params,
1306 hidl_vec<hidl_vec<uint8_t>>* outChain) {
1307 if (!outChain) {
1308 return ErrorCode::OUTPUT_PARAMETER_NULL;
1309 }
Shawn Willden50eb1b22016-01-21 12:41:23 -07001310
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001311 if (!checkAllowedOperationParams(params)) {
1312 return ErrorCode::INVALID_ARGUMENT;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001313 }
1314
1315 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1316
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001317 bool attestingDeviceIds = isDeviceIdAttestationRequested(params);
1318 if (attestingDeviceIds) {
1319 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1320 if (binder == 0) {
1321 return ErrorCode::CANNOT_ATTEST_IDS;
1322 }
1323 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1324 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1325 IPCThreadState::self()->getCallingPid(), callingUid)) {
Shawn Willdene2a7b522017-04-11 09:27:40 -06001326 return ErrorCode::CANNOT_ATTEST_IDS;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001327 }
1328 }
1329
Shawn Willdene2a7b522017-04-11 09:27:40 -06001330 AuthorizationSet mutableParams = params;
1331
1332 KeyStoreServiceReturnCode responseCode;
1333 bool factoryResetSinceIdRotation;
1334 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
1335
1336 if (!responseCode.isOk()) return responseCode;
1337 if (factoryResetSinceIdRotation) mutableParams.push_back(TAG_RESET_SINCE_ID_ROTATION);
1338
Shawn Willden50eb1b22016-01-21 12:41:23 -07001339 Blob keyBlob;
1340 String8 name8(name);
Shawn Willdene2a7b522017-04-11 09:27:40 -06001341 responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001342 if (!responseCode.isOk()) {
Shawn Willden50eb1b22016-01-21 12:41:23 -07001343 return responseCode;
1344 }
1345
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001346 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
Janis Danisevskis011675d2016-09-01 11:41:29 +01001347 if (!asn1_attestation_id_result.isOk()) {
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001348 ALOGE("failed to gather attestation_id");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001349 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001350 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001351 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001352
1353 /*
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001354 * The attestation application ID cannot be longer than
1355 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, so we truncate if too long.
Janis Danisevskis18f27ad2016-06-01 13:57:40 -07001356 */
Shawn Willdene2a7b522017-04-11 09:27:40 -06001357 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001358 asn1_attestation_id.resize(KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE);
Shawn Willdene2a7b522017-04-11 09:27:40 -06001359 }
Shawn Willden50eb1b22016-01-21 12:41:23 -07001360
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001361 mutableParams.push_back(TAG_ATTESTATION_APPLICATION_ID, blob2hidlVec(asn1_attestation_id));
1362
1363 KeyStoreServiceReturnCode error;
1364 auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1365 error = ret;
1366 if (!error.isOk()) {
1367 return;
1368 }
1369 if (outChain) *outChain = certChain;
1370 };
1371
1372 auto hidlKey = blob2hidlVec(keyBlob);
1373 auto& dev = mKeyStore->getDevice(keyBlob);
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001374 KeyStoreServiceReturnCode attestationRc =
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001375 KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001376
1377 KeyStoreServiceReturnCode deletionRc;
1378 if (attestingDeviceIds) {
1379 // When performing device id attestation, treat the key as ephemeral and delete it straight
1380 // away.
1381 deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001382 }
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001383
1384 if (!attestationRc.isOk()) {
1385 return attestationRc;
1386 }
1387 if (!error.isOk()) {
1388 return error;
1389 }
1390 return deletionRc;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001391}
1392
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001393KeyStoreServiceReturnCode KeyStoreService::onDeviceOffBody() {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001394 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1395 mAuthTokenTable.onDeviceOffBody();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001396 return ResponseCode::NO_ERROR;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001397}
1398
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001399/**
1400 * Prune the oldest pruneable operation.
1401 */
1402bool KeyStoreService::pruneOperation() {
1403 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1404 ALOGD("Trying to prune operation %p", oldest.get());
1405 size_t op_count_before_abort = mOperationMap.getOperationCount();
1406 // We mostly ignore errors from abort() because all we care about is whether at least
1407 // one operation has been removed.
1408 int abort_error = abort(oldest);
1409 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1410 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1411 return false;
1412 }
1413 return true;
1414}
1415
1416/**
1417 * Get the effective target uid for a binder operation that takes an
1418 * optional uid as the target.
1419 */
1420uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1421 if (targetUid == UID_SELF) {
1422 return IPCThreadState::self()->getCallingUid();
1423 }
1424 return static_cast<uid_t>(targetUid);
1425}
1426
1427/**
1428 * Check if the caller of the current binder method has the required
1429 * permission and if acting on other uids the grants to do so.
1430 */
1431bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1432 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1433 pid_t spid = IPCThreadState::self()->getCallingPid();
1434 if (!has_permission(callingUid, permission, spid)) {
1435 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1436 return false;
1437 }
1438 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1439 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1440 return false;
1441 }
1442 return true;
1443}
1444
1445/**
1446 * Check if the caller of the current binder method has the required
1447 * permission and the target uid is the caller or the caller is system.
1448 */
1449bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1450 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1451 pid_t spid = IPCThreadState::self()->getCallingPid();
1452 if (!has_permission(callingUid, permission, spid)) {
1453 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1454 return false;
1455 }
1456 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1457}
1458
1459/**
1460 * Check if the caller of the current binder method has the required
1461 * permission or the target of the operation is the caller's uid. This is
1462 * for operation where the permission is only for cross-uid activity and all
1463 * uids are allowed to act on their own (ie: clearing all entries for a
1464 * given uid).
1465 */
1466bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1467 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1468 if (getEffectiveUid(targetUid) == callingUid) {
1469 return true;
1470 } else {
1471 return checkBinderPermission(permission, targetUid);
1472 }
1473}
1474
1475/**
1476 * Helper method to check that the caller has the required permission as
1477 * well as the keystore is in the unlocked state if checkUnlocked is true.
1478 *
1479 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1480 * otherwise the state of keystore when not unlocked and checkUnlocked is
1481 * true.
1482 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001483KeyStoreServiceReturnCode
1484KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1485 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001486 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001487 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001488 }
1489 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1490 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001491 // All State values coincide with ResponseCodes
1492 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001493 }
1494
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001495 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001496}
1497
1498bool KeyStoreService::isKeystoreUnlocked(State state) {
1499 switch (state) {
1500 case ::STATE_NO_ERROR:
1501 return true;
1502 case ::STATE_UNINITIALIZED:
1503 case ::STATE_LOCKED:
1504 return false;
1505 }
1506 return false;
1507}
1508
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001509/**
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001510 * Check that all KeyParameter's provided by the application are
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001511 * allowed. Any parameter that keystore adds itself should be disallowed here.
1512 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001513bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1514 for (size_t i = 0; i < params.size(); ++i) {
1515 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001516 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001517 case Tag::AUTH_TOKEN:
1518 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001519 return false;
1520 default:
1521 break;
1522 }
1523 }
1524 return true;
1525}
1526
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001527ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
1528 km_device_t* dev,
1529 const AuthorizationSet& params,
1530 KeyCharacteristics* out) {
1531 hidl_vec<uint8_t> appId;
1532 hidl_vec<uint8_t> appData;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001533 for (auto param : params) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001534 if (param.tag == Tag::APPLICATION_ID) {
1535 appId = authorizationValue(TAG_APPLICATION_ID, param).value();
1536 } else if (param.tag == Tag::APPLICATION_DATA) {
1537 appData = authorizationValue(TAG_APPLICATION_DATA, param).value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001538 }
1539 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001540 ErrorCode error = ErrorCode::OK;
1541
1542 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
1543 error = ret;
1544 if (error != ErrorCode::OK) {
1545 return;
1546 }
1547 if (out) *out = keyCharacteristics;
1548 };
1549
1550 ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appData, hidlCb));
1551 if (rc != ErrorCode::OK) {
1552 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001553 }
1554 return error;
1555}
1556
1557/**
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001558 * Get the auth token for this operation from the auth token table.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001559 *
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001560 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
1561 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1562 * authorization token exists for that operation and
1563 * failOnTokenMissing is false.
1564 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1565 * token for the operation
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001566 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001567KeyStoreServiceReturnCode KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics,
1568 uint64_t handle, KeyPurpose purpose,
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001569 const HardwareAuthToken** authToken,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001570 bool failOnTokenMissing) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001571
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001572 AuthorizationSet allCharacteristics;
1573 for (size_t i = 0; i < characteristics.softwareEnforced.size(); i++) {
1574 allCharacteristics.push_back(characteristics.softwareEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001575 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001576 for (size_t i = 0; i < characteristics.teeEnforced.size(); i++) {
1577 allCharacteristics.push_back(characteristics.teeEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001578 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001579 AuthTokenTable::Error err =
1580 mAuthTokenTable.FindAuthorization(allCharacteristics, purpose, handle, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001581 switch (err) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001582 case AuthTokenTable::OK:
1583 case AuthTokenTable::AUTH_NOT_REQUIRED:
1584 return ResponseCode::NO_ERROR;
1585 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1586 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
1587 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
1588 return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1589 case AuthTokenTable::OP_HANDLE_REQUIRED:
1590 return failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
1591 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001592 default:
1593 ALOGE("Unexpected FindAuthorization return value %d", err);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001594 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001595 }
1596}
1597
1598/**
1599 * Add the auth token for the operation to the param list if the operation
1600 * requires authorization. Uses the cached result in the OperationMap if available
1601 * otherwise gets the token from the AuthTokenTable and caches the result.
1602 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001603 * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001604 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1605 * authenticated.
1606 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1607 * operation token.
1608 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001609KeyStoreServiceReturnCode KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
1610 AuthorizationSet* params) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001611 const HardwareAuthToken* authToken = nullptr;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001612 mOperationMap.getOperationAuthToken(token, &authToken);
1613 if (!authToken) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001614 km_device_t dev;
1615 uint64_t handle;
1616 const KeyCharacteristics* characteristics = nullptr;
1617 KeyPurpose purpose;
1618 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001619 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001620 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001621 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001622 auto result = getAuthToken(*characteristics, handle, purpose, &authToken);
1623 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001624 return result;
1625 }
1626 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001627 mOperationMap.setOperationAuthToken(token, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001628 }
1629 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001630 addAuthTokenToParams(params, authToken);
1631 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001632}
1633
1634/**
1635 * Translate a result value to a legacy return value. All keystore errors are
1636 * preserved and keymaster errors become SYSTEM_ERRORs
1637 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001638KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001639 if (result > 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001640 return static_cast<ResponseCode>(result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001641 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001642 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001643}
1644
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001645static NullOr<const Algorithm&>
1646getKeyAlgoritmFromKeyCharacteristics(const KeyCharacteristics& characteristics) {
1647 for (size_t i = 0; i < characteristics.teeEnforced.size(); ++i) {
1648 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.teeEnforced[i]);
1649 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001650 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001651 for (size_t i = 0; i < characteristics.softwareEnforced.size(); ++i) {
1652 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.softwareEnforced[i]);
1653 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001654 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001655 return {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001656}
1657
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001658void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001659 // All legacy keys are DIGEST_NONE/PAD_NONE.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001660 params->push_back(TAG_DIGEST, Digest::NONE);
1661 params->push_back(TAG_PADDING, PaddingMode::NONE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001662
1663 // Look up the algorithm of the key.
1664 KeyCharacteristics characteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001665 auto rc = getKeyCharacteristics(name, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF,
1666 &characteristics);
1667 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001668 ALOGE("Failed to get key characteristics");
1669 return;
1670 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001671 auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
1672 if (!algorithm.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001673 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1674 return;
1675 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001676 params->push_back(TAG_ALGORITHM, algorithm.value());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001677}
1678
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001679KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
1680 const hidl_vec<uint8_t>& data,
1681 hidl_vec<uint8_t>* out,
1682 const hidl_vec<uint8_t>& signature,
1683 KeyPurpose purpose) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001684
1685 std::basic_stringstream<uint8_t> outBuffer;
1686 OperationResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001687 AuthorizationSet inArgs;
1688 addLegacyBeginParams(name, &inArgs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001689 sp<IBinder> appToken(new BBinder);
1690 sp<IBinder> token;
1691
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001692 begin(appToken, name, purpose, true, inArgs.hidl_data(), hidl_vec<uint8_t>(), UID_SELF,
1693 &result);
1694 if (!result.resultCode.isOk()) {
1695 if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001696 ALOGW("Key not found");
1697 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001698 ALOGW("Error in begin: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001699 }
1700 return translateResultToLegacyResult(result.resultCode);
1701 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001702 inArgs.Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001703 token = result.token;
1704 size_t consumed = 0;
1705 size_t lastConsumed = 0;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001706 hidl_vec<uint8_t> data_view;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001707 do {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001708 data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
1709 update(token, inArgs.hidl_data(), data_view, &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001710 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001711 ALOGW("Error in update: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001712 return translateResultToLegacyResult(result.resultCode);
1713 }
1714 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001715 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001716 }
1717 lastConsumed = result.inputConsumed;
1718 consumed += lastConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001719 } while (consumed < data.size() && lastConsumed > 0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001720
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001721 if (consumed != data.size()) {
1722 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
1723 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001724 }
1725
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001726 finish(token, inArgs.hidl_data(), signature, hidl_vec<uint8_t>(), &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001727 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001728 ALOGW("Error in finish: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001729 return translateResultToLegacyResult(result.resultCode);
1730 }
1731 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001732 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001733 }
1734
1735 if (out) {
1736 auto buf = outBuffer.str();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001737 out->resize(buf.size());
1738 memcpy(&(*out)[0], buf.data(), out->size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001739 }
1740
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001741 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001742}
1743
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001744KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
1745 const AuthorizationSet& params,
1746 Blob* blob) {
Shawn Willden98c59162016-03-20 09:10:18 -06001747 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
1748 String8 name8(name);
1749 ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001750 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willden98c59162016-03-20 09:10:18 -06001751 return responseCode;
1752 }
Rubin Xu7675c9f2017-03-15 19:26:52 +00001753 ALOGI("upgradeKeyBlob %s %d", name8.string(), uid);
Shawn Willden98c59162016-03-20 09:10:18 -06001754
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001755 auto hidlKey = blob2hidlVec(*blob);
1756 auto& dev = mKeyStore->getDevice(*blob);
Shawn Willden98c59162016-03-20 09:10:18 -06001757
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001758 KeyStoreServiceReturnCode error;
1759 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
1760 error = ret;
1761 if (!error.isOk()) {
1762 return;
1763 }
1764
1765 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1766 error = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(uid));
1767 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001768 ALOGI("upgradeKeyBlob keystore->del failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001769 return;
1770 }
1771
1772 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
1773 0 /* infoLength */, ::TYPE_KEYMASTER_10);
1774 newBlob.setFallback(blob->isFallback());
1775 newBlob.setEncrypted(blob->isEncrypted());
1776
1777 error = mKeyStore->put(filename.string(), &newBlob, get_user_id(uid));
1778 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001779 ALOGI("upgradeKeyBlob keystore->put failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001780 return;
1781 }
1782
1783 // Re-read blob for caller. We can't use newBlob because writing it modified it.
1784 error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1785 };
1786
1787 KeyStoreServiceReturnCode rc =
1788 KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
1789 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001790 return rc;
1791 }
1792
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001793 return error;
Shawn Willden98c59162016-03-20 09:10:18 -06001794}
1795
Shawn Willdene2a7b522017-04-11 09:27:40 -06001796} // namespace keystore