blob: 5f05e01874b5f2fa5b13b0540589615780cccca4 [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}
65
Shawn Willdene2a7b522017-04-11 09:27:40 -060066std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
67 struct stat sbuf;
68 if (stat(kTimestampFilePath, &sbuf) == 0) {
69 double diff_secs = difftime(time(NULL), sbuf.st_ctime);
70 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
71 }
72
73 if (errno != ENOENT) {
74 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
75 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
76 }
77
78 int fd = creat(kTimestampFilePath, 0600);
79 if (fd < 0) {
80 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
81 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
82 }
83
84 if (close(fd)) {
85 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
86 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
87 }
88
89 return {ResponseCode::NO_ERROR, true};
90}
91
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +020092constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
93
94KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
95 KeyStoreServiceReturnCode responseCode;
96 bool factoryResetSinceIdRotation;
97 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
98
99 if (!responseCode.isOk()) return responseCode;
100 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
101
102 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
103 if (!asn1_attestation_id_result.isOk()) {
104 ALOGE("failed to gather attestation_id");
105 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
106 }
107 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
108
109 /*
110 * The attestation application ID cannot be longer than
111 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, so we truncate if too long.
112 */
113 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
114 asn1_attestation_id.resize(KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE);
115 }
116
117 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
118
119 return ResponseCode::NO_ERROR;
120}
121
Shawn Willdene2a7b522017-04-11 09:27:40 -0600122} // anonymous namespace
123
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700124void KeyStoreService::binderDied(const wp<IBinder>& who) {
125 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700126 for (const auto& token : operations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700127 abort(token);
128 }
129}
130
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100131KeyStoreServiceReturnCode KeyStoreService::getState(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700132 if (!checkBinderPermission(P_GET_STATE)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100133 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700134 }
135
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100136 return ResponseCode(mKeyStore->getState(userId));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700137}
138
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100139KeyStoreServiceReturnCode KeyStoreService::get(const String16& name, int32_t uid,
140 hidl_vec<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700141 uid_t targetUid = getEffectiveUid(uid);
142 if (!checkBinderPermission(P_GET, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100143 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700144 }
145
146 String8 name8(name);
147 Blob keyBlob;
148
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100149 KeyStoreServiceReturnCode rc =
150 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
151 if (!rc.isOk()) {
152 if (item) *item = hidl_vec<uint8_t>();
153 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700154 }
155
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100156 // Do not replace this with "if (item) *item = blob2hidlVec(keyBlob)"!
157 // blob2hidlVec creates a hidl_vec<uint8_t> that references, but not owns, the data in keyBlob
158 // the subsequent assignment (*item = resultBlob) makes a deep copy, so that *item will own the
159 // corresponding resources.
160 auto resultBlob = blob2hidlVec(keyBlob);
161 if (item) {
162 *item = resultBlob;
163 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700164
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100165 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700166}
167
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100168KeyStoreServiceReturnCode KeyStoreService::insert(const String16& name,
169 const hidl_vec<uint8_t>& item, int targetUid,
170 int32_t flags) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700171 targetUid = getEffectiveUid(targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100172 auto result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700173 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100174 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700175 return result;
176 }
177
178 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400179 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_GENERIC));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700180
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100181 Blob keyBlob(&item[0], item.size(), NULL, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700182 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
183
184 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
185}
186
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100187KeyStoreServiceReturnCode KeyStoreService::del(const String16& name, int targetUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700188 targetUid = getEffectiveUid(targetUid);
189 if (!checkBinderPermission(P_DELETE, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100190 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700191 }
192 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000193 ALOGI("del %s %d", name8.string(), targetUid);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400194 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100195 ResponseCode result = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
196 if (result != ResponseCode::NO_ERROR) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400197 return result;
198 }
199
200 // Also delete any characteristics files
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100201 String8 chrFilename(
202 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400203 return mKeyStore->del(chrFilename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700204}
205
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100206KeyStoreServiceReturnCode KeyStoreService::exist(const String16& name, int targetUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700207 targetUid = getEffectiveUid(targetUid);
208 if (!checkBinderPermission(P_EXIST, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100209 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700210 }
211
212 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400213 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700214
215 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100216 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700217 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100218 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700219}
220
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100221KeyStoreServiceReturnCode KeyStoreService::list(const String16& prefix, int targetUid,
222 Vector<String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700223 targetUid = getEffectiveUid(targetUid);
224 if (!checkBinderPermission(P_LIST, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100225 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700226 }
227 const String8 prefix8(prefix);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400228 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid, TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700229
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100230 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
231 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700232 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100233 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700234}
235
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100236KeyStoreServiceReturnCode KeyStoreService::reset() {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700237 if (!checkBinderPermission(P_RESET)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100238 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700239 }
240
241 uid_t callingUid = IPCThreadState::self()->getCallingUid();
242 mKeyStore->resetUser(get_user_id(callingUid), false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100243 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700244}
245
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100246KeyStoreServiceReturnCode KeyStoreService::onUserPasswordChanged(int32_t userId,
247 const String16& password) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700248 if (!checkBinderPermission(P_PASSWORD)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100249 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700250 }
251
252 const String8 password8(password);
253 // Flush the auth token table to prevent stale tokens from sticking
254 // around.
255 mAuthTokenTable.Clear();
256
257 if (password.size() == 0) {
258 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
259 mKeyStore->resetUser(userId, true);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100260 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700261 } else {
262 switch (mKeyStore->getState(userId)) {
263 case ::STATE_UNINITIALIZED: {
264 // generate master key, encrypt with password, write to file,
265 // initialize mMasterKey*.
266 return mKeyStore->initializeUser(password8, userId);
267 }
268 case ::STATE_NO_ERROR: {
269 // rewrite master key with new password.
270 return mKeyStore->writeMasterKey(password8, userId);
271 }
272 case ::STATE_LOCKED: {
273 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
274 mKeyStore->resetUser(userId, true);
275 return mKeyStore->initializeUser(password8, userId);
276 }
277 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100278 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700279 }
280}
281
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100282KeyStoreServiceReturnCode KeyStoreService::onUserAdded(int32_t userId, int32_t parentId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700283 if (!checkBinderPermission(P_USER_CHANGED)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100284 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700285 }
286
287 // Sanity check that the new user has an empty keystore.
288 if (!mKeyStore->isEmpty(userId)) {
289 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
290 }
291 // Unconditionally clear the keystore, just to be safe.
292 mKeyStore->resetUser(userId, false);
293 if (parentId != -1) {
294 // This profile must share the same master key password as the parent profile. Because the
295 // password of the parent profile is not known here, the best we can do is copy the parent's
296 // master key and master key file. This makes this profile use the same master key as the
297 // parent profile, forever.
298 return mKeyStore->copyMasterKey(parentId, userId);
299 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100300 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700301 }
302}
303
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100304KeyStoreServiceReturnCode KeyStoreService::onUserRemoved(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700305 if (!checkBinderPermission(P_USER_CHANGED)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100306 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700307 }
308
309 mKeyStore->resetUser(userId, false);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100310 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700311}
312
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100313KeyStoreServiceReturnCode KeyStoreService::lock(int32_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700314 if (!checkBinderPermission(P_LOCK)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100315 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700316 }
317
318 State state = mKeyStore->getState(userId);
319 if (state != ::STATE_NO_ERROR) {
320 ALOGD("calling lock in state: %d", state);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100321 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700322 }
323
324 mKeyStore->lock(userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100325 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700326}
327
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100328KeyStoreServiceReturnCode KeyStoreService::unlock(int32_t userId, const String16& pw) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700329 if (!checkBinderPermission(P_UNLOCK)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100330 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700331 }
332
333 State state = mKeyStore->getState(userId);
334 if (state != ::STATE_LOCKED) {
335 switch (state) {
336 case ::STATE_NO_ERROR:
337 ALOGI("calling unlock when already unlocked, ignoring.");
338 break;
339 case ::STATE_UNINITIALIZED:
340 ALOGE("unlock called on uninitialized keystore.");
341 break;
342 default:
343 ALOGE("unlock called on keystore in unknown state: %d", state);
344 break;
345 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100346 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700347 }
348
349 const String8 password8(pw);
350 // read master key, decrypt with password, initialize mMasterKey*.
351 return mKeyStore->readMasterKey(password8, userId);
352}
353
354bool KeyStoreService::isEmpty(int32_t userId) {
355 if (!checkBinderPermission(P_IS_EMPTY)) {
356 return false;
357 }
358
359 return mKeyStore->isEmpty(userId);
360}
361
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100362KeyStoreServiceReturnCode KeyStoreService::generate(const String16& name, int32_t targetUid,
363 int32_t keyType, int32_t keySize, int32_t flags,
364 Vector<sp<KeystoreArg>>* args) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700365 targetUid = getEffectiveUid(targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100366 auto result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700367 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100368 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700369 return result;
370 }
371
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100372 keystore::AuthorizationSet params;
373 add_legacy_key_authorizations(keyType, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700374
375 switch (keyType) {
376 case EVP_PKEY_EC: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100377 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700378 if (keySize == -1) {
379 keySize = EC_DEFAULT_KEY_SIZE;
380 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
381 ALOGI("invalid key size %d", keySize);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100382 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700383 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100384 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700385 break;
386 }
387 case EVP_PKEY_RSA: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100388 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700389 if (keySize == -1) {
390 keySize = RSA_DEFAULT_KEY_SIZE;
391 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
392 ALOGI("invalid key size %d", keySize);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100393 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700394 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100395 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700396 unsigned long exponent = RSA_DEFAULT_EXPONENT;
397 if (args->size() > 1) {
398 ALOGI("invalid number of arguments: %zu", args->size());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100399 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700400 } else if (args->size() == 1) {
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700401 const sp<KeystoreArg>& expArg = args->itemAt(0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700402 if (expArg != NULL) {
403 Unique_BIGNUM pubExpBn(BN_bin2bn(
404 reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
405 if (pubExpBn.get() == NULL) {
406 ALOGI("Could not convert public exponent to BN");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100407 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700408 }
409 exponent = BN_get_word(pubExpBn.get());
410 if (exponent == 0xFFFFFFFFL) {
411 ALOGW("cannot represent public exponent as a long value");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100412 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700413 }
414 } else {
415 ALOGW("public exponent not read");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100416 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700417 }
418 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100419 params.push_back(TAG_RSA_PUBLIC_EXPONENT, exponent);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700420 break;
421 }
422 default: {
423 ALOGW("Unsupported key type %d", keyType);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100424 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700425 }
426 }
427
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100428 auto rc = generateKey(name, params.hidl_data(), hidl_vec<uint8_t>(), targetUid, flags,
429 /*outCharacteristics*/ NULL);
430 if (!rc.isOk()) {
431 ALOGW("generate failed: %d", int32_t(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700432 }
433 return translateResultToLegacyResult(rc);
434}
435
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100436KeyStoreServiceReturnCode KeyStoreService::import(const String16& name,
437 const hidl_vec<uint8_t>& data, int targetUid,
438 int32_t flags) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700439
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100440 const uint8_t* ptr = &data[0];
441
442 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, data.size()));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700443 if (!pkcs8.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100444 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700445 }
446 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
447 if (!pkey.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100448 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700449 }
450 int type = EVP_PKEY_type(pkey->type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100451 AuthorizationSet params;
452 add_legacy_key_authorizations(type, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700453 switch (type) {
454 case EVP_PKEY_RSA:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100455 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700456 break;
457 case EVP_PKEY_EC:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100458 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700459 break;
460 default:
461 ALOGW("Unsupported key type %d", type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100462 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700463 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100464
465 auto rc = importKey(name, params.hidl_data(), KeyFormat::PKCS8, data, targetUid, flags,
466 /*outCharacteristics*/ NULL);
467
468 if (!rc.isOk()) {
469 ALOGW("importKey failed: %d", int32_t(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700470 }
471 return translateResultToLegacyResult(rc);
472}
473
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100474KeyStoreServiceReturnCode KeyStoreService::sign(const String16& name, const hidl_vec<uint8_t>& data,
475 hidl_vec<uint8_t>* out) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700476 if (!checkBinderPermission(P_SIGN)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100477 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700478 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100479 return doLegacySignVerify(name, data, out, hidl_vec<uint8_t>(), KeyPurpose::SIGN);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700480}
481
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100482KeyStoreServiceReturnCode KeyStoreService::verify(const String16& name,
483 const hidl_vec<uint8_t>& data,
484 const hidl_vec<uint8_t>& signature) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700485 if (!checkBinderPermission(P_VERIFY)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100486 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700487 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100488 return doLegacySignVerify(name, data, nullptr, signature, KeyPurpose::VERIFY);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700489}
490
491/*
492 * TODO: The abstraction between things stored in hardware and regular blobs
493 * of data stored on the filesystem should be moved down to keystore itself.
494 * Unfortunately the Java code that calls this has naming conventions that it
495 * knows about. Ideally keystore shouldn't be used to store random blobs of
496 * data.
497 *
498 * Until that happens, it's necessary to have a separate "get_pubkey" and
499 * "del_key" since the Java code doesn't really communicate what it's
500 * intentions are.
501 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100502KeyStoreServiceReturnCode KeyStoreService::get_pubkey(const String16& name,
503 hidl_vec<uint8_t>* pubKey) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700504 ExportResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100505 exportKey(name, KeyFormat::X509, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF, &result);
506 if (!result.resultCode.isOk()) {
507 ALOGW("export failed: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700508 return translateResultToLegacyResult(result.resultCode);
509 }
510
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100511 if (pubKey) *pubKey = std::move(result.exportData);
512 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700513}
514
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100515KeyStoreServiceReturnCode KeyStoreService::grant(const String16& name, int32_t granteeUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700516 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100517 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
518 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700519 return result;
520 }
521
522 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400523 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700524
525 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100526 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700527 }
528
529 mKeyStore->addGrant(filename.string(), granteeUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100530 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700531}
532
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100533KeyStoreServiceReturnCode KeyStoreService::ungrant(const String16& name, int32_t granteeUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700534 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100535 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
536 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700537 return result;
538 }
539
540 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400541 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700542
543 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100544 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700545 }
546
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100547 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ResponseCode::NO_ERROR
548 : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700549}
550
551int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
552 uid_t targetUid = getEffectiveUid(uid);
553 if (!checkBinderPermission(P_GET, targetUid)) {
554 ALOGW("permission denied for %d: getmtime", targetUid);
555 return -1L;
556 }
557
558 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400559 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700560
561 if (access(filename.string(), R_OK) == -1) {
562 ALOGW("could not access %s for getmtime", filename.string());
563 return -1L;
564 }
565
566 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
567 if (fd < 0) {
568 ALOGW("could not open %s for getmtime", filename.string());
569 return -1L;
570 }
571
572 struct stat s;
573 int ret = fstat(fd, &s);
574 close(fd);
575 if (ret == -1) {
576 ALOGW("could not stat %s for getmtime", filename.string());
577 return -1L;
578 }
579
580 return static_cast<int64_t>(s.st_mtime);
581}
582
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400583// TODO(tuckeris): This is dead code, remove it. Don't bother copying over key characteristics here
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100584KeyStoreServiceReturnCode KeyStoreService::duplicate(const String16& srcKey, int32_t srcUid,
585 const String16& destKey, int32_t destUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700586 uid_t callingUid = IPCThreadState::self()->getCallingUid();
587 pid_t spid = IPCThreadState::self()->getCallingPid();
588 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
589 ALOGW("permission denied for %d: duplicate", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100590 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700591 }
592
593 State state = mKeyStore->getState(get_user_id(callingUid));
594 if (!isKeystoreUnlocked(state)) {
595 ALOGD("calling duplicate in state: %d", state);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100596 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700597 }
598
599 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
600 srcUid = callingUid;
601 } else if (!is_granted_to(callingUid, srcUid)) {
602 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100603 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700604 }
605
606 if (destUid == -1) {
607 destUid = callingUid;
608 }
609
610 if (srcUid != destUid) {
611 if (static_cast<uid_t>(srcUid) != callingUid) {
612 ALOGD("can only duplicate from caller to other or to same uid: "
613 "calling=%d, srcUid=%d, destUid=%d",
614 callingUid, srcUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100615 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700616 }
617
618 if (!is_granted_to(callingUid, destUid)) {
619 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100620 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700621 }
622 }
623
624 String8 source8(srcKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400625 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700626
627 String8 target8(destKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400628 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700629
630 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
631 ALOGD("destination already exists: %s", targetFile.string());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100632 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700633 }
634
635 Blob keyBlob;
636 ResponseCode responseCode =
637 mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, get_user_id(srcUid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100638 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700639 return responseCode;
640 }
641
642 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
643}
644
645int32_t KeyStoreService::is_hardware_backed(const String16& keyType) {
646 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
647}
648
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100649KeyStoreServiceReturnCode KeyStoreService::clear_uid(int64_t targetUid64) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700650 uid_t targetUid = getEffectiveUid(targetUid64);
651 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100652 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700653 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000654 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700655
656 String8 prefix = String8::format("%u_", targetUid);
657 Vector<String16> aliases;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100658 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
659 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700660 }
661
662 for (uint32_t i = 0; i < aliases.size(); i++) {
663 String8 name8(aliases[i]);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400664 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Rubin Xu85c85e92017-04-26 20:07:30 +0100665
666 if (get_app_id(targetUid) == AID_SYSTEM) {
667 Blob keyBlob;
668 ResponseCode responseCode =
669 mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, get_user_id(targetUid));
670 if (responseCode == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
671 // Do not clear keys critical to device encryption under system uid.
672 continue;
673 }
674 }
675
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700676 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400677
678 // del() will fail silently if no cached characteristics are present for this alias.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100679 String8 chr_filename(
680 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400681 mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700682 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100683 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700684}
685
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100686KeyStoreServiceReturnCode KeyStoreService::addRngEntropy(const hidl_vec<uint8_t>& entropy) {
687 const auto& device = mKeyStore->getDevice();
688 return KS_HANDLE_HIDL_ERROR(device->addRngEntropy(entropy));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700689}
690
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100691KeyStoreServiceReturnCode KeyStoreService::generateKey(const String16& name,
692 const hidl_vec<KeyParameter>& params,
693 const hidl_vec<uint8_t>& entropy, int uid,
694 int flags,
695 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700696 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100697 KeyStoreServiceReturnCode rc =
698 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
699 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700700 return rc;
701 }
Rubin Xu67899de2017-04-21 19:15:13 +0100702 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
703 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
704 return ResponseCode::PERMISSION_DENIED;
705 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700706
Shawn Willdene2a7b522017-04-11 09:27:40 -0600707 if (containsTag(params, Tag::INCLUDE_UNIQUE_ID)) {
708 if (!checkBinderPermission(P_GEN_UNIQUE_ID)) return ResponseCode::PERMISSION_DENIED;
709 }
710
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100711 bool usingFallback = false;
712 auto& dev = mKeyStore->getDevice();
713 AuthorizationSet keyCharacteristics = params;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400714
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700715 // TODO: Seed from Linux RNG before this.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100716 rc = addRngEntropy(entropy);
717 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700718 return rc;
719 }
720
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100721 KeyStoreServiceReturnCode error;
722 auto hidl_cb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
723 const KeyCharacteristics& keyCharacteristics) {
724 error = ret;
725 if (!error.isOk()) {
726 return;
727 }
728 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700729
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100730 // Write the key
731 String8 name8(name);
732 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700733
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100734 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
735 keyBlob.setFallback(usingFallback);
Rubin Xu67899de2017-04-21 19:15:13 +0100736 keyBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
737 if (isAuthenticationBound(params) && !keyBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -0700738 keyBlob.setSuperEncrypted(true);
739 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100740 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700741
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100742 error = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
743 };
744
745 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(params, hidl_cb));
746 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400747 return rc;
748 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100749 if (!error.isOk()) {
750 ALOGE("Failed to generate key -> falling back to software keymaster");
751 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000752 auto fallback = mKeyStore->getFallbackDevice();
753 if (!fallback.isOk()) {
754 return error;
755 }
756 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->generateKey(params, hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100757 if (!rc.isOk()) {
758 return rc;
759 }
760 if (!error.isOk()) {
761 return error;
762 }
763 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400764
765 // Write the characteristics:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100766 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400767 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
768
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100769 std::stringstream kc_stream;
770 keyCharacteristics.Serialize(&kc_stream);
771 if (kc_stream.bad()) {
772 return ResponseCode::SYSTEM_ERROR;
773 }
774 auto kc_buf = kc_stream.str();
775 Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
776 ::TYPE_KEY_CHARACTERISTICS);
777 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400778 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
779
780 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700781}
782
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100783KeyStoreServiceReturnCode
784KeyStoreService::getKeyCharacteristics(const String16& name, const hidl_vec<uint8_t>& clientId,
785 const hidl_vec<uint8_t>& appData, int32_t uid,
786 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700787 if (!outCharacteristics) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100788 return ErrorCode::UNEXPECTED_NULL_POINTER;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700789 }
790
791 uid_t targetUid = getEffectiveUid(uid);
792 uid_t callingUid = IPCThreadState::self()->getCallingUid();
793 if (!is_granted_to(callingUid, targetUid)) {
794 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
795 targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100796 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700797 }
798
799 Blob keyBlob;
800 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700801
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100802 KeyStoreServiceReturnCode rc =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700803 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100804 if (!rc.isOk()) {
805 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700806 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100807
808 auto hidlKeyBlob = blob2hidlVec(keyBlob);
809 auto& dev = mKeyStore->getDevice(keyBlob);
810
811 KeyStoreServiceReturnCode error;
812
813 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
814 error = ret;
815 if (!error.isOk()) {
816 return;
Shawn Willden98c59162016-03-20 09:10:18 -0600817 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100818 *outCharacteristics = keyCharacteristics;
819 };
820
821 rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(hidlKeyBlob, clientId, appData, hidlCb));
822 if (!rc.isOk()) {
823 return rc;
824 }
825
826 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
827 AuthorizationSet upgradeParams;
828 if (clientId.size()) {
829 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
830 }
831 if (appData.size()) {
832 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
Shawn Willden98c59162016-03-20 09:10:18 -0600833 }
834 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100835 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -0600836 return rc;
837 }
Shawn Willden715d0232016-01-21 00:45:13 -0700838
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100839 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
840
841 rc = KS_HANDLE_HIDL_ERROR(
842 dev->getKeyCharacteristics(upgradedHidlKeyBlob, clientId, appData, hidlCb));
843 if (!rc.isOk()) {
844 return rc;
845 }
846 // Note that, on success, "error" will have been updated by the hidlCB callback.
847 // So it is fine to return "error" below.
848 }
849 return error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700850}
851
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100852KeyStoreServiceReturnCode
853KeyStoreService::importKey(const String16& name, const hidl_vec<KeyParameter>& params,
854 KeyFormat format, const hidl_vec<uint8_t>& keyData, int uid, int flags,
855 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700856 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100857 KeyStoreServiceReturnCode rc =
858 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
859 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700860 return rc;
861 }
Rubin Xu67899de2017-04-21 19:15:13 +0100862 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
863 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
864 return ResponseCode::PERMISSION_DENIED;
865 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700866
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100867 bool usingFallback = false;
868 auto& dev = mKeyStore->getDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700869
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700870 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700871
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100872 KeyStoreServiceReturnCode error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700873
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100874 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
875 const KeyCharacteristics& keyCharacteristics) {
876 error = ret;
877 if (!error.isOk()) {
878 return;
879 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700880
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100881 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
882
883 // Write the key:
884 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
885
886 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
887 ksBlob.setFallback(usingFallback);
Rubin Xu67899de2017-04-21 19:15:13 +0100888 ksBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
889 if (isAuthenticationBound(params) && !ksBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -0700890 ksBlob.setSuperEncrypted(true);
891 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100892 ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
893
894 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
895 };
896
897 rc = KS_HANDLE_HIDL_ERROR(dev->importKey(params, format, keyData, hidlCb));
898 // possible hidl error
899 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400900 return rc;
901 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100902 // now check error from callback
903 if (!error.isOk()) {
904 ALOGE("Failed to import key -> falling back to software keymaster");
905 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000906 auto fallback = mKeyStore->getFallbackDevice();
907 if (!fallback.isOk()) {
908 return error;
909 }
910 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->importKey(params, format, keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100911 // possible hidl error
912 if (!rc.isOk()) {
913 return rc;
914 }
915 // now check error from callback
916 if (!error.isOk()) {
917 return error;
918 }
919 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400920
921 // Write the characteristics:
922 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
923
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100924 AuthorizationSet opParams = params;
925 std::stringstream kcStream;
926 opParams.Serialize(&kcStream);
927 if (kcStream.bad()) return ResponseCode::SYSTEM_ERROR;
928 auto kcBuf = kcStream.str();
929
930 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
931 ::TYPE_KEY_CHARACTERISTICS);
932 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400933 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
934
935 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700936}
937
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100938void KeyStoreService::exportKey(const String16& name, KeyFormat format,
939 const hidl_vec<uint8_t>& clientId, const hidl_vec<uint8_t>& appData,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700940 int32_t uid, ExportResult* result) {
941
942 uid_t targetUid = getEffectiveUid(uid);
943 uid_t callingUid = IPCThreadState::self()->getCallingUid();
944 if (!is_granted_to(callingUid, targetUid)) {
945 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100946 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700947 return;
948 }
949
950 Blob keyBlob;
951 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700952
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100953 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
954 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700955 return;
956 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100957
958 auto key = blob2hidlVec(keyBlob);
959 auto& dev = mKeyStore->getDevice(keyBlob);
960
961 auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
962 result->resultCode = ret;
963 if (!result->resultCode.isOk()) {
Ji Wang2c142312016-10-14 17:21:10 +0800964 return;
965 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100966 result->exportData = keyMaterial;
967 };
968 KeyStoreServiceReturnCode rc =
969 KS_HANDLE_HIDL_ERROR(dev->exportKey(format, key, clientId, appData, hidlCb));
970 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
971 // callback hidlCb.
972 if (!rc.isOk()) {
973 result->resultCode = rc;
Ji Wang2c142312016-10-14 17:21:10 +0800974 }
975
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100976 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
977 AuthorizationSet upgradeParams;
978 if (clientId.size()) {
979 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
980 }
981 if (appData.size()) {
982 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
983 }
984 result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
985 if (!result->resultCode.isOk()) {
986 return;
987 }
988
989 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
990
991 result->resultCode = KS_HANDLE_HIDL_ERROR(
992 dev->exportKey(format, upgradedHidlKeyBlob, clientId, appData, hidlCb));
993 if (!result->resultCode.isOk()) {
994 return;
995 }
996 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700997}
998
Shawn Willdend3ed3a22017-03-28 00:39:16 +0000999static inline void addAuthTokenToParams(AuthorizationSet* params, const HardwareAuthToken* token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001000 if (token) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001001 params->push_back(TAG_AUTH_TOKEN, authToken2HidlVec(*token));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001002 }
1003}
1004
1005void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, KeyPurpose purpose,
1006 bool pruneable, const hidl_vec<KeyParameter>& params,
1007 const hidl_vec<uint8_t>& entropy, int32_t uid,
1008 OperationResult* result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001009 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1010 uid_t targetUid = getEffectiveUid(uid);
1011 if (!is_granted_to(callingUid, targetUid)) {
1012 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001013 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001014 return;
1015 }
1016 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
1017 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001018 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001019 return;
1020 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001021 if (!checkAllowedOperationParams(params)) {
1022 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001023 return;
1024 }
1025 Blob keyBlob;
1026 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001027 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Shawn Willdend5a24e62017-02-28 13:53:24 -07001028 if (result->resultCode == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
1029 result->resultCode = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1030 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001031 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001032 return;
1033 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001034
1035 auto key = blob2hidlVec(keyBlob);
1036 auto& dev = mKeyStore->getDevice(keyBlob);
1037 AuthorizationSet opParams = params;
1038 KeyCharacteristics characteristics;
1039 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
1040
1041 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1042 result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
1043 if (!result->resultCode.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001044 return;
1045 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001046 key = blob2hidlVec(keyBlob);
1047 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
Shawn Willden98c59162016-03-20 09:10:18 -06001048 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001049 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001050 return;
1051 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001052
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001053 const HardwareAuthToken* authToken = NULL;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001054
1055 // Merge these characteristics with the ones cached when the key was generated or imported
1056 Blob charBlob;
1057 AuthorizationSet persistedCharacteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001058 result->resultCode =
1059 mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
1060 if (result->resultCode.isOk()) {
1061 // TODO write one shot stream buffer to avoid copying (twice here)
1062 std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
1063 charBlob.getLength());
1064 std::stringstream charStream(charBuffer);
1065 persistedCharacteristics.Deserialize(&charStream);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001066 } else {
1067 ALOGD("Unable to read cached characteristics for key");
1068 }
1069
1070 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001071 AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
1072 AuthorizationSet teeEnforced = characteristics.teeEnforced;
1073 persistedCharacteristics.Union(softwareEnforced);
1074 persistedCharacteristics.Subtract(teeEnforced);
1075 characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001076
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001077 result->resultCode = getAuthToken(characteristics, 0, purpose, &authToken,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001078 /*failOnTokenMissing*/ false);
1079 // If per-operation auth is needed we need to begin the operation and
1080 // the client will need to authorize that operation before calling
1081 // update. Any other auth issues stop here.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001082 if (!result->resultCode.isOk() && result->resultCode != ResponseCode::OP_AUTH_NEEDED) return;
1083
1084 addAuthTokenToParams(&opParams, authToken);
1085
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001086 // Add entropy to the device first.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001087 if (entropy.size()) {
1088 result->resultCode = addRngEntropy(entropy);
1089 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001090 return;
1091 }
1092 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001093
1094 // Create a keyid for this key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001095 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001096 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
1097 ALOGE("Failed to create a key ID for authorization checking.");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001098 result->resultCode = ErrorCode::UNKNOWN_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001099 return;
1100 }
1101
1102 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001103 AuthorizationSet key_auths = characteristics.teeEnforced;
1104 key_auths.append(&characteristics.softwareEnforced[0],
1105 &characteristics.softwareEnforced[characteristics.softwareEnforced.size()]);
1106
1107 result->resultCode = enforcement_policy.AuthorizeOperation(
1108 purpose, keyid, key_auths, opParams, 0 /* op_handle */, true /* is_begin_operation */);
1109 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001110 return;
1111 }
1112
Shawn Willdene2a7b522017-04-11 09:27:40 -06001113 // If there are more than kMaxOperations, abort the oldest operation that was started as
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001114 // pruneable.
Shawn Willdene2a7b522017-04-11 09:27:40 -06001115 while (mOperationMap.getOperationCount() >= kMaxOperations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001116 ALOGD("Reached or exceeded concurrent operations limit");
1117 if (!pruneOperation()) {
1118 break;
1119 }
1120 }
1121
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001122 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1123 uint64_t operationHandle) {
1124 result->resultCode = ret;
1125 if (!result->resultCode.isOk()) {
1126 return;
1127 }
1128 result->handle = operationHandle;
1129 result->outParams = outParams;
1130 };
1131
1132 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
1133 if (rc != ErrorCode::OK) {
1134 ALOGW("Got error %d from begin()", rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001135 }
1136
1137 // If there are too many operations abort the oldest operation that was
1138 // started as pruneable and try again.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001139 while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1140 ALOGW("Ran out of operation handles");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001141 if (!pruneOperation()) {
1142 break;
1143 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001144 rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001145 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001146 if (rc != ErrorCode::OK) {
1147 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001148 return;
1149 }
1150
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001151 // Note: The operation map takes possession of the contents of "characteristics".
1152 // It is safe to use characteristics after the following line but it will be empty.
1153 sp<IBinder> operationToken = mOperationMap.addOperation(
1154 result->handle, keyid, purpose, dev, appToken, std::move(characteristics), pruneable);
1155 assert(characteristics.teeEnforced.size() == 0);
1156 assert(characteristics.softwareEnforced.size() == 0);
1157
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001158 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001159 mOperationMap.setOperationAuthToken(operationToken, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001160 }
1161 // Return the authentication lookup result. If this is a per operation
1162 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1163 // application should get an auth token using the handle before the
1164 // first call to update, which will fail if keystore hasn't received the
1165 // auth token.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001166 // All fields but "token" were set in the begin operation's callback.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001167 result->token = operationToken;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001168}
1169
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001170void KeyStoreService::update(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1171 const hidl_vec<uint8_t>& data, OperationResult* result) {
1172 if (!checkAllowedOperationParams(params)) {
1173 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001174 return;
1175 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001176 km_device_t dev;
1177 uint64_t handle;
1178 KeyPurpose purpose;
1179 km_id_t keyid;
1180 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001181 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001182 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001183 return;
1184 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001185 AuthorizationSet opParams = params;
1186 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1187 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001188 return;
1189 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001190
1191 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001192 AuthorizationSet key_auths(characteristics->teeEnforced);
1193 key_auths.append(&characteristics->softwareEnforced[0],
1194 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001195 result->resultCode = enforcement_policy.AuthorizeOperation(
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001196 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1197 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001198 return;
1199 }
1200
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001201 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
1202 const hidl_vec<KeyParameter>& outParams, const hidl_vec<uint8_t>& output) {
1203 result->resultCode = ret;
1204 if (!result->resultCode.isOk()) {
1205 return;
1206 }
1207 result->inputConsumed = inputConsumed;
1208 result->outParams = outParams;
1209 result->data = output;
1210 };
1211
Janis Danisevskisb0245ee2017-01-25 15:43:01 +00001212 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->update(handle, opParams.hidl_data(),
1213 data, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001214 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1215 // it if there was a communication error indicated by the ErrorCode.
1216 if (!rc.isOk()) {
1217 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001218 }
1219}
1220
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001221void KeyStoreService::finish(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1222 const hidl_vec<uint8_t>& signature, const hidl_vec<uint8_t>& entropy,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001223 OperationResult* result) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001224 if (!checkAllowedOperationParams(params)) {
1225 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001226 return;
1227 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001228 km_device_t dev;
1229 uint64_t handle;
1230 KeyPurpose purpose;
1231 km_id_t keyid;
1232 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001233 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001234 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001235 return;
1236 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001237 AuthorizationSet opParams = params;
1238 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1239 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001240 return;
1241 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001242
1243 if (entropy.size()) {
1244 result->resultCode = addRngEntropy(entropy);
1245 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001246 return;
1247 }
1248 }
1249
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001250 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001251 AuthorizationSet key_auths(characteristics->teeEnforced);
1252 key_auths.append(&characteristics->softwareEnforced[0],
1253 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
1254 result->resultCode = enforcement_policy.AuthorizeOperation(
1255 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1256 if (!result->resultCode.isOk()) return;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001257
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001258 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1259 const hidl_vec<uint8_t>& output) {
1260 result->resultCode = ret;
1261 if (!result->resultCode.isOk()) {
1262 return;
1263 }
1264 result->outParams = outParams;
1265 result->data = output;
1266 };
1267
1268 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->finish(
1269 handle, opParams.hidl_data(),
1270 hidl_vec<uint8_t>() /* TODO(swillden): wire up input to finish() */, signature, hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001271 // Remove the operation regardless of the result
1272 mOperationMap.removeOperation(token);
1273 mAuthTokenTable.MarkCompleted(handle);
1274
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001275 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1276 // it if there was a communication error indicated by the ErrorCode.
1277 if (!rc.isOk()) {
1278 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001279 }
1280}
1281
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001282KeyStoreServiceReturnCode KeyStoreService::abort(const sp<IBinder>& token) {
1283 km_device_t dev;
1284 uint64_t handle;
1285 KeyPurpose purpose;
1286 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001287 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001288 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001289 }
1290 mOperationMap.removeOperation(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001291
1292 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->abort(handle));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001293 mAuthTokenTable.MarkCompleted(handle);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001294 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001295}
1296
1297bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001298 km_device_t dev;
1299 uint64_t handle;
1300 const KeyCharacteristics* characteristics;
1301 KeyPurpose purpose;
1302 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001303 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1304 return false;
1305 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001306 const HardwareAuthToken* authToken = NULL;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001307 mOperationMap.getOperationAuthToken(token, &authToken);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001308 AuthorizationSet ignored;
1309 auto authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1310 return authResult.isOk();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001311}
1312
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001313KeyStoreServiceReturnCode KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001314 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1315 // receive a HardwareAuthToken, rather than an opaque byte array.
1316
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001317 if (!checkBinderPermission(P_ADD_AUTH)) {
1318 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001319 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001320 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001321 if (length != sizeof(hw_auth_token_t)) {
1322 return ErrorCode::INVALID_ARGUMENT;
1323 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001324
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001325 hw_auth_token_t authToken;
1326 memcpy(reinterpret_cast<void*>(&authToken), token, sizeof(hw_auth_token_t));
1327 if (authToken.version != 0) {
1328 return ErrorCode::INVALID_ARGUMENT;
1329 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001330
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001331 std::unique_ptr<HardwareAuthToken> hidlAuthToken(new HardwareAuthToken);
1332 hidlAuthToken->challenge = authToken.challenge;
1333 hidlAuthToken->userId = authToken.user_id;
1334 hidlAuthToken->authenticatorId = authToken.authenticator_id;
1335 hidlAuthToken->authenticatorType = authToken.authenticator_type;
1336 hidlAuthToken->timestamp = authToken.timestamp;
1337 static_assert(
1338 std::is_same<decltype(hidlAuthToken->hmac),
1339 ::android::hardware::hidl_array<uint8_t, sizeof(authToken.hmac)>>::value,
1340 "This function assumes token HMAC is 32 bytes, but it might not be.");
1341 std::copy(authToken.hmac, authToken.hmac + sizeof(authToken.hmac), hidlAuthToken->hmac.data());
1342
1343 // The table takes ownership of authToken.
1344 mAuthTokenTable.AddAuthenticationToken(hidlAuthToken.release());
1345 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001346}
1347
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001348bool isDeviceIdAttestationRequested(const hidl_vec<KeyParameter>& params) {
1349 for (size_t i = 0; i < params.size(); ++i) {
1350 switch (params[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -06001351 case Tag::ATTESTATION_ID_BRAND:
1352 case Tag::ATTESTATION_ID_DEVICE:
1353 case Tag::ATTESTATION_ID_IMEI:
1354 case Tag::ATTESTATION_ID_MANUFACTURER:
1355 case Tag::ATTESTATION_ID_MEID:
1356 case Tag::ATTESTATION_ID_MODEL:
1357 case Tag::ATTESTATION_ID_PRODUCT:
1358 case Tag::ATTESTATION_ID_SERIAL:
1359 return true;
1360 default:
1361 break;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001362 }
1363 }
1364 return false;
1365}
1366
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001367KeyStoreServiceReturnCode KeyStoreService::attestKey(const String16& name,
1368 const hidl_vec<KeyParameter>& params,
1369 hidl_vec<hidl_vec<uint8_t>>* outChain) {
1370 if (!outChain) {
1371 return ErrorCode::OUTPUT_PARAMETER_NULL;
1372 }
Shawn Willden50eb1b22016-01-21 12:41:23 -07001373
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001374 if (!checkAllowedOperationParams(params)) {
1375 return ErrorCode::INVALID_ARGUMENT;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001376 }
1377
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001378 if (isDeviceIdAttestationRequested(params)) {
1379 // There is a dedicated attestDeviceIds() method for device ID attestation.
1380 return ErrorCode::INVALID_ARGUMENT;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001381 }
1382
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001383 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1384
Shawn Willdene2a7b522017-04-11 09:27:40 -06001385 AuthorizationSet mutableParams = params;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001386 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1387 if (!rc.isOk()) {
1388 return rc;
1389 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001390
Shawn Willden50eb1b22016-01-21 12:41:23 -07001391 Blob keyBlob;
1392 String8 name8(name);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001393 rc = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
1394 if (!rc.isOk()) {
1395 return rc;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001396 }
1397
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001398 KeyStoreServiceReturnCode error;
1399 auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1400 error = ret;
1401 if (!error.isOk()) {
1402 return;
1403 }
1404 if (outChain) *outChain = certChain;
1405 };
1406
1407 auto hidlKey = blob2hidlVec(keyBlob);
1408 auto& dev = mKeyStore->getDevice(keyBlob);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001409 rc = KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
1410 if (!rc.isOk()) {
1411 return rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001412 }
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001413 return error;
1414}
1415
1416KeyStoreServiceReturnCode KeyStoreService::attestDeviceIds(const hidl_vec<KeyParameter>& params,
1417 hidl_vec<hidl_vec<uint8_t>>* outChain) {
1418 if (!outChain) {
1419 return ErrorCode::OUTPUT_PARAMETER_NULL;
1420 }
1421
1422 if (!checkAllowedOperationParams(params)) {
1423 return ErrorCode::INVALID_ARGUMENT;
1424 }
1425
1426 if (!isDeviceIdAttestationRequested(params)) {
1427 // There is an attestKey() method for attesting keys without device ID attestation.
1428 return ErrorCode::INVALID_ARGUMENT;
1429 }
1430
1431 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1432 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1433 if (binder == 0) {
1434 return ErrorCode::CANNOT_ATTEST_IDS;
1435 }
1436 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1437 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1438 IPCThreadState::self()->getCallingPid(), callingUid)) {
1439 return ErrorCode::CANNOT_ATTEST_IDS;
1440 }
1441
1442 AuthorizationSet mutableParams = params;
1443 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1444 if (!rc.isOk()) {
1445 return rc;
1446 }
1447
1448 // Generate temporary key.
1449 auto& dev = mKeyStore->getDevice();
1450 KeyStoreServiceReturnCode error;
1451 hidl_vec<uint8_t> hidlKey;
1452
1453 AuthorizationSet keyCharacteristics;
1454 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1455 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1456 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1457 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1458 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
1459 auto generateHidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
1460 const KeyCharacteristics&) {
1461 error = ret;
1462 if (!error.isOk()) {
1463 return;
1464 }
1465 hidlKey = hidlKeyBlob;
1466 };
1467
1468 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(keyCharacteristics.hidl_data(), generateHidlCb));
1469 if (!rc.isOk()) {
1470 return rc;
1471 }
1472 if (!error.isOk()) {
1473 return error;
1474 }
1475
1476 // Attest key and device IDs.
1477 auto attestHidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1478 error = ret;
1479 if (!error.isOk()) {
1480 return;
1481 }
1482 *outChain = certChain;
1483 };
1484 KeyStoreServiceReturnCode attestationRc =
1485 KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), attestHidlCb));
1486
1487 // Delete temporary key.
1488 KeyStoreServiceReturnCode deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001489
1490 if (!attestationRc.isOk()) {
1491 return attestationRc;
1492 }
1493 if (!error.isOk()) {
1494 return error;
1495 }
1496 return deletionRc;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001497}
1498
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001499KeyStoreServiceReturnCode KeyStoreService::onDeviceOffBody() {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001500 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1501 mAuthTokenTable.onDeviceOffBody();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001502 return ResponseCode::NO_ERROR;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001503}
1504
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001505/**
1506 * Prune the oldest pruneable operation.
1507 */
1508bool KeyStoreService::pruneOperation() {
1509 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1510 ALOGD("Trying to prune operation %p", oldest.get());
1511 size_t op_count_before_abort = mOperationMap.getOperationCount();
1512 // We mostly ignore errors from abort() because all we care about is whether at least
1513 // one operation has been removed.
1514 int abort_error = abort(oldest);
1515 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1516 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1517 return false;
1518 }
1519 return true;
1520}
1521
1522/**
1523 * Get the effective target uid for a binder operation that takes an
1524 * optional uid as the target.
1525 */
1526uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1527 if (targetUid == UID_SELF) {
1528 return IPCThreadState::self()->getCallingUid();
1529 }
1530 return static_cast<uid_t>(targetUid);
1531}
1532
1533/**
1534 * Check if the caller of the current binder method has the required
1535 * permission and if acting on other uids the grants to do so.
1536 */
1537bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1538 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1539 pid_t spid = IPCThreadState::self()->getCallingPid();
1540 if (!has_permission(callingUid, permission, spid)) {
1541 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1542 return false;
1543 }
1544 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1545 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1546 return false;
1547 }
1548 return true;
1549}
1550
1551/**
1552 * Check if the caller of the current binder method has the required
1553 * permission and the target uid is the caller or the caller is system.
1554 */
1555bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1556 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1557 pid_t spid = IPCThreadState::self()->getCallingPid();
1558 if (!has_permission(callingUid, permission, spid)) {
1559 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1560 return false;
1561 }
1562 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1563}
1564
1565/**
1566 * Check if the caller of the current binder method has the required
1567 * permission or the target of the operation is the caller's uid. This is
1568 * for operation where the permission is only for cross-uid activity and all
1569 * uids are allowed to act on their own (ie: clearing all entries for a
1570 * given uid).
1571 */
1572bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1573 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1574 if (getEffectiveUid(targetUid) == callingUid) {
1575 return true;
1576 } else {
1577 return checkBinderPermission(permission, targetUid);
1578 }
1579}
1580
1581/**
1582 * Helper method to check that the caller has the required permission as
1583 * well as the keystore is in the unlocked state if checkUnlocked is true.
1584 *
1585 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1586 * otherwise the state of keystore when not unlocked and checkUnlocked is
1587 * true.
1588 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001589KeyStoreServiceReturnCode
1590KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1591 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001592 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001593 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001594 }
1595 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1596 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001597 // All State values coincide with ResponseCodes
1598 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001599 }
1600
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001601 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001602}
1603
1604bool KeyStoreService::isKeystoreUnlocked(State state) {
1605 switch (state) {
1606 case ::STATE_NO_ERROR:
1607 return true;
1608 case ::STATE_UNINITIALIZED:
1609 case ::STATE_LOCKED:
1610 return false;
1611 }
1612 return false;
1613}
1614
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001615/**
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001616 * Check that all KeyParameter's provided by the application are
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001617 * allowed. Any parameter that keystore adds itself should be disallowed here.
1618 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001619bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1620 for (size_t i = 0; i < params.size(); ++i) {
1621 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001622 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001623 case Tag::AUTH_TOKEN:
1624 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001625 return false;
1626 default:
1627 break;
1628 }
1629 }
1630 return true;
1631}
1632
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001633ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
1634 km_device_t* dev,
1635 const AuthorizationSet& params,
1636 KeyCharacteristics* out) {
1637 hidl_vec<uint8_t> appId;
1638 hidl_vec<uint8_t> appData;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001639 for (auto param : params) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001640 if (param.tag == Tag::APPLICATION_ID) {
1641 appId = authorizationValue(TAG_APPLICATION_ID, param).value();
1642 } else if (param.tag == Tag::APPLICATION_DATA) {
1643 appData = authorizationValue(TAG_APPLICATION_DATA, param).value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001644 }
1645 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001646 ErrorCode error = ErrorCode::OK;
1647
1648 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
1649 error = ret;
1650 if (error != ErrorCode::OK) {
1651 return;
1652 }
1653 if (out) *out = keyCharacteristics;
1654 };
1655
1656 ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appData, hidlCb));
1657 if (rc != ErrorCode::OK) {
1658 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001659 }
1660 return error;
1661}
1662
1663/**
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001664 * Get the auth token for this operation from the auth token table.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001665 *
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001666 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
1667 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1668 * authorization token exists for that operation and
1669 * failOnTokenMissing is false.
1670 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1671 * token for the operation
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001672 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001673KeyStoreServiceReturnCode KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics,
1674 uint64_t handle, KeyPurpose purpose,
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001675 const HardwareAuthToken** authToken,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001676 bool failOnTokenMissing) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001677
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001678 AuthorizationSet allCharacteristics;
1679 for (size_t i = 0; i < characteristics.softwareEnforced.size(); i++) {
1680 allCharacteristics.push_back(characteristics.softwareEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001681 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001682 for (size_t i = 0; i < characteristics.teeEnforced.size(); i++) {
1683 allCharacteristics.push_back(characteristics.teeEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001684 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001685 AuthTokenTable::Error err =
1686 mAuthTokenTable.FindAuthorization(allCharacteristics, purpose, handle, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001687 switch (err) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001688 case AuthTokenTable::OK:
1689 case AuthTokenTable::AUTH_NOT_REQUIRED:
1690 return ResponseCode::NO_ERROR;
1691 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1692 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
1693 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
1694 return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1695 case AuthTokenTable::OP_HANDLE_REQUIRED:
1696 return failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
1697 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001698 default:
1699 ALOGE("Unexpected FindAuthorization return value %d", err);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001700 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001701 }
1702}
1703
1704/**
1705 * Add the auth token for the operation to the param list if the operation
1706 * requires authorization. Uses the cached result in the OperationMap if available
1707 * otherwise gets the token from the AuthTokenTable and caches the result.
1708 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001709 * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001710 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1711 * authenticated.
1712 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1713 * operation token.
1714 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001715KeyStoreServiceReturnCode KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
1716 AuthorizationSet* params) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001717 const HardwareAuthToken* authToken = nullptr;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001718 mOperationMap.getOperationAuthToken(token, &authToken);
1719 if (!authToken) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001720 km_device_t dev;
1721 uint64_t handle;
1722 const KeyCharacteristics* characteristics = nullptr;
1723 KeyPurpose purpose;
1724 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001725 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001726 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001727 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001728 auto result = getAuthToken(*characteristics, handle, purpose, &authToken);
1729 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001730 return result;
1731 }
1732 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001733 mOperationMap.setOperationAuthToken(token, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001734 }
1735 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001736 addAuthTokenToParams(params, authToken);
1737 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001738}
1739
1740/**
1741 * Translate a result value to a legacy return value. All keystore errors are
1742 * preserved and keymaster errors become SYSTEM_ERRORs
1743 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001744KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001745 if (result > 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001746 return static_cast<ResponseCode>(result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001747 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001748 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001749}
1750
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001751static NullOr<const Algorithm&>
1752getKeyAlgoritmFromKeyCharacteristics(const KeyCharacteristics& characteristics) {
1753 for (size_t i = 0; i < characteristics.teeEnforced.size(); ++i) {
1754 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.teeEnforced[i]);
1755 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001756 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001757 for (size_t i = 0; i < characteristics.softwareEnforced.size(); ++i) {
1758 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.softwareEnforced[i]);
1759 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001760 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001761 return {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001762}
1763
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001764void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001765 // All legacy keys are DIGEST_NONE/PAD_NONE.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001766 params->push_back(TAG_DIGEST, Digest::NONE);
1767 params->push_back(TAG_PADDING, PaddingMode::NONE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001768
1769 // Look up the algorithm of the key.
1770 KeyCharacteristics characteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001771 auto rc = getKeyCharacteristics(name, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF,
1772 &characteristics);
1773 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001774 ALOGE("Failed to get key characteristics");
1775 return;
1776 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001777 auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
1778 if (!algorithm.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001779 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1780 return;
1781 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001782 params->push_back(TAG_ALGORITHM, algorithm.value());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001783}
1784
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001785KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
1786 const hidl_vec<uint8_t>& data,
1787 hidl_vec<uint8_t>* out,
1788 const hidl_vec<uint8_t>& signature,
1789 KeyPurpose purpose) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001790
1791 std::basic_stringstream<uint8_t> outBuffer;
1792 OperationResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001793 AuthorizationSet inArgs;
1794 addLegacyBeginParams(name, &inArgs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001795 sp<IBinder> appToken(new BBinder);
1796 sp<IBinder> token;
1797
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001798 begin(appToken, name, purpose, true, inArgs.hidl_data(), hidl_vec<uint8_t>(), UID_SELF,
1799 &result);
1800 if (!result.resultCode.isOk()) {
1801 if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001802 ALOGW("Key not found");
1803 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001804 ALOGW("Error in begin: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001805 }
1806 return translateResultToLegacyResult(result.resultCode);
1807 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001808 inArgs.Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001809 token = result.token;
1810 size_t consumed = 0;
1811 size_t lastConsumed = 0;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001812 hidl_vec<uint8_t> data_view;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001813 do {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001814 data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
1815 update(token, inArgs.hidl_data(), data_view, &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001816 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001817 ALOGW("Error in update: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001818 return translateResultToLegacyResult(result.resultCode);
1819 }
1820 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001821 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001822 }
1823 lastConsumed = result.inputConsumed;
1824 consumed += lastConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001825 } while (consumed < data.size() && lastConsumed > 0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001826
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001827 if (consumed != data.size()) {
1828 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
1829 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001830 }
1831
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001832 finish(token, inArgs.hidl_data(), signature, hidl_vec<uint8_t>(), &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001833 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001834 ALOGW("Error in finish: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001835 return translateResultToLegacyResult(result.resultCode);
1836 }
1837 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001838 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001839 }
1840
1841 if (out) {
1842 auto buf = outBuffer.str();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001843 out->resize(buf.size());
1844 memcpy(&(*out)[0], buf.data(), out->size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001845 }
1846
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001847 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001848}
1849
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001850KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
1851 const AuthorizationSet& params,
1852 Blob* blob) {
Shawn Willden98c59162016-03-20 09:10:18 -06001853 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
1854 String8 name8(name);
1855 ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001856 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willden98c59162016-03-20 09:10:18 -06001857 return responseCode;
1858 }
Rubin Xu7675c9f2017-03-15 19:26:52 +00001859 ALOGI("upgradeKeyBlob %s %d", name8.string(), uid);
Shawn Willden98c59162016-03-20 09:10:18 -06001860
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001861 auto hidlKey = blob2hidlVec(*blob);
1862 auto& dev = mKeyStore->getDevice(*blob);
Shawn Willden98c59162016-03-20 09:10:18 -06001863
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001864 KeyStoreServiceReturnCode error;
1865 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
1866 error = ret;
1867 if (!error.isOk()) {
1868 return;
1869 }
1870
1871 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1872 error = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(uid));
1873 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001874 ALOGI("upgradeKeyBlob keystore->del failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001875 return;
1876 }
1877
1878 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
1879 0 /* infoLength */, ::TYPE_KEYMASTER_10);
1880 newBlob.setFallback(blob->isFallback());
1881 newBlob.setEncrypted(blob->isEncrypted());
Rubin Xu67899de2017-04-21 19:15:13 +01001882 newBlob.setSuperEncrypted(blob->isSuperEncrypted());
1883 newBlob.setCriticalToDeviceEncryption(blob->isCriticalToDeviceEncryption());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001884
1885 error = mKeyStore->put(filename.string(), &newBlob, get_user_id(uid));
1886 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001887 ALOGI("upgradeKeyBlob keystore->put failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001888 return;
1889 }
1890
1891 // Re-read blob for caller. We can't use newBlob because writing it modified it.
1892 error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1893 };
1894
1895 KeyStoreServiceReturnCode rc =
1896 KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
1897 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001898 return rc;
1899 }
1900
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001901 return error;
Shawn Willden98c59162016-03-20 09:10:18 -06001902}
1903
Shawn Willdene2a7b522017-04-11 09:27:40 -06001904} // namespace keystore