blob: 39341ef89bf4e7f310ebc9e99555f73cee8968ba [file] [log] [blame]
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Janis Danisevskis011675d2016-09-01 11:41:29 +010017#define LOG_TAG "keystore"
18
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070019#include "key_store_service.h"
20
21#include <fcntl.h>
22#include <sys/stat.h>
23
Janis Danisevskis7612fd42016-09-01 11:50:02 +010024#include <algorithm>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070025#include <sstream>
26
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010027#include <binder/IInterface.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070028#include <binder/IPCThreadState.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010029#include <binder/IPermissionController.h>
30#include <binder/IServiceManager.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070031
32#include <private/android_filesystem_config.h>
33
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010034#include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070035
36#include "defaults.h"
Janis Danisevskis18f27ad2016-06-01 13:57:40 -070037#include "keystore_attestation_id.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010038#include "keystore_keymaster_enforcement.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070039#include "keystore_utils.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010040#include <keystore/keystore_hidl_support.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070041
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010042namespace keystore {
Shawn Willdend5a24e62017-02-28 13:53:24 -070043
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010044using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070045
Shawn Willdene2a7b522017-04-11 09:27:40 -060046namespace {
47
48constexpr size_t kMaxOperations = 15;
49constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
50const char* kTimestampFilePath = "timestamp";
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070051
52struct BIGNUM_Delete {
53 void operator()(BIGNUM* p) const { BN_free(p); }
54};
Janis Danisevskisccfff102017-05-01 11:02:51 -070055typedef std::unique_ptr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070056
Shawn Willdene2a7b522017-04-11 09:27:40 -060057bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
58 return params.end() != std::find_if(params.begin(), params.end(),
59 [&](auto& param) { return param.tag == tag; });
60}
61
Shawn Willdend5a24e62017-02-28 13:53:24 -070062bool isAuthenticationBound(const hidl_vec<KeyParameter>& params) {
63 return !containsTag(params, Tag::NO_AUTH_REQUIRED);
64}
Janis Danisevskis54fcc992019-03-25 10:26:30 -070065#define KEYSTORE_SERVICE_LOCK \
66 std::lock_guard<decltype(keystoreServiceMutex_)> keystore_lock(keystoreServiceMutex_)
Shawn Willdend5a24e62017-02-28 13:53:24 -070067
Shawn Willdene2a7b522017-04-11 09:27:40 -060068std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
69 struct stat sbuf;
70 if (stat(kTimestampFilePath, &sbuf) == 0) {
71 double diff_secs = difftime(time(NULL), sbuf.st_ctime);
72 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
73 }
74
75 if (errno != ENOENT) {
76 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
77 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
78 }
79
80 int fd = creat(kTimestampFilePath, 0600);
81 if (fd < 0) {
82 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
83 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
84 }
85
86 if (close(fd)) {
87 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
88 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
89 }
90
91 return {ResponseCode::NO_ERROR, true};
92}
93
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +020094constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
95
96KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
97 KeyStoreServiceReturnCode responseCode;
98 bool factoryResetSinceIdRotation;
99 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
100
101 if (!responseCode.isOk()) return responseCode;
102 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
103
104 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
105 if (!asn1_attestation_id_result.isOk()) {
106 ALOGE("failed to gather attestation_id");
107 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
108 }
109 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
110
111 /*
112 * The attestation application ID cannot be longer than
113 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, so we truncate if too long.
114 */
115 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
116 asn1_attestation_id.resize(KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE);
117 }
118
119 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
120
121 return ResponseCode::NO_ERROR;
122}
123
Shawn Willdene2a7b522017-04-11 09:27:40 -0600124} // anonymous namespace
125
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700126void KeyStoreService::binderDied(const wp<IBinder>& who) {
127 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700128 for (const auto& token : operations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700129 abort(token);
130 }
131}
132
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100133KeyStoreServiceReturnCode KeyStoreService::getState(int32_t userId) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700134 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700135 if (!checkBinderPermission(P_GET_STATE)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100136 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700137 }
138
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100139 return ResponseCode(mKeyStore->getState(userId));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700140}
141
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100142KeyStoreServiceReturnCode KeyStoreService::get(const String16& name, int32_t uid,
143 hidl_vec<uint8_t>* item) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700144 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700145 uid_t targetUid = getEffectiveUid(uid);
146 if (!checkBinderPermission(P_GET, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100147 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700148 }
149
150 String8 name8(name);
151 Blob keyBlob;
152
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100153 KeyStoreServiceReturnCode rc =
154 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
155 if (!rc.isOk()) {
156 if (item) *item = hidl_vec<uint8_t>();
157 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700158 }
159
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100160 // Do not replace this with "if (item) *item = blob2hidlVec(keyBlob)"!
161 // blob2hidlVec creates a hidl_vec<uint8_t> that references, but not owns, the data in keyBlob
162 // the subsequent assignment (*item = resultBlob) makes a deep copy, so that *item will own the
163 // corresponding resources.
164 auto resultBlob = blob2hidlVec(keyBlob);
165 if (item) {
166 *item = resultBlob;
167 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700168
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100169 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700170}
171
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100172KeyStoreServiceReturnCode KeyStoreService::insert(const String16& name,
173 const hidl_vec<uint8_t>& item, int targetUid,
174 int32_t flags) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700175 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700176 targetUid = getEffectiveUid(targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100177 auto result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700178 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100179 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700180 return result;
181 }
182
183 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400184 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_GENERIC));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700185
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100186 Blob keyBlob(&item[0], item.size(), NULL, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700187 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
188
189 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
190}
191
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100192KeyStoreServiceReturnCode KeyStoreService::del(const String16& name, int targetUid) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700193 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700194 targetUid = getEffectiveUid(targetUid);
195 if (!checkBinderPermission(P_DELETE, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100196 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700197 }
198 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000199 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700200 auto filename = mKeyStore->getBlobFileNameIfExists(name8, targetUid, ::TYPE_ANY);
201 if (!filename.isOk()) return ResponseCode::KEY_NOT_FOUND;
202
203 ResponseCode result = mKeyStore->del(filename.value().string(), ::TYPE_ANY,
204 get_user_id(targetUid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100205 if (result != ResponseCode::NO_ERROR) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400206 return result;
207 }
208
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700209 filename = mKeyStore->getBlobFileNameIfExists(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS);
210 if (filename.isOk()) {
211 return mKeyStore->del(filename.value().string(), ::TYPE_KEY_CHARACTERISTICS,
212 get_user_id(targetUid));
213 }
214 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700215}
216
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100217KeyStoreServiceReturnCode KeyStoreService::exist(const String16& name, int targetUid) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700218 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700219 targetUid = getEffectiveUid(targetUid);
220 if (!checkBinderPermission(P_EXIST, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100221 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700222 }
223
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700224 auto filename = mKeyStore->getBlobFileNameIfExists(String8(name), targetUid, ::TYPE_ANY);
225 return filename.isOk() ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700226}
227
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100228KeyStoreServiceReturnCode KeyStoreService::list(const String16& prefix, int targetUid,
229 Vector<String16>* matches) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700230 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700231 targetUid = getEffectiveUid(targetUid);
232 if (!checkBinderPermission(P_LIST, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100233 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700234 }
235 const String8 prefix8(prefix);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400236 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid, TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700237
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100238 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
239 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700240 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100241 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700242}
243
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100244KeyStoreServiceReturnCode KeyStoreService::reset() {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700245 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700246 if (!checkBinderPermission(P_RESET)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100247 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700248 }
249
250 uid_t callingUid = IPCThreadState::self()->getCallingUid();
251 mKeyStore->resetUser(get_user_id(callingUid), false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100252 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700253}
254
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100255KeyStoreServiceReturnCode KeyStoreService::onUserPasswordChanged(int32_t userId,
256 const String16& password) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700257 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700258 if (!checkBinderPermission(P_PASSWORD)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100259 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700260 }
261
262 const String8 password8(password);
263 // Flush the auth token table to prevent stale tokens from sticking
264 // around.
265 mAuthTokenTable.Clear();
266
267 if (password.size() == 0) {
268 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
269 mKeyStore->resetUser(userId, true);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100270 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700271 } else {
272 switch (mKeyStore->getState(userId)) {
273 case ::STATE_UNINITIALIZED: {
274 // generate master key, encrypt with password, write to file,
275 // initialize mMasterKey*.
276 return mKeyStore->initializeUser(password8, userId);
277 }
278 case ::STATE_NO_ERROR: {
279 // rewrite master key with new password.
280 return mKeyStore->writeMasterKey(password8, userId);
281 }
282 case ::STATE_LOCKED: {
283 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
284 mKeyStore->resetUser(userId, true);
285 return mKeyStore->initializeUser(password8, userId);
286 }
287 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100288 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700289 }
290}
291
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100292KeyStoreServiceReturnCode KeyStoreService::onUserAdded(int32_t userId, int32_t parentId) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700293 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700294 if (!checkBinderPermission(P_USER_CHANGED)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100295 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700296 }
297
298 // Sanity check that the new user has an empty keystore.
299 if (!mKeyStore->isEmpty(userId)) {
300 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
301 }
302 // Unconditionally clear the keystore, just to be safe.
303 mKeyStore->resetUser(userId, false);
304 if (parentId != -1) {
305 // This profile must share the same master key password as the parent profile. Because the
306 // password of the parent profile is not known here, the best we can do is copy the parent's
307 // master key and master key file. This makes this profile use the same master key as the
308 // parent profile, forever.
309 return mKeyStore->copyMasterKey(parentId, userId);
310 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100311 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700312 }
313}
314
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100315KeyStoreServiceReturnCode KeyStoreService::onUserRemoved(int32_t userId) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700316 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700317 if (!checkBinderPermission(P_USER_CHANGED)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100318 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700319 }
320
321 mKeyStore->resetUser(userId, false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100322 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700323}
324
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100325KeyStoreServiceReturnCode KeyStoreService::lock(int32_t userId) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700326 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700327 if (!checkBinderPermission(P_LOCK)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100328 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700329 }
330
331 State state = mKeyStore->getState(userId);
332 if (state != ::STATE_NO_ERROR) {
333 ALOGD("calling lock in state: %d", state);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100334 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700335 }
336
337 mKeyStore->lock(userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100338 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700339}
340
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100341KeyStoreServiceReturnCode KeyStoreService::unlock(int32_t userId, const String16& pw) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700342 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700343 if (!checkBinderPermission(P_UNLOCK)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100344 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700345 }
346
347 State state = mKeyStore->getState(userId);
348 if (state != ::STATE_LOCKED) {
349 switch (state) {
350 case ::STATE_NO_ERROR:
351 ALOGI("calling unlock when already unlocked, ignoring.");
352 break;
353 case ::STATE_UNINITIALIZED:
354 ALOGE("unlock called on uninitialized keystore.");
355 break;
356 default:
357 ALOGE("unlock called on keystore in unknown state: %d", state);
358 break;
359 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100360 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700361 }
362
363 const String8 password8(pw);
364 // read master key, decrypt with password, initialize mMasterKey*.
365 return mKeyStore->readMasterKey(password8, userId);
366}
367
368bool KeyStoreService::isEmpty(int32_t userId) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700369 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700370 if (!checkBinderPermission(P_IS_EMPTY)) {
371 return false;
372 }
373
374 return mKeyStore->isEmpty(userId);
375}
376
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100377KeyStoreServiceReturnCode KeyStoreService::generate(const String16& name, int32_t targetUid,
378 int32_t keyType, int32_t keySize, int32_t flags,
379 Vector<sp<KeystoreArg>>* args) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700380 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700381 targetUid = getEffectiveUid(targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100382 auto result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700383 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100384 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700385 return result;
386 }
387
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100388 keystore::AuthorizationSet params;
389 add_legacy_key_authorizations(keyType, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700390
391 switch (keyType) {
392 case EVP_PKEY_EC: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100393 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700394 if (keySize == -1) {
395 keySize = EC_DEFAULT_KEY_SIZE;
396 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
397 ALOGI("invalid key size %d", keySize);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100398 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700399 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100400 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700401 break;
402 }
403 case EVP_PKEY_RSA: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100404 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700405 if (keySize == -1) {
406 keySize = RSA_DEFAULT_KEY_SIZE;
407 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
408 ALOGI("invalid key size %d", keySize);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100409 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700410 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100411 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700412 unsigned long exponent = RSA_DEFAULT_EXPONENT;
413 if (args->size() > 1) {
414 ALOGI("invalid number of arguments: %zu", args->size());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100415 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700416 } else if (args->size() == 1) {
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700417 const sp<KeystoreArg>& expArg = args->itemAt(0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700418 if (expArg != NULL) {
419 Unique_BIGNUM pubExpBn(BN_bin2bn(
420 reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
421 if (pubExpBn.get() == NULL) {
422 ALOGI("Could not convert public exponent to BN");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100423 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700424 }
425 exponent = BN_get_word(pubExpBn.get());
426 if (exponent == 0xFFFFFFFFL) {
427 ALOGW("cannot represent public exponent as a long value");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100428 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700429 }
430 } else {
431 ALOGW("public exponent not read");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100432 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700433 }
434 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100435 params.push_back(TAG_RSA_PUBLIC_EXPONENT, exponent);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700436 break;
437 }
438 default: {
439 ALOGW("Unsupported key type %d", keyType);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100440 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700441 }
442 }
443
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100444 auto rc = generateKey(name, params.hidl_data(), hidl_vec<uint8_t>(), targetUid, flags,
445 /*outCharacteristics*/ NULL);
446 if (!rc.isOk()) {
447 ALOGW("generate failed: %d", int32_t(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700448 }
449 return translateResultToLegacyResult(rc);
450}
451
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100452KeyStoreServiceReturnCode KeyStoreService::import(const String16& name,
453 const hidl_vec<uint8_t>& data, int targetUid,
454 int32_t flags) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700455
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700456 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100457 const uint8_t* ptr = &data[0];
458
459 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, data.size()));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700460 if (!pkcs8.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100461 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700462 }
463 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
464 if (!pkey.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100465 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700466 }
467 int type = EVP_PKEY_type(pkey->type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100468 AuthorizationSet params;
469 add_legacy_key_authorizations(type, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700470 switch (type) {
471 case EVP_PKEY_RSA:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100472 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700473 break;
474 case EVP_PKEY_EC:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100475 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700476 break;
477 default:
478 ALOGW("Unsupported key type %d", type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100479 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700480 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100481
482 auto rc = importKey(name, params.hidl_data(), KeyFormat::PKCS8, data, targetUid, flags,
483 /*outCharacteristics*/ NULL);
484
485 if (!rc.isOk()) {
486 ALOGW("importKey failed: %d", int32_t(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700487 }
488 return translateResultToLegacyResult(rc);
489}
490
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100491KeyStoreServiceReturnCode KeyStoreService::sign(const String16& name, const hidl_vec<uint8_t>& data,
492 hidl_vec<uint8_t>* out) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700493 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700494 if (!checkBinderPermission(P_SIGN)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100495 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700496 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100497 return doLegacySignVerify(name, data, out, hidl_vec<uint8_t>(), KeyPurpose::SIGN);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700498}
499
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100500KeyStoreServiceReturnCode KeyStoreService::verify(const String16& name,
501 const hidl_vec<uint8_t>& data,
502 const hidl_vec<uint8_t>& signature) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700503 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700504 if (!checkBinderPermission(P_VERIFY)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100505 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700506 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100507 return doLegacySignVerify(name, data, nullptr, signature, KeyPurpose::VERIFY);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700508}
509
510/*
511 * TODO: The abstraction between things stored in hardware and regular blobs
512 * of data stored on the filesystem should be moved down to keystore itself.
513 * Unfortunately the Java code that calls this has naming conventions that it
514 * knows about. Ideally keystore shouldn't be used to store random blobs of
515 * data.
516 *
517 * Until that happens, it's necessary to have a separate "get_pubkey" and
518 * "del_key" since the Java code doesn't really communicate what it's
519 * intentions are.
520 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100521KeyStoreServiceReturnCode KeyStoreService::get_pubkey(const String16& name,
522 hidl_vec<uint8_t>* pubKey) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700523 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700524 ExportResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100525 exportKey(name, KeyFormat::X509, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF, &result);
526 if (!result.resultCode.isOk()) {
527 ALOGW("export failed: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700528 return translateResultToLegacyResult(result.resultCode);
529 }
530
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100531 if (pubKey) *pubKey = std::move(result.exportData);
532 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700533}
534
Janis Danisevskis6d449e82017-06-07 18:03:31 -0700535String16 KeyStoreService::grant(const String16& name, int32_t granteeUid) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700536 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700537 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100538 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
539 if (!result.isOk()) {
Janis Danisevskis6d449e82017-06-07 18:03:31 -0700540 return String16();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700541 }
542
543 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400544 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700545
546 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskis6d449e82017-06-07 18:03:31 -0700547 return String16();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700548 }
549
Janis Danisevskis3f303642017-09-20 16:30:19 -0700550 return String16(mKeyStore->addGrant(String8(name).string(), callingUid, granteeUid).c_str());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700551}
552
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100553KeyStoreServiceReturnCode KeyStoreService::ungrant(const String16& name, int32_t granteeUid) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700554 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700555 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100556 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
557 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700558 return result;
559 }
560
561 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400562 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700563
564 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100565 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700566 }
567
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700568 return mKeyStore->removeGrant(name8, callingUid, granteeUid) ? ResponseCode::NO_ERROR
Janis Danisevskisd3024ed2017-09-01 13:24:23 -0700569 : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700570}
571
572int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700573 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700574 uid_t targetUid = getEffectiveUid(uid);
575 if (!checkBinderPermission(P_GET, targetUid)) {
576 ALOGW("permission denied for %d: getmtime", targetUid);
577 return -1L;
578 }
579
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700580 auto filename = mKeyStore->getBlobFileNameIfExists(String8(name), targetUid, ::TYPE_ANY);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700581
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700582 if (!filename.isOk()) {
583 ALOGW("could not access %s for getmtime", filename.value().string());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700584 return -1L;
585 }
586
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700587 int fd = TEMP_FAILURE_RETRY(open(filename.value().string(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700588 if (fd < 0) {
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700589 ALOGW("could not open %s for getmtime", filename.value().string());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700590 return -1L;
591 }
592
593 struct stat s;
594 int ret = fstat(fd, &s);
595 close(fd);
596 if (ret == -1) {
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700597 ALOGW("could not stat %s for getmtime", filename.value().string());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700598 return -1L;
599 }
600
601 return static_cast<int64_t>(s.st_mtime);
602}
603
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400604// TODO(tuckeris): This is dead code, remove it. Don't bother copying over key characteristics here
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100605KeyStoreServiceReturnCode KeyStoreService::duplicate(const String16& srcKey, int32_t srcUid,
606 const String16& destKey, int32_t destUid) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700607 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700608 uid_t callingUid = IPCThreadState::self()->getCallingUid();
609 pid_t spid = IPCThreadState::self()->getCallingPid();
610 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
611 ALOGW("permission denied for %d: duplicate", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100612 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700613 }
614
615 State state = mKeyStore->getState(get_user_id(callingUid));
616 if (!isKeystoreUnlocked(state)) {
617 ALOGD("calling duplicate in state: %d", state);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100618 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700619 }
620
621 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
622 srcUid = callingUid;
623 } else if (!is_granted_to(callingUid, srcUid)) {
624 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100625 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700626 }
627
628 if (destUid == -1) {
629 destUid = callingUid;
630 }
631
632 if (srcUid != destUid) {
633 if (static_cast<uid_t>(srcUid) != callingUid) {
634 ALOGD("can only duplicate from caller to other or to same uid: "
635 "calling=%d, srcUid=%d, destUid=%d",
636 callingUid, srcUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100637 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700638 }
639
640 if (!is_granted_to(callingUid, destUid)) {
641 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100642 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700643 }
644 }
645
646 String8 source8(srcKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400647 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700648
649 String8 target8(destKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400650 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700651
652 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
653 ALOGD("destination already exists: %s", targetFile.string());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100654 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700655 }
656
657 Blob keyBlob;
658 ResponseCode responseCode =
659 mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, get_user_id(srcUid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100660 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700661 return responseCode;
662 }
663
664 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
665}
666
667int32_t KeyStoreService::is_hardware_backed(const String16& keyType) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700668 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700669 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
670}
671
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100672KeyStoreServiceReturnCode KeyStoreService::clear_uid(int64_t targetUid64) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700673 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700674 uid_t targetUid = getEffectiveUid(targetUid64);
675 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100676 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700677 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000678 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700679
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700680 mKeyStore->removeAllGrantsToUid(targetUid);
681
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700682 String8 prefix = String8::format("%u_", targetUid);
683 Vector<String16> aliases;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100684 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
685 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700686 }
687
688 for (uint32_t i = 0; i < aliases.size(); i++) {
689 String8 name8(aliases[i]);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400690 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Rubin Xu85c85e92017-04-26 20:07:30 +0100691
692 if (get_app_id(targetUid) == AID_SYSTEM) {
693 Blob keyBlob;
694 ResponseCode responseCode =
695 mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, get_user_id(targetUid));
696 if (responseCode == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
697 // Do not clear keys critical to device encryption under system uid.
698 continue;
699 }
700 }
701
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700702 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400703
704 // del() will fail silently if no cached characteristics are present for this alias.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100705 String8 chr_filename(
706 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400707 mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700708 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100709 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700710}
711
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100712KeyStoreServiceReturnCode KeyStoreService::addRngEntropy(const hidl_vec<uint8_t>& entropy) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700713 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100714 const auto& device = mKeyStore->getDevice();
715 return KS_HANDLE_HIDL_ERROR(device->addRngEntropy(entropy));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700716}
717
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100718KeyStoreServiceReturnCode KeyStoreService::generateKey(const String16& name,
719 const hidl_vec<KeyParameter>& params,
720 const hidl_vec<uint8_t>& entropy, int uid,
721 int flags,
722 KeyCharacteristics* outCharacteristics) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700723 KEYSTORE_SERVICE_LOCK;
Max Bires05fbbe52017-11-29 14:38:48 -0800724 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
725 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700726 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100727 KeyStoreServiceReturnCode rc =
728 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
729 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700730 return rc;
731 }
Rubin Xu67899de2017-04-21 19:15:13 +0100732 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
733 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
734 return ResponseCode::PERMISSION_DENIED;
735 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600736 if (containsTag(params, Tag::INCLUDE_UNIQUE_ID)) {
Max Biresfd8d0142017-12-12 11:16:43 -0800737 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Bires05fbbe52017-11-29 14:38:48 -0800738 originalUid != IPCThreadState::self()->getCallingUid()) {
739 return ResponseCode::PERMISSION_DENIED;
740 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600741 }
742
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100743 bool usingFallback = false;
744 auto& dev = mKeyStore->getDevice();
745 AuthorizationSet keyCharacteristics = params;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400746
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700747 // TODO: Seed from Linux RNG before this.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100748 rc = addRngEntropy(entropy);
749 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700750 return rc;
751 }
752
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100753 KeyStoreServiceReturnCode error;
754 auto hidl_cb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
755 const KeyCharacteristics& keyCharacteristics) {
756 error = ret;
757 if (!error.isOk()) {
758 return;
759 }
760 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700761
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100762 // Write the key
763 String8 name8(name);
764 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700765
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100766 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
767 keyBlob.setFallback(usingFallback);
Rubin Xu67899de2017-04-21 19:15:13 +0100768 keyBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
769 if (isAuthenticationBound(params) && !keyBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -0700770 keyBlob.setSuperEncrypted(true);
771 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100772 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700773
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100774 error = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
775 };
776
777 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(params, hidl_cb));
778 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400779 return rc;
780 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100781 if (!error.isOk()) {
782 ALOGE("Failed to generate key -> falling back to software keymaster");
783 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000784 auto fallback = mKeyStore->getFallbackDevice();
785 if (!fallback.isOk()) {
786 return error;
787 }
788 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->generateKey(params, hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100789 if (!rc.isOk()) {
790 return rc;
791 }
792 if (!error.isOk()) {
793 return error;
794 }
795 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400796
797 // Write the characteristics:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100798 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400799 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
800
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100801 std::stringstream kc_stream;
802 keyCharacteristics.Serialize(&kc_stream);
803 if (kc_stream.bad()) {
804 return ResponseCode::SYSTEM_ERROR;
805 }
806 auto kc_buf = kc_stream.str();
807 Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
808 ::TYPE_KEY_CHARACTERISTICS);
809 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400810 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
811
812 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700813}
814
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100815KeyStoreServiceReturnCode
816KeyStoreService::getKeyCharacteristics(const String16& name, const hidl_vec<uint8_t>& clientId,
817 const hidl_vec<uint8_t>& appData, int32_t uid,
818 KeyCharacteristics* outCharacteristics) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700819 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700820 if (!outCharacteristics) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100821 return ErrorCode::UNEXPECTED_NULL_POINTER;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700822 }
823
824 uid_t targetUid = getEffectiveUid(uid);
825 uid_t callingUid = IPCThreadState::self()->getCallingUid();
826 if (!is_granted_to(callingUid, targetUid)) {
827 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
828 targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100829 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700830 }
831
832 Blob keyBlob;
833 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700834
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100835 KeyStoreServiceReturnCode rc =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700836 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskisd714a672017-09-01 14:31:36 -0700837 if (rc == ResponseCode::UNINITIALIZED) {
838 /*
839 * If we fail reading the blob because the master key is missing we try to retrieve the
840 * key characteristics from the characteristics file. This happens when auth-bound
841 * keys are used after a screen lock has been removed by the user.
842 */
843 rc = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
844 if (!rc.isOk()) {
845 return rc;
846 }
847 AuthorizationSet keyCharacteristics;
848 // TODO write one shot stream buffer to avoid copying (twice here)
849 std::string charBuffer(reinterpret_cast<const char*>(keyBlob.getValue()),
850 keyBlob.getLength());
851 std::stringstream charStream(charBuffer);
852 keyCharacteristics.Deserialize(&charStream);
853
854 outCharacteristics->softwareEnforced = keyCharacteristics.hidl_data();
855 return rc;
856 } else if (!rc.isOk()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100857 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700858 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100859
860 auto hidlKeyBlob = blob2hidlVec(keyBlob);
861 auto& dev = mKeyStore->getDevice(keyBlob);
862
863 KeyStoreServiceReturnCode error;
864
865 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
866 error = ret;
867 if (!error.isOk()) {
868 return;
Shawn Willden98c59162016-03-20 09:10:18 -0600869 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100870 *outCharacteristics = keyCharacteristics;
871 };
872
873 rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(hidlKeyBlob, clientId, appData, hidlCb));
874 if (!rc.isOk()) {
875 return rc;
876 }
877
878 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
879 AuthorizationSet upgradeParams;
880 if (clientId.size()) {
881 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
882 }
883 if (appData.size()) {
884 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
Shawn Willden98c59162016-03-20 09:10:18 -0600885 }
886 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100887 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -0600888 return rc;
889 }
Shawn Willden715d0232016-01-21 00:45:13 -0700890
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100891 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
892
893 rc = KS_HANDLE_HIDL_ERROR(
894 dev->getKeyCharacteristics(upgradedHidlKeyBlob, clientId, appData, hidlCb));
895 if (!rc.isOk()) {
896 return rc;
897 }
898 // Note that, on success, "error" will have been updated by the hidlCB callback.
899 // So it is fine to return "error" below.
900 }
901 return error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700902}
903
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100904KeyStoreServiceReturnCode
905KeyStoreService::importKey(const String16& name, const hidl_vec<KeyParameter>& params,
906 KeyFormat format, const hidl_vec<uint8_t>& keyData, int uid, int flags,
907 KeyCharacteristics* outCharacteristics) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700908 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700909 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100910 KeyStoreServiceReturnCode rc =
911 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
912 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700913 return rc;
914 }
Rubin Xu67899de2017-04-21 19:15:13 +0100915 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
916 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
917 return ResponseCode::PERMISSION_DENIED;
918 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700919
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100920 bool usingFallback = false;
921 auto& dev = mKeyStore->getDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700922
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700923 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700924
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100925 KeyStoreServiceReturnCode error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700926
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100927 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
928 const KeyCharacteristics& keyCharacteristics) {
929 error = ret;
930 if (!error.isOk()) {
931 return;
932 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700933
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100934 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
935
936 // Write the key:
937 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
938
939 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
940 ksBlob.setFallback(usingFallback);
Rubin Xu67899de2017-04-21 19:15:13 +0100941 ksBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
942 if (isAuthenticationBound(params) && !ksBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -0700943 ksBlob.setSuperEncrypted(true);
944 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100945 ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
946
947 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
948 };
949
950 rc = KS_HANDLE_HIDL_ERROR(dev->importKey(params, format, keyData, hidlCb));
951 // possible hidl error
952 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400953 return rc;
954 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100955 // now check error from callback
956 if (!error.isOk()) {
957 ALOGE("Failed to import key -> falling back to software keymaster");
958 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000959 auto fallback = mKeyStore->getFallbackDevice();
960 if (!fallback.isOk()) {
961 return error;
962 }
963 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->importKey(params, format, keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100964 // possible hidl error
965 if (!rc.isOk()) {
966 return rc;
967 }
968 // now check error from callback
969 if (!error.isOk()) {
970 return error;
971 }
972 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400973
974 // Write the characteristics:
975 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
976
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100977 AuthorizationSet opParams = params;
978 std::stringstream kcStream;
979 opParams.Serialize(&kcStream);
980 if (kcStream.bad()) return ResponseCode::SYSTEM_ERROR;
981 auto kcBuf = kcStream.str();
982
983 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
984 ::TYPE_KEY_CHARACTERISTICS);
985 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400986 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
987
988 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700989}
990
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100991void KeyStoreService::exportKey(const String16& name, KeyFormat format,
992 const hidl_vec<uint8_t>& clientId, const hidl_vec<uint8_t>& appData,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700993 int32_t uid, ExportResult* result) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -0700994 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700995
996 uid_t targetUid = getEffectiveUid(uid);
997 uid_t callingUid = IPCThreadState::self()->getCallingUid();
998 if (!is_granted_to(callingUid, targetUid)) {
999 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001000 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001001 return;
1002 }
1003
1004 Blob keyBlob;
1005 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001006
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001007 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
1008 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001009 return;
1010 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001011
1012 auto key = blob2hidlVec(keyBlob);
1013 auto& dev = mKeyStore->getDevice(keyBlob);
1014
1015 auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
1016 result->resultCode = ret;
1017 if (!result->resultCode.isOk()) {
Ji Wang2c142312016-10-14 17:21:10 +08001018 return;
1019 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001020 result->exportData = keyMaterial;
1021 };
1022 KeyStoreServiceReturnCode rc =
1023 KS_HANDLE_HIDL_ERROR(dev->exportKey(format, key, clientId, appData, hidlCb));
1024 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
1025 // callback hidlCb.
1026 if (!rc.isOk()) {
1027 result->resultCode = rc;
Ji Wang2c142312016-10-14 17:21:10 +08001028 }
1029
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001030 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1031 AuthorizationSet upgradeParams;
1032 if (clientId.size()) {
1033 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
1034 }
1035 if (appData.size()) {
1036 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
1037 }
1038 result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
1039 if (!result->resultCode.isOk()) {
1040 return;
1041 }
1042
1043 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
1044
1045 result->resultCode = KS_HANDLE_HIDL_ERROR(
1046 dev->exportKey(format, upgradedHidlKeyBlob, clientId, appData, hidlCb));
1047 if (!result->resultCode.isOk()) {
1048 return;
1049 }
1050 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001051}
1052
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001053static inline void addAuthTokenToParams(AuthorizationSet* params, const HardwareAuthToken* token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001054 if (token) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001055 params->push_back(TAG_AUTH_TOKEN, authToken2HidlVec(*token));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001056 }
1057}
1058
1059void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, KeyPurpose purpose,
1060 bool pruneable, const hidl_vec<KeyParameter>& params,
1061 const hidl_vec<uint8_t>& entropy, int32_t uid,
1062 OperationResult* result) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -07001063 KEYSTORE_SERVICE_LOCK;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001064 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1065 uid_t targetUid = getEffectiveUid(uid);
1066 if (!is_granted_to(callingUid, targetUid)) {
1067 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001068 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001069 return;
1070 }
1071 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
1072 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001073 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001074 return;
1075 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001076 if (!checkAllowedOperationParams(params)) {
1077 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001078 return;
1079 }
1080 Blob keyBlob;
1081 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001082 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Shawn Willdend5a24e62017-02-28 13:53:24 -07001083 if (result->resultCode == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
1084 result->resultCode = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1085 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001086 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001087 return;
1088 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001089
1090 auto key = blob2hidlVec(keyBlob);
1091 auto& dev = mKeyStore->getDevice(keyBlob);
1092 AuthorizationSet opParams = params;
1093 KeyCharacteristics characteristics;
1094 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
1095
1096 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1097 result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
1098 if (!result->resultCode.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001099 return;
1100 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001101 key = blob2hidlVec(keyBlob);
1102 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
Shawn Willden98c59162016-03-20 09:10:18 -06001103 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001104 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001105 return;
1106 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001107
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001108 const HardwareAuthToken* authToken = NULL;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001109
1110 // Merge these characteristics with the ones cached when the key was generated or imported
1111 Blob charBlob;
1112 AuthorizationSet persistedCharacteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001113 result->resultCode =
1114 mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
1115 if (result->resultCode.isOk()) {
1116 // TODO write one shot stream buffer to avoid copying (twice here)
1117 std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
1118 charBlob.getLength());
1119 std::stringstream charStream(charBuffer);
1120 persistedCharacteristics.Deserialize(&charStream);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001121 } else {
1122 ALOGD("Unable to read cached characteristics for key");
1123 }
1124
1125 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001126 AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
1127 AuthorizationSet teeEnforced = characteristics.teeEnforced;
1128 persistedCharacteristics.Union(softwareEnforced);
1129 persistedCharacteristics.Subtract(teeEnforced);
1130 characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001131
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001132 auto authResult = getAuthToken(characteristics, 0, purpose, &authToken,
1133 /*failOnTokenMissing*/ false);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001134 // If per-operation auth is needed we need to begin the operation and
1135 // the client will need to authorize that operation before calling
1136 // update. Any other auth issues stop here.
Shawn Willden827243a2017-09-12 05:41:33 -06001137 if (!authResult.isOk() && authResult != ResponseCode::OP_AUTH_NEEDED) {
1138 result->resultCode = authResult;
1139 return;
1140 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001141
1142 addAuthTokenToParams(&opParams, authToken);
1143
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001144 // Add entropy to the device first.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001145 if (entropy.size()) {
1146 result->resultCode = addRngEntropy(entropy);
1147 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001148 return;
1149 }
1150 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001151
1152 // Create a keyid for this key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001153 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001154 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
1155 ALOGE("Failed to create a key ID for authorization checking.");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001156 result->resultCode = ErrorCode::UNKNOWN_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001157 return;
1158 }
1159
1160 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001161 AuthorizationSet key_auths = characteristics.teeEnforced;
1162 key_auths.append(&characteristics.softwareEnforced[0],
1163 &characteristics.softwareEnforced[characteristics.softwareEnforced.size()]);
1164
1165 result->resultCode = enforcement_policy.AuthorizeOperation(
1166 purpose, keyid, key_auths, opParams, 0 /* op_handle */, true /* is_begin_operation */);
1167 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001168 return;
1169 }
1170
Shawn Willdene2a7b522017-04-11 09:27:40 -06001171 // If there are more than kMaxOperations, abort the oldest operation that was started as
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001172 // pruneable.
Shawn Willdene2a7b522017-04-11 09:27:40 -06001173 while (mOperationMap.getOperationCount() >= kMaxOperations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001174 ALOGD("Reached or exceeded concurrent operations limit");
1175 if (!pruneOperation()) {
1176 break;
1177 }
1178 }
1179
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001180 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1181 uint64_t operationHandle) {
1182 result->resultCode = ret;
1183 if (!result->resultCode.isOk()) {
1184 return;
1185 }
1186 result->handle = operationHandle;
1187 result->outParams = outParams;
1188 };
1189
1190 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
1191 if (rc != ErrorCode::OK) {
1192 ALOGW("Got error %d from begin()", rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001193 }
1194
1195 // If there are too many operations abort the oldest operation that was
1196 // started as pruneable and try again.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001197 while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1198 ALOGW("Ran out of operation handles");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001199 if (!pruneOperation()) {
1200 break;
1201 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001202 rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001203 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001204 if (rc != ErrorCode::OK) {
1205 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001206 return;
1207 }
1208
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001209 // Note: The operation map takes possession of the contents of "characteristics".
1210 // It is safe to use characteristics after the following line but it will be empty.
1211 sp<IBinder> operationToken = mOperationMap.addOperation(
1212 result->handle, keyid, purpose, dev, appToken, std::move(characteristics), pruneable);
1213 assert(characteristics.teeEnforced.size() == 0);
1214 assert(characteristics.softwareEnforced.size() == 0);
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001215 result->token = operationToken;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001216
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001217 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001218 mOperationMap.setOperationAuthToken(operationToken, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001219 }
1220 // Return the authentication lookup result. If this is a per operation
1221 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1222 // application should get an auth token using the handle before the
1223 // first call to update, which will fail if keystore hasn't received the
1224 // auth token.
Shawn Willden2f96c792017-09-07 23:59:08 -06001225 if (result->resultCode == ErrorCode::OK) {
1226 result->resultCode = authResult;
1227 }
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001228
1229 // Other result fields were set in the begin operation's callback.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001230}
1231
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001232void KeyStoreService::update(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1233 const hidl_vec<uint8_t>& data, OperationResult* result) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -07001234 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001235 if (!checkAllowedOperationParams(params)) {
1236 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001237 return;
1238 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001239 km_device_t dev;
1240 uint64_t handle;
1241 KeyPurpose purpose;
1242 km_id_t keyid;
1243 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001244 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001245 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001246 return;
1247 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001248 AuthorizationSet opParams = params;
1249 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1250 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001251 return;
1252 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001253
1254 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001255 AuthorizationSet key_auths(characteristics->teeEnforced);
1256 key_auths.append(&characteristics->softwareEnforced[0],
1257 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001258 result->resultCode = enforcement_policy.AuthorizeOperation(
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001259 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1260 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001261 return;
1262 }
1263
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001264 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
1265 const hidl_vec<KeyParameter>& outParams, const hidl_vec<uint8_t>& output) {
1266 result->resultCode = ret;
1267 if (!result->resultCode.isOk()) {
1268 return;
1269 }
1270 result->inputConsumed = inputConsumed;
1271 result->outParams = outParams;
1272 result->data = output;
1273 };
1274
Janis Danisevskisb0245ee2017-01-25 15:43:01 +00001275 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->update(handle, opParams.hidl_data(),
1276 data, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001277 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1278 // it if there was a communication error indicated by the ErrorCode.
1279 if (!rc.isOk()) {
1280 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001281 }
1282}
1283
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001284void KeyStoreService::finish(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1285 const hidl_vec<uint8_t>& signature, const hidl_vec<uint8_t>& entropy,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001286 OperationResult* result) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -07001287 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001288 if (!checkAllowedOperationParams(params)) {
1289 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001290 return;
1291 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001292 km_device_t dev;
1293 uint64_t handle;
1294 KeyPurpose purpose;
1295 km_id_t keyid;
1296 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001297 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001298 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001299 return;
1300 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001301 AuthorizationSet opParams = params;
1302 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1303 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001304 return;
1305 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001306
1307 if (entropy.size()) {
1308 result->resultCode = addRngEntropy(entropy);
1309 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001310 return;
1311 }
1312 }
1313
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001314 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001315 AuthorizationSet key_auths(characteristics->teeEnforced);
1316 key_auths.append(&characteristics->softwareEnforced[0],
1317 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
1318 result->resultCode = enforcement_policy.AuthorizeOperation(
1319 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1320 if (!result->resultCode.isOk()) return;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001321
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001322 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1323 const hidl_vec<uint8_t>& output) {
1324 result->resultCode = ret;
1325 if (!result->resultCode.isOk()) {
1326 return;
1327 }
1328 result->outParams = outParams;
1329 result->data = output;
1330 };
1331
1332 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->finish(
1333 handle, opParams.hidl_data(),
1334 hidl_vec<uint8_t>() /* TODO(swillden): wire up input to finish() */, signature, hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001335 // Remove the operation regardless of the result
1336 mOperationMap.removeOperation(token);
1337 mAuthTokenTable.MarkCompleted(handle);
1338
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001339 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1340 // it if there was a communication error indicated by the ErrorCode.
1341 if (!rc.isOk()) {
1342 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001343 }
1344}
1345
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001346KeyStoreServiceReturnCode KeyStoreService::abort(const sp<IBinder>& token) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -07001347 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001348 km_device_t dev;
1349 uint64_t handle;
1350 KeyPurpose purpose;
1351 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001352 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001353 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001354 }
1355 mOperationMap.removeOperation(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001356
1357 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->abort(handle));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001358 mAuthTokenTable.MarkCompleted(handle);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001359 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001360}
1361
1362bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -07001363 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001364 km_device_t dev;
1365 uint64_t handle;
1366 const KeyCharacteristics* characteristics;
1367 KeyPurpose purpose;
1368 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001369 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1370 return false;
1371 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001372 const HardwareAuthToken* authToken = NULL;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001373 mOperationMap.getOperationAuthToken(token, &authToken);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001374 AuthorizationSet ignored;
1375 auto authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1376 return authResult.isOk();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001377}
1378
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001379KeyStoreServiceReturnCode KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -07001380 KEYSTORE_SERVICE_LOCK;
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001381 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1382 // receive a HardwareAuthToken, rather than an opaque byte array.
1383
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001384 if (!checkBinderPermission(P_ADD_AUTH)) {
1385 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001386 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001387 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001388 if (length != sizeof(hw_auth_token_t)) {
1389 return ErrorCode::INVALID_ARGUMENT;
1390 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001391
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001392 hw_auth_token_t authToken;
1393 memcpy(reinterpret_cast<void*>(&authToken), token, sizeof(hw_auth_token_t));
1394 if (authToken.version != 0) {
1395 return ErrorCode::INVALID_ARGUMENT;
1396 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001397
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001398 std::unique_ptr<HardwareAuthToken> hidlAuthToken(new HardwareAuthToken);
1399 hidlAuthToken->challenge = authToken.challenge;
1400 hidlAuthToken->userId = authToken.user_id;
1401 hidlAuthToken->authenticatorId = authToken.authenticator_id;
1402 hidlAuthToken->authenticatorType = authToken.authenticator_type;
1403 hidlAuthToken->timestamp = authToken.timestamp;
1404 static_assert(
1405 std::is_same<decltype(hidlAuthToken->hmac),
1406 ::android::hardware::hidl_array<uint8_t, sizeof(authToken.hmac)>>::value,
1407 "This function assumes token HMAC is 32 bytes, but it might not be.");
1408 std::copy(authToken.hmac, authToken.hmac + sizeof(authToken.hmac), hidlAuthToken->hmac.data());
1409
1410 // The table takes ownership of authToken.
1411 mAuthTokenTable.AddAuthenticationToken(hidlAuthToken.release());
1412 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001413}
1414
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001415bool isDeviceIdAttestationRequested(const hidl_vec<KeyParameter>& params) {
1416 for (size_t i = 0; i < params.size(); ++i) {
1417 switch (params[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -06001418 case Tag::ATTESTATION_ID_BRAND:
1419 case Tag::ATTESTATION_ID_DEVICE:
1420 case Tag::ATTESTATION_ID_IMEI:
1421 case Tag::ATTESTATION_ID_MANUFACTURER:
1422 case Tag::ATTESTATION_ID_MEID:
1423 case Tag::ATTESTATION_ID_MODEL:
1424 case Tag::ATTESTATION_ID_PRODUCT:
1425 case Tag::ATTESTATION_ID_SERIAL:
1426 return true;
1427 default:
1428 break;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001429 }
1430 }
1431 return false;
1432}
1433
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001434KeyStoreServiceReturnCode KeyStoreService::attestKey(const String16& name,
1435 const hidl_vec<KeyParameter>& params,
1436 hidl_vec<hidl_vec<uint8_t>>* outChain) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -07001437 KEYSTORE_SERVICE_LOCK;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001438 if (!outChain) {
1439 return ErrorCode::OUTPUT_PARAMETER_NULL;
1440 }
Shawn Willden50eb1b22016-01-21 12:41:23 -07001441
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001442 if (!checkAllowedOperationParams(params)) {
1443 return ErrorCode::INVALID_ARGUMENT;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001444 }
1445
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001446 if (isDeviceIdAttestationRequested(params)) {
1447 // There is a dedicated attestDeviceIds() method for device ID attestation.
1448 return ErrorCode::INVALID_ARGUMENT;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001449 }
1450
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001451 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1452
Shawn Willdene2a7b522017-04-11 09:27:40 -06001453 AuthorizationSet mutableParams = params;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001454 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1455 if (!rc.isOk()) {
1456 return rc;
1457 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001458
Shawn Willden50eb1b22016-01-21 12:41:23 -07001459 Blob keyBlob;
1460 String8 name8(name);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001461 rc = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
1462 if (!rc.isOk()) {
1463 return rc;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001464 }
1465
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001466 KeyStoreServiceReturnCode error;
1467 auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1468 error = ret;
1469 if (!error.isOk()) {
1470 return;
1471 }
1472 if (outChain) *outChain = certChain;
1473 };
1474
1475 auto hidlKey = blob2hidlVec(keyBlob);
1476 auto& dev = mKeyStore->getDevice(keyBlob);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001477 rc = KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
1478 if (!rc.isOk()) {
1479 return rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001480 }
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001481 return error;
1482}
1483
1484KeyStoreServiceReturnCode KeyStoreService::attestDeviceIds(const hidl_vec<KeyParameter>& params,
1485 hidl_vec<hidl_vec<uint8_t>>* outChain) {
Janis Danisevskis54fcc992019-03-25 10:26:30 -07001486 KEYSTORE_SERVICE_LOCK;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001487 if (!outChain) {
1488 return ErrorCode::OUTPUT_PARAMETER_NULL;
1489 }
1490
1491 if (!checkAllowedOperationParams(params)) {
1492 return ErrorCode::INVALID_ARGUMENT;
1493 }
1494
1495 if (!isDeviceIdAttestationRequested(params)) {
1496 // There is an attestKey() method for attesting keys without device ID attestation.
1497 return ErrorCode::INVALID_ARGUMENT;
1498 }
1499
1500 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1501 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1502 if (binder == 0) {
1503 return ErrorCode::CANNOT_ATTEST_IDS;
1504 }
1505 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1506 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1507 IPCThreadState::self()->getCallingPid(), callingUid)) {
1508 return ErrorCode::CANNOT_ATTEST_IDS;
1509 }
1510
1511 AuthorizationSet mutableParams = params;
1512 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1513 if (!rc.isOk()) {
1514 return rc;
1515 }
1516
1517 // Generate temporary key.
1518 auto& dev = mKeyStore->getDevice();
1519 KeyStoreServiceReturnCode error;
1520 hidl_vec<uint8_t> hidlKey;
1521
1522 AuthorizationSet keyCharacteristics;
1523 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1524 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1525 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1526 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1527 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
1528 auto generateHidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
1529 const KeyCharacteristics&) {
1530 error = ret;
1531 if (!error.isOk()) {
1532 return;
1533 }
1534 hidlKey = hidlKeyBlob;
1535 };
1536
1537 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(keyCharacteristics.hidl_data(), generateHidlCb));
1538 if (!rc.isOk()) {
1539 return rc;
1540 }
1541 if (!error.isOk()) {
1542 return error;
1543 }
1544
1545 // Attest key and device IDs.
1546 auto attestHidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1547 error = ret;
1548 if (!error.isOk()) {
1549 return;
1550 }
1551 *outChain = certChain;
1552 };
1553 KeyStoreServiceReturnCode attestationRc =
1554 KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), attestHidlCb));
1555
1556 // Delete temporary key.
1557 KeyStoreServiceReturnCode deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001558
1559 if (!attestationRc.isOk()) {
1560 return attestationRc;
1561 }
1562 if (!error.isOk()) {
1563 return error;
1564 }
1565 return deletionRc;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001566}
1567
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001568KeyStoreServiceReturnCode KeyStoreService::onDeviceOffBody() {
Janis Danisevskis54fcc992019-03-25 10:26:30 -07001569 KEYSTORE_SERVICE_LOCK;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001570 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1571 mAuthTokenTable.onDeviceOffBody();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001572 return ResponseCode::NO_ERROR;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001573}
1574
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001575/**
1576 * Prune the oldest pruneable operation.
1577 */
1578bool KeyStoreService::pruneOperation() {
1579 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1580 ALOGD("Trying to prune operation %p", oldest.get());
1581 size_t op_count_before_abort = mOperationMap.getOperationCount();
1582 // We mostly ignore errors from abort() because all we care about is whether at least
1583 // one operation has been removed.
1584 int abort_error = abort(oldest);
1585 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1586 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1587 return false;
1588 }
1589 return true;
1590}
1591
1592/**
1593 * Get the effective target uid for a binder operation that takes an
1594 * optional uid as the target.
1595 */
1596uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1597 if (targetUid == UID_SELF) {
1598 return IPCThreadState::self()->getCallingUid();
1599 }
1600 return static_cast<uid_t>(targetUid);
1601}
1602
1603/**
1604 * Check if the caller of the current binder method has the required
1605 * permission and if acting on other uids the grants to do so.
1606 */
1607bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1608 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1609 pid_t spid = IPCThreadState::self()->getCallingPid();
1610 if (!has_permission(callingUid, permission, spid)) {
1611 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1612 return false;
1613 }
1614 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1615 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1616 return false;
1617 }
1618 return true;
1619}
1620
1621/**
1622 * Check if the caller of the current binder method has the required
1623 * permission and the target uid is the caller or the caller is system.
1624 */
1625bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1626 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1627 pid_t spid = IPCThreadState::self()->getCallingPid();
1628 if (!has_permission(callingUid, permission, spid)) {
1629 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1630 return false;
1631 }
1632 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1633}
1634
1635/**
1636 * Check if the caller of the current binder method has the required
1637 * permission or the target of the operation is the caller's uid. This is
1638 * for operation where the permission is only for cross-uid activity and all
1639 * uids are allowed to act on their own (ie: clearing all entries for a
1640 * given uid).
1641 */
1642bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1643 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1644 if (getEffectiveUid(targetUid) == callingUid) {
1645 return true;
1646 } else {
1647 return checkBinderPermission(permission, targetUid);
1648 }
1649}
1650
1651/**
1652 * Helper method to check that the caller has the required permission as
1653 * well as the keystore is in the unlocked state if checkUnlocked is true.
1654 *
1655 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1656 * otherwise the state of keystore when not unlocked and checkUnlocked is
1657 * true.
1658 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001659KeyStoreServiceReturnCode
1660KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1661 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001662 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001663 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001664 }
1665 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1666 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001667 // All State values coincide with ResponseCodes
1668 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001669 }
1670
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001671 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001672}
1673
1674bool KeyStoreService::isKeystoreUnlocked(State state) {
1675 switch (state) {
1676 case ::STATE_NO_ERROR:
1677 return true;
1678 case ::STATE_UNINITIALIZED:
1679 case ::STATE_LOCKED:
1680 return false;
1681 }
1682 return false;
1683}
1684
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001685/**
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001686 * Check that all KeyParameter's provided by the application are
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001687 * allowed. Any parameter that keystore adds itself should be disallowed here.
1688 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001689bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1690 for (size_t i = 0; i < params.size(); ++i) {
1691 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001692 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001693 case Tag::AUTH_TOKEN:
1694 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001695 return false;
1696 default:
1697 break;
1698 }
1699 }
1700 return true;
1701}
1702
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001703ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
1704 km_device_t* dev,
1705 const AuthorizationSet& params,
1706 KeyCharacteristics* out) {
1707 hidl_vec<uint8_t> appId;
1708 hidl_vec<uint8_t> appData;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001709 for (auto param : params) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001710 if (param.tag == Tag::APPLICATION_ID) {
1711 appId = authorizationValue(TAG_APPLICATION_ID, param).value();
1712 } else if (param.tag == Tag::APPLICATION_DATA) {
1713 appData = authorizationValue(TAG_APPLICATION_DATA, param).value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001714 }
1715 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001716 ErrorCode error = ErrorCode::OK;
1717
1718 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
1719 error = ret;
1720 if (error != ErrorCode::OK) {
1721 return;
1722 }
1723 if (out) *out = keyCharacteristics;
1724 };
1725
1726 ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appData, hidlCb));
1727 if (rc != ErrorCode::OK) {
1728 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001729 }
1730 return error;
1731}
1732
1733/**
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001734 * Get the auth token for this operation from the auth token table.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001735 *
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001736 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
1737 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1738 * authorization token exists for that operation and
1739 * failOnTokenMissing is false.
1740 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1741 * token for the operation
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001742 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001743KeyStoreServiceReturnCode KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics,
1744 uint64_t handle, KeyPurpose purpose,
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001745 const HardwareAuthToken** authToken,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001746 bool failOnTokenMissing) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001747
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001748 AuthorizationSet allCharacteristics;
1749 for (size_t i = 0; i < characteristics.softwareEnforced.size(); i++) {
1750 allCharacteristics.push_back(characteristics.softwareEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001751 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001752 for (size_t i = 0; i < characteristics.teeEnforced.size(); i++) {
1753 allCharacteristics.push_back(characteristics.teeEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001754 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001755 AuthTokenTable::Error err =
1756 mAuthTokenTable.FindAuthorization(allCharacteristics, purpose, handle, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001757 switch (err) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001758 case AuthTokenTable::OK:
1759 case AuthTokenTable::AUTH_NOT_REQUIRED:
1760 return ResponseCode::NO_ERROR;
1761 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1762 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
1763 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
Rubin Xuce99f582017-10-12 10:50:11 +01001764 ALOGE("getAuthToken failed: %d", err); //STOPSHIP: debug only, to be removed
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001765 return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1766 case AuthTokenTable::OP_HANDLE_REQUIRED:
1767 return failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
1768 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001769 default:
1770 ALOGE("Unexpected FindAuthorization return value %d", err);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001771 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001772 }
1773}
1774
1775/**
1776 * Add the auth token for the operation to the param list if the operation
1777 * requires authorization. Uses the cached result in the OperationMap if available
1778 * otherwise gets the token from the AuthTokenTable and caches the result.
1779 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001780 * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001781 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1782 * authenticated.
1783 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1784 * operation token.
1785 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001786KeyStoreServiceReturnCode KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
1787 AuthorizationSet* params) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001788 const HardwareAuthToken* authToken = nullptr;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001789 mOperationMap.getOperationAuthToken(token, &authToken);
1790 if (!authToken) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001791 km_device_t dev;
1792 uint64_t handle;
1793 const KeyCharacteristics* characteristics = nullptr;
1794 KeyPurpose purpose;
1795 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001796 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001797 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001798 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001799 auto result = getAuthToken(*characteristics, handle, purpose, &authToken);
1800 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001801 return result;
1802 }
1803 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001804 mOperationMap.setOperationAuthToken(token, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001805 }
1806 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001807 addAuthTokenToParams(params, authToken);
1808 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001809}
1810
1811/**
1812 * Translate a result value to a legacy return value. All keystore errors are
1813 * preserved and keymaster errors become SYSTEM_ERRORs
1814 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001815KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001816 if (result > 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001817 return static_cast<ResponseCode>(result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001818 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001819 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001820}
1821
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001822static NullOr<const Algorithm&>
1823getKeyAlgoritmFromKeyCharacteristics(const KeyCharacteristics& characteristics) {
1824 for (size_t i = 0; i < characteristics.teeEnforced.size(); ++i) {
1825 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.teeEnforced[i]);
1826 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001827 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001828 for (size_t i = 0; i < characteristics.softwareEnforced.size(); ++i) {
1829 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.softwareEnforced[i]);
1830 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001831 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001832 return {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001833}
1834
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001835void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001836 // All legacy keys are DIGEST_NONE/PAD_NONE.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001837 params->push_back(TAG_DIGEST, Digest::NONE);
1838 params->push_back(TAG_PADDING, PaddingMode::NONE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001839
1840 // Look up the algorithm of the key.
1841 KeyCharacteristics characteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001842 auto rc = getKeyCharacteristics(name, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF,
1843 &characteristics);
1844 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001845 ALOGE("Failed to get key characteristics");
1846 return;
1847 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001848 auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
1849 if (!algorithm.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001850 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1851 return;
1852 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001853 params->push_back(TAG_ALGORITHM, algorithm.value());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001854}
1855
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001856KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
1857 const hidl_vec<uint8_t>& data,
1858 hidl_vec<uint8_t>* out,
1859 const hidl_vec<uint8_t>& signature,
1860 KeyPurpose purpose) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001861
1862 std::basic_stringstream<uint8_t> outBuffer;
1863 OperationResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001864 AuthorizationSet inArgs;
1865 addLegacyBeginParams(name, &inArgs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001866 sp<IBinder> appToken(new BBinder);
1867 sp<IBinder> token;
1868
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001869 begin(appToken, name, purpose, true, inArgs.hidl_data(), hidl_vec<uint8_t>(), UID_SELF,
1870 &result);
1871 if (!result.resultCode.isOk()) {
1872 if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001873 ALOGW("Key not found");
1874 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001875 ALOGW("Error in begin: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001876 }
1877 return translateResultToLegacyResult(result.resultCode);
1878 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001879 inArgs.Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001880 token = result.token;
1881 size_t consumed = 0;
1882 size_t lastConsumed = 0;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001883 hidl_vec<uint8_t> data_view;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001884 do {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001885 data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
1886 update(token, inArgs.hidl_data(), data_view, &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001887 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001888 ALOGW("Error in update: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001889 return translateResultToLegacyResult(result.resultCode);
1890 }
1891 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001892 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001893 }
1894 lastConsumed = result.inputConsumed;
1895 consumed += lastConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001896 } while (consumed < data.size() && lastConsumed > 0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001897
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001898 if (consumed != data.size()) {
1899 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
1900 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001901 }
1902
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001903 finish(token, inArgs.hidl_data(), signature, hidl_vec<uint8_t>(), &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001904 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001905 ALOGW("Error in finish: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001906 return translateResultToLegacyResult(result.resultCode);
1907 }
1908 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001909 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001910 }
1911
1912 if (out) {
1913 auto buf = outBuffer.str();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001914 out->resize(buf.size());
1915 memcpy(&(*out)[0], buf.data(), out->size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001916 }
1917
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001918 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001919}
1920
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001921KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
1922 const AuthorizationSet& params,
1923 Blob* blob) {
Shawn Willden98c59162016-03-20 09:10:18 -06001924 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
1925 String8 name8(name);
1926 ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001927 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willden98c59162016-03-20 09:10:18 -06001928 return responseCode;
1929 }
Rubin Xu7675c9f2017-03-15 19:26:52 +00001930 ALOGI("upgradeKeyBlob %s %d", name8.string(), uid);
Shawn Willden98c59162016-03-20 09:10:18 -06001931
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001932 auto hidlKey = blob2hidlVec(*blob);
1933 auto& dev = mKeyStore->getDevice(*blob);
Shawn Willden98c59162016-03-20 09:10:18 -06001934
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001935 KeyStoreServiceReturnCode error;
1936 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
1937 error = ret;
1938 if (!error.isOk()) {
1939 return;
1940 }
1941
Janis Danisevskisaf7783f2017-09-21 11:29:47 -07001942 auto filename = mKeyStore->getBlobFileNameIfExists(name8, uid, ::TYPE_KEYMASTER_10);
1943 if (!filename.isOk()) {
1944 ALOGI("trying to upgrade a non existing blob");
1945 return;
1946 }
1947 error = mKeyStore->del(filename.value().string(), ::TYPE_ANY, get_user_id(uid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001948 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001949 ALOGI("upgradeKeyBlob keystore->del failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001950 return;
1951 }
1952
1953 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
1954 0 /* infoLength */, ::TYPE_KEYMASTER_10);
1955 newBlob.setFallback(blob->isFallback());
1956 newBlob.setEncrypted(blob->isEncrypted());
Rubin Xu67899de2017-04-21 19:15:13 +01001957 newBlob.setSuperEncrypted(blob->isSuperEncrypted());
1958 newBlob.setCriticalToDeviceEncryption(blob->isCriticalToDeviceEncryption());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001959
Janis Danisevskisaf7783f2017-09-21 11:29:47 -07001960 error = mKeyStore->put(filename.value().string(), &newBlob, get_user_id(uid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001961 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001962 ALOGI("upgradeKeyBlob keystore->put failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001963 return;
1964 }
1965
1966 // Re-read blob for caller. We can't use newBlob because writing it modified it.
1967 error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1968 };
1969
1970 KeyStoreServiceReturnCode rc =
1971 KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
1972 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001973 return rc;
1974 }
1975
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001976 return error;
Shawn Willden98c59162016-03-20 09:10:18 -06001977}
1978
Shawn Willdene2a7b522017-04-11 09:27:40 -06001979} // namespace keystore