blob: f6786b880bc80bf9bfbca6447215f470ccb30e83 [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);
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700194 auto filename = mKeyStore->getBlobFileNameIfExists(name8, targetUid, ::TYPE_ANY);
195 if (!filename.isOk()) return ResponseCode::KEY_NOT_FOUND;
196
197 ResponseCode result = mKeyStore->del(filename.value().string(), ::TYPE_ANY,
198 get_user_id(targetUid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100199 if (result != ResponseCode::NO_ERROR) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400200 return result;
201 }
202
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700203 filename = mKeyStore->getBlobFileNameIfExists(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS);
204 if (filename.isOk()) {
205 return mKeyStore->del(filename.value().string(), ::TYPE_KEY_CHARACTERISTICS,
206 get_user_id(targetUid));
207 }
208 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700209}
210
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100211KeyStoreServiceReturnCode KeyStoreService::exist(const String16& name, int targetUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700212 targetUid = getEffectiveUid(targetUid);
213 if (!checkBinderPermission(P_EXIST, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100214 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700215 }
216
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700217 auto filename = mKeyStore->getBlobFileNameIfExists(String8(name), targetUid, ::TYPE_ANY);
218 return filename.isOk() ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND;
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 Danisevskis6d449e82017-06-07 18:03:31 -0700515String16 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()) {
Janis Danisevskis6d449e82017-06-07 18:03:31 -0700519 return String16();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700520 }
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 Danisevskis6d449e82017-06-07 18:03:31 -0700526 return String16();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700527 }
528
Janis Danisevskis3f303642017-09-20 16:30:19 -0700529 return String16(mKeyStore->addGrant(String8(name).string(), callingUid, granteeUid).c_str());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700530}
531
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100532KeyStoreServiceReturnCode KeyStoreService::ungrant(const String16& name, int32_t granteeUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700533 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100534 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
535 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700536 return result;
537 }
538
539 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400540 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700541
542 if (access(filename.string(), R_OK) == -1) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100543 return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700544 }
545
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700546 return mKeyStore->removeGrant(name8, callingUid, granteeUid) ? ResponseCode::NO_ERROR
Janis Danisevskisd3024ed2017-09-01 13:24:23 -0700547 : ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700548}
549
550int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
551 uid_t targetUid = getEffectiveUid(uid);
552 if (!checkBinderPermission(P_GET, targetUid)) {
553 ALOGW("permission denied for %d: getmtime", targetUid);
554 return -1L;
555 }
556
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700557 auto filename = mKeyStore->getBlobFileNameIfExists(String8(name), targetUid, ::TYPE_ANY);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700558
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700559 if (!filename.isOk()) {
560 ALOGW("could not access %s for getmtime", filename.value().string());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700561 return -1L;
562 }
563
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700564 int fd = TEMP_FAILURE_RETRY(open(filename.value().string(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700565 if (fd < 0) {
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700566 ALOGW("could not open %s for getmtime", filename.value().string());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700567 return -1L;
568 }
569
570 struct stat s;
571 int ret = fstat(fd, &s);
572 close(fd);
573 if (ret == -1) {
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700574 ALOGW("could not stat %s for getmtime", filename.value().string());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700575 return -1L;
576 }
577
578 return static_cast<int64_t>(s.st_mtime);
579}
580
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400581// TODO(tuckeris): This is dead code, remove it. Don't bother copying over key characteristics here
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100582KeyStoreServiceReturnCode KeyStoreService::duplicate(const String16& srcKey, int32_t srcUid,
583 const String16& destKey, int32_t destUid) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700584 uid_t callingUid = IPCThreadState::self()->getCallingUid();
585 pid_t spid = IPCThreadState::self()->getCallingPid();
586 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
587 ALOGW("permission denied for %d: duplicate", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100588 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700589 }
590
591 State state = mKeyStore->getState(get_user_id(callingUid));
592 if (!isKeystoreUnlocked(state)) {
593 ALOGD("calling duplicate in state: %d", state);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100594 return ResponseCode(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700595 }
596
597 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
598 srcUid = callingUid;
599 } else if (!is_granted_to(callingUid, srcUid)) {
600 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100601 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700602 }
603
604 if (destUid == -1) {
605 destUid = callingUid;
606 }
607
608 if (srcUid != destUid) {
609 if (static_cast<uid_t>(srcUid) != callingUid) {
610 ALOGD("can only duplicate from caller to other or to same uid: "
611 "calling=%d, srcUid=%d, destUid=%d",
612 callingUid, srcUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100613 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700614 }
615
616 if (!is_granted_to(callingUid, destUid)) {
617 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100618 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700619 }
620 }
621
622 String8 source8(srcKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400623 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700624
625 String8 target8(destKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400626 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700627
628 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
629 ALOGD("destination already exists: %s", targetFile.string());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100630 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700631 }
632
633 Blob keyBlob;
634 ResponseCode responseCode =
635 mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, get_user_id(srcUid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100636 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700637 return responseCode;
638 }
639
640 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
641}
642
643int32_t KeyStoreService::is_hardware_backed(const String16& keyType) {
644 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
645}
646
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100647KeyStoreServiceReturnCode KeyStoreService::clear_uid(int64_t targetUid64) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700648 uid_t targetUid = getEffectiveUid(targetUid64);
649 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100650 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700651 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000652 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700653
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700654 mKeyStore->removeAllGrantsToUid(targetUid);
655
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700656 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) {
Max Bires05fbbe52017-11-29 14:38:48 -0800696 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
697 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700698 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100699 KeyStoreServiceReturnCode rc =
700 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
701 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700702 return rc;
703 }
Rubin Xu67899de2017-04-21 19:15:13 +0100704 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
705 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
706 return ResponseCode::PERMISSION_DENIED;
707 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600708 if (containsTag(params, Tag::INCLUDE_UNIQUE_ID)) {
Max Biresfd8d0142017-12-12 11:16:43 -0800709 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Bires05fbbe52017-11-29 14:38:48 -0800710 originalUid != IPCThreadState::self()->getCallingUid()) {
711 return ResponseCode::PERMISSION_DENIED;
712 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600713 }
714
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100715 bool usingFallback = false;
716 auto& dev = mKeyStore->getDevice();
717 AuthorizationSet keyCharacteristics = params;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400718
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700719 // TODO: Seed from Linux RNG before this.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100720 rc = addRngEntropy(entropy);
721 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700722 return rc;
723 }
724
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100725 KeyStoreServiceReturnCode error;
726 auto hidl_cb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
727 const KeyCharacteristics& keyCharacteristics) {
728 error = ret;
729 if (!error.isOk()) {
730 return;
731 }
732 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700733
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100734 // Write the key
735 String8 name8(name);
736 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700737
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100738 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
739 keyBlob.setFallback(usingFallback);
Rubin Xu67899de2017-04-21 19:15:13 +0100740 keyBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
741 if (isAuthenticationBound(params) && !keyBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -0700742 keyBlob.setSuperEncrypted(true);
743 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100744 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700745
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100746 error = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
747 };
748
749 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(params, hidl_cb));
750 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400751 return rc;
752 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100753 if (!error.isOk()) {
754 ALOGE("Failed to generate key -> falling back to software keymaster");
755 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000756 auto fallback = mKeyStore->getFallbackDevice();
757 if (!fallback.isOk()) {
758 return error;
759 }
760 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->generateKey(params, hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100761 if (!rc.isOk()) {
762 return rc;
763 }
764 if (!error.isOk()) {
765 return error;
766 }
767 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400768
769 // Write the characteristics:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100770 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400771 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
772
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100773 std::stringstream kc_stream;
774 keyCharacteristics.Serialize(&kc_stream);
775 if (kc_stream.bad()) {
776 return ResponseCode::SYSTEM_ERROR;
777 }
778 auto kc_buf = kc_stream.str();
779 Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
780 ::TYPE_KEY_CHARACTERISTICS);
781 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400782 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
783
784 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700785}
786
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100787KeyStoreServiceReturnCode
788KeyStoreService::getKeyCharacteristics(const String16& name, const hidl_vec<uint8_t>& clientId,
789 const hidl_vec<uint8_t>& appData, int32_t uid,
790 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700791 if (!outCharacteristics) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100792 return ErrorCode::UNEXPECTED_NULL_POINTER;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700793 }
794
795 uid_t targetUid = getEffectiveUid(uid);
796 uid_t callingUid = IPCThreadState::self()->getCallingUid();
797 if (!is_granted_to(callingUid, targetUid)) {
798 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
799 targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100800 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700801 }
802
803 Blob keyBlob;
804 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700805
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100806 KeyStoreServiceReturnCode rc =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700807 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskisd714a672017-09-01 14:31:36 -0700808 if (rc == ResponseCode::UNINITIALIZED) {
809 /*
810 * If we fail reading the blob because the master key is missing we try to retrieve the
811 * key characteristics from the characteristics file. This happens when auth-bound
812 * keys are used after a screen lock has been removed by the user.
813 */
814 rc = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
815 if (!rc.isOk()) {
816 return rc;
817 }
818 AuthorizationSet keyCharacteristics;
819 // TODO write one shot stream buffer to avoid copying (twice here)
820 std::string charBuffer(reinterpret_cast<const char*>(keyBlob.getValue()),
821 keyBlob.getLength());
822 std::stringstream charStream(charBuffer);
823 keyCharacteristics.Deserialize(&charStream);
824
825 outCharacteristics->softwareEnforced = keyCharacteristics.hidl_data();
826 return rc;
827 } else if (!rc.isOk()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100828 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700829 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100830
831 auto hidlKeyBlob = blob2hidlVec(keyBlob);
832 auto& dev = mKeyStore->getDevice(keyBlob);
833
834 KeyStoreServiceReturnCode error;
835
836 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
837 error = ret;
838 if (!error.isOk()) {
839 return;
Shawn Willden98c59162016-03-20 09:10:18 -0600840 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100841 *outCharacteristics = keyCharacteristics;
842 };
843
844 rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(hidlKeyBlob, clientId, appData, hidlCb));
845 if (!rc.isOk()) {
846 return rc;
847 }
848
849 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
850 AuthorizationSet upgradeParams;
851 if (clientId.size()) {
852 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
853 }
854 if (appData.size()) {
855 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
Shawn Willden98c59162016-03-20 09:10:18 -0600856 }
857 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100858 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -0600859 return rc;
860 }
Shawn Willden715d0232016-01-21 00:45:13 -0700861
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100862 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
863
864 rc = KS_HANDLE_HIDL_ERROR(
865 dev->getKeyCharacteristics(upgradedHidlKeyBlob, clientId, appData, hidlCb));
866 if (!rc.isOk()) {
867 return rc;
868 }
869 // Note that, on success, "error" will have been updated by the hidlCB callback.
870 // So it is fine to return "error" below.
871 }
872 return error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700873}
874
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100875KeyStoreServiceReturnCode
876KeyStoreService::importKey(const String16& name, const hidl_vec<KeyParameter>& params,
877 KeyFormat format, const hidl_vec<uint8_t>& keyData, int uid, int flags,
878 KeyCharacteristics* outCharacteristics) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700879 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100880 KeyStoreServiceReturnCode rc =
881 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
882 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700883 return rc;
884 }
Rubin Xu67899de2017-04-21 19:15:13 +0100885 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
886 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
887 return ResponseCode::PERMISSION_DENIED;
888 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700889
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100890 bool usingFallback = false;
891 auto& dev = mKeyStore->getDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700892
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700893 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700894
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100895 KeyStoreServiceReturnCode error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700896
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100897 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
898 const KeyCharacteristics& keyCharacteristics) {
899 error = ret;
900 if (!error.isOk()) {
901 return;
902 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700903
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100904 if (outCharacteristics) *outCharacteristics = keyCharacteristics;
905
906 // Write the key:
907 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
908
909 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
910 ksBlob.setFallback(usingFallback);
Rubin Xu67899de2017-04-21 19:15:13 +0100911 ksBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
912 if (isAuthenticationBound(params) && !ksBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -0700913 ksBlob.setSuperEncrypted(true);
914 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100915 ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
916
917 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
918 };
919
920 rc = KS_HANDLE_HIDL_ERROR(dev->importKey(params, format, keyData, hidlCb));
921 // possible hidl error
922 if (!rc.isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400923 return rc;
924 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100925 // now check error from callback
926 if (!error.isOk()) {
927 ALOGE("Failed to import key -> falling back to software keymaster");
928 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000929 auto fallback = mKeyStore->getFallbackDevice();
930 if (!fallback.isOk()) {
931 return error;
932 }
933 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->importKey(params, format, keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100934 // possible hidl error
935 if (!rc.isOk()) {
936 return rc;
937 }
938 // now check error from callback
939 if (!error.isOk()) {
940 return error;
941 }
942 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400943
944 // Write the characteristics:
945 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
946
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100947 AuthorizationSet opParams = params;
948 std::stringstream kcStream;
949 opParams.Serialize(&kcStream);
950 if (kcStream.bad()) return ResponseCode::SYSTEM_ERROR;
951 auto kcBuf = kcStream.str();
952
953 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
954 ::TYPE_KEY_CHARACTERISTICS);
955 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400956 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
957
958 return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700959}
960
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100961void KeyStoreService::exportKey(const String16& name, KeyFormat format,
962 const hidl_vec<uint8_t>& clientId, const hidl_vec<uint8_t>& appData,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700963 int32_t uid, ExportResult* result) {
964
965 uid_t targetUid = getEffectiveUid(uid);
966 uid_t callingUid = IPCThreadState::self()->getCallingUid();
967 if (!is_granted_to(callingUid, targetUid)) {
968 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100969 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700970 return;
971 }
972
973 Blob keyBlob;
974 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700975
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100976 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
977 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700978 return;
979 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100980
981 auto key = blob2hidlVec(keyBlob);
982 auto& dev = mKeyStore->getDevice(keyBlob);
983
984 auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
985 result->resultCode = ret;
986 if (!result->resultCode.isOk()) {
Ji Wang2c142312016-10-14 17:21:10 +0800987 return;
988 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100989 result->exportData = keyMaterial;
990 };
991 KeyStoreServiceReturnCode rc =
992 KS_HANDLE_HIDL_ERROR(dev->exportKey(format, key, clientId, appData, hidlCb));
993 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
994 // callback hidlCb.
995 if (!rc.isOk()) {
996 result->resultCode = rc;
Ji Wang2c142312016-10-14 17:21:10 +0800997 }
998
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100999 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1000 AuthorizationSet upgradeParams;
1001 if (clientId.size()) {
1002 upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
1003 }
1004 if (appData.size()) {
1005 upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
1006 }
1007 result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
1008 if (!result->resultCode.isOk()) {
1009 return;
1010 }
1011
1012 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
1013
1014 result->resultCode = KS_HANDLE_HIDL_ERROR(
1015 dev->exportKey(format, upgradedHidlKeyBlob, clientId, appData, hidlCb));
1016 if (!result->resultCode.isOk()) {
1017 return;
1018 }
1019 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001020}
1021
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001022static inline void addAuthTokenToParams(AuthorizationSet* params, const HardwareAuthToken* token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001023 if (token) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001024 params->push_back(TAG_AUTH_TOKEN, authToken2HidlVec(*token));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001025 }
1026}
1027
1028void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, KeyPurpose purpose,
1029 bool pruneable, const hidl_vec<KeyParameter>& params,
1030 const hidl_vec<uint8_t>& entropy, int32_t uid,
1031 OperationResult* result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001032 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1033 uid_t targetUid = getEffectiveUid(uid);
1034 if (!is_granted_to(callingUid, targetUid)) {
1035 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001036 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001037 return;
1038 }
1039 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
1040 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001041 result->resultCode = ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001042 return;
1043 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001044 if (!checkAllowedOperationParams(params)) {
1045 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001046 return;
1047 }
1048 Blob keyBlob;
1049 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001050 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Shawn Willdend5a24e62017-02-28 13:53:24 -07001051 if (result->resultCode == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
1052 result->resultCode = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1053 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001054 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001055 return;
1056 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001057
1058 auto key = blob2hidlVec(keyBlob);
1059 auto& dev = mKeyStore->getDevice(keyBlob);
1060 AuthorizationSet opParams = params;
1061 KeyCharacteristics characteristics;
1062 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
1063
1064 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1065 result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
1066 if (!result->resultCode.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001067 return;
1068 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001069 key = blob2hidlVec(keyBlob);
1070 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
Shawn Willden98c59162016-03-20 09:10:18 -06001071 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001072 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001073 return;
1074 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001075
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001076 const HardwareAuthToken* authToken = NULL;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001077
1078 // Merge these characteristics with the ones cached when the key was generated or imported
1079 Blob charBlob;
1080 AuthorizationSet persistedCharacteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001081 result->resultCode =
1082 mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
1083 if (result->resultCode.isOk()) {
1084 // TODO write one shot stream buffer to avoid copying (twice here)
1085 std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
1086 charBlob.getLength());
1087 std::stringstream charStream(charBuffer);
1088 persistedCharacteristics.Deserialize(&charStream);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001089 } else {
1090 ALOGD("Unable to read cached characteristics for key");
1091 }
1092
1093 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001094 AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
1095 AuthorizationSet teeEnforced = characteristics.teeEnforced;
1096 persistedCharacteristics.Union(softwareEnforced);
1097 persistedCharacteristics.Subtract(teeEnforced);
1098 characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001099
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001100 auto authResult = getAuthToken(characteristics, 0, purpose, &authToken,
1101 /*failOnTokenMissing*/ false);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001102 // If per-operation auth is needed we need to begin the operation and
1103 // the client will need to authorize that operation before calling
1104 // update. Any other auth issues stop here.
Shawn Willden827243a2017-09-12 05:41:33 -06001105 if (!authResult.isOk() && authResult != ResponseCode::OP_AUTH_NEEDED) {
1106 result->resultCode = authResult;
1107 return;
1108 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001109
1110 addAuthTokenToParams(&opParams, authToken);
1111
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001112 // Add entropy to the device first.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001113 if (entropy.size()) {
1114 result->resultCode = addRngEntropy(entropy);
1115 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001116 return;
1117 }
1118 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001119
1120 // Create a keyid for this key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001121 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001122 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
1123 ALOGE("Failed to create a key ID for authorization checking.");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001124 result->resultCode = ErrorCode::UNKNOWN_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001125 return;
1126 }
1127
1128 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001129 AuthorizationSet key_auths = characteristics.teeEnforced;
1130 key_auths.append(&characteristics.softwareEnforced[0],
1131 &characteristics.softwareEnforced[characteristics.softwareEnforced.size()]);
1132
1133 result->resultCode = enforcement_policy.AuthorizeOperation(
1134 purpose, keyid, key_auths, opParams, 0 /* op_handle */, true /* is_begin_operation */);
1135 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001136 return;
1137 }
1138
Shawn Willdene2a7b522017-04-11 09:27:40 -06001139 // If there are more than kMaxOperations, abort the oldest operation that was started as
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001140 // pruneable.
Shawn Willdene2a7b522017-04-11 09:27:40 -06001141 while (mOperationMap.getOperationCount() >= kMaxOperations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001142 ALOGD("Reached or exceeded concurrent operations limit");
1143 if (!pruneOperation()) {
1144 break;
1145 }
1146 }
1147
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001148 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1149 uint64_t operationHandle) {
1150 result->resultCode = ret;
1151 if (!result->resultCode.isOk()) {
1152 return;
1153 }
1154 result->handle = operationHandle;
1155 result->outParams = outParams;
1156 };
1157
1158 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
1159 if (rc != ErrorCode::OK) {
1160 ALOGW("Got error %d from begin()", rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001161 }
1162
1163 // If there are too many operations abort the oldest operation that was
1164 // started as pruneable and try again.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001165 while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1166 ALOGW("Ran out of operation handles");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001167 if (!pruneOperation()) {
1168 break;
1169 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001170 rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001171 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001172 if (rc != ErrorCode::OK) {
1173 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001174 return;
1175 }
1176
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001177 // Note: The operation map takes possession of the contents of "characteristics".
1178 // It is safe to use characteristics after the following line but it will be empty.
1179 sp<IBinder> operationToken = mOperationMap.addOperation(
1180 result->handle, keyid, purpose, dev, appToken, std::move(characteristics), pruneable);
1181 assert(characteristics.teeEnforced.size() == 0);
1182 assert(characteristics.softwareEnforced.size() == 0);
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001183 result->token = operationToken;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001184
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001185 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001186 mOperationMap.setOperationAuthToken(operationToken, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001187 }
1188 // Return the authentication lookup result. If this is a per operation
1189 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1190 // application should get an auth token using the handle before the
1191 // first call to update, which will fail if keystore hasn't received the
1192 // auth token.
Shawn Willden2f96c792017-09-07 23:59:08 -06001193 if (result->resultCode == ErrorCode::OK) {
1194 result->resultCode = authResult;
1195 }
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001196
1197 // Other result fields were set in the begin operation's callback.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001198}
1199
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001200void KeyStoreService::update(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1201 const hidl_vec<uint8_t>& data, OperationResult* result) {
1202 if (!checkAllowedOperationParams(params)) {
1203 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001204 return;
1205 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001206 km_device_t dev;
1207 uint64_t handle;
1208 KeyPurpose purpose;
1209 km_id_t keyid;
1210 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001211 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001212 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001213 return;
1214 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001215 AuthorizationSet opParams = params;
1216 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1217 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001218 return;
1219 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001220
1221 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001222 AuthorizationSet key_auths(characteristics->teeEnforced);
1223 key_auths.append(&characteristics->softwareEnforced[0],
1224 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001225 result->resultCode = enforcement_policy.AuthorizeOperation(
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001226 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1227 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001228 return;
1229 }
1230
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001231 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
1232 const hidl_vec<KeyParameter>& outParams, const hidl_vec<uint8_t>& output) {
1233 result->resultCode = ret;
1234 if (!result->resultCode.isOk()) {
1235 return;
1236 }
1237 result->inputConsumed = inputConsumed;
1238 result->outParams = outParams;
1239 result->data = output;
1240 };
1241
Janis Danisevskisb0245ee2017-01-25 15:43:01 +00001242 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->update(handle, opParams.hidl_data(),
1243 data, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001244 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1245 // it if there was a communication error indicated by the ErrorCode.
1246 if (!rc.isOk()) {
1247 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001248 }
1249}
1250
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001251void KeyStoreService::finish(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
1252 const hidl_vec<uint8_t>& signature, const hidl_vec<uint8_t>& entropy,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001253 OperationResult* result) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001254 if (!checkAllowedOperationParams(params)) {
1255 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001256 return;
1257 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001258 km_device_t dev;
1259 uint64_t handle;
1260 KeyPurpose purpose;
1261 km_id_t keyid;
1262 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001263 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001264 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001265 return;
1266 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001267 AuthorizationSet opParams = params;
1268 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1269 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001270 return;
1271 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001272
1273 if (entropy.size()) {
1274 result->resultCode = addRngEntropy(entropy);
1275 if (!result->resultCode.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001276 return;
1277 }
1278 }
1279
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001280 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001281 AuthorizationSet key_auths(characteristics->teeEnforced);
1282 key_auths.append(&characteristics->softwareEnforced[0],
1283 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
1284 result->resultCode = enforcement_policy.AuthorizeOperation(
1285 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1286 if (!result->resultCode.isOk()) return;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001287
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001288 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1289 const hidl_vec<uint8_t>& output) {
1290 result->resultCode = ret;
1291 if (!result->resultCode.isOk()) {
1292 return;
1293 }
1294 result->outParams = outParams;
1295 result->data = output;
1296 };
1297
1298 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->finish(
1299 handle, opParams.hidl_data(),
1300 hidl_vec<uint8_t>() /* TODO(swillden): wire up input to finish() */, signature, hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001301 // Remove the operation regardless of the result
1302 mOperationMap.removeOperation(token);
1303 mAuthTokenTable.MarkCompleted(handle);
1304
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001305 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1306 // it if there was a communication error indicated by the ErrorCode.
1307 if (!rc.isOk()) {
1308 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001309 }
1310}
1311
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001312KeyStoreServiceReturnCode KeyStoreService::abort(const sp<IBinder>& token) {
1313 km_device_t dev;
1314 uint64_t handle;
1315 KeyPurpose purpose;
1316 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001317 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001318 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001319 }
1320 mOperationMap.removeOperation(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001321
1322 ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->abort(handle));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001323 mAuthTokenTable.MarkCompleted(handle);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001324 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001325}
1326
1327bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001328 km_device_t dev;
1329 uint64_t handle;
1330 const KeyCharacteristics* characteristics;
1331 KeyPurpose purpose;
1332 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001333 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1334 return false;
1335 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001336 const HardwareAuthToken* authToken = NULL;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001337 mOperationMap.getOperationAuthToken(token, &authToken);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001338 AuthorizationSet ignored;
1339 auto authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1340 return authResult.isOk();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001341}
1342
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001343KeyStoreServiceReturnCode KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001344 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1345 // receive a HardwareAuthToken, rather than an opaque byte array.
1346
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001347 if (!checkBinderPermission(P_ADD_AUTH)) {
1348 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001349 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001350 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001351 if (length != sizeof(hw_auth_token_t)) {
1352 return ErrorCode::INVALID_ARGUMENT;
1353 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001354
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001355 hw_auth_token_t authToken;
1356 memcpy(reinterpret_cast<void*>(&authToken), token, sizeof(hw_auth_token_t));
1357 if (authToken.version != 0) {
1358 return ErrorCode::INVALID_ARGUMENT;
1359 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001360
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001361 std::unique_ptr<HardwareAuthToken> hidlAuthToken(new HardwareAuthToken);
1362 hidlAuthToken->challenge = authToken.challenge;
1363 hidlAuthToken->userId = authToken.user_id;
1364 hidlAuthToken->authenticatorId = authToken.authenticator_id;
1365 hidlAuthToken->authenticatorType = authToken.authenticator_type;
1366 hidlAuthToken->timestamp = authToken.timestamp;
1367 static_assert(
1368 std::is_same<decltype(hidlAuthToken->hmac),
1369 ::android::hardware::hidl_array<uint8_t, sizeof(authToken.hmac)>>::value,
1370 "This function assumes token HMAC is 32 bytes, but it might not be.");
1371 std::copy(authToken.hmac, authToken.hmac + sizeof(authToken.hmac), hidlAuthToken->hmac.data());
1372
1373 // The table takes ownership of authToken.
1374 mAuthTokenTable.AddAuthenticationToken(hidlAuthToken.release());
1375 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001376}
1377
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001378bool isDeviceIdAttestationRequested(const hidl_vec<KeyParameter>& params) {
1379 for (size_t i = 0; i < params.size(); ++i) {
1380 switch (params[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -06001381 case Tag::ATTESTATION_ID_BRAND:
1382 case Tag::ATTESTATION_ID_DEVICE:
1383 case Tag::ATTESTATION_ID_IMEI:
1384 case Tag::ATTESTATION_ID_MANUFACTURER:
1385 case Tag::ATTESTATION_ID_MEID:
1386 case Tag::ATTESTATION_ID_MODEL:
1387 case Tag::ATTESTATION_ID_PRODUCT:
1388 case Tag::ATTESTATION_ID_SERIAL:
1389 return true;
1390 default:
1391 break;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001392 }
1393 }
1394 return false;
1395}
1396
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001397KeyStoreServiceReturnCode KeyStoreService::attestKey(const String16& name,
1398 const hidl_vec<KeyParameter>& params,
1399 hidl_vec<hidl_vec<uint8_t>>* outChain) {
1400 if (!outChain) {
1401 return ErrorCode::OUTPUT_PARAMETER_NULL;
1402 }
Shawn Willden50eb1b22016-01-21 12:41:23 -07001403
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001404 if (!checkAllowedOperationParams(params)) {
1405 return ErrorCode::INVALID_ARGUMENT;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001406 }
1407
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001408 if (isDeviceIdAttestationRequested(params)) {
1409 // There is a dedicated attestDeviceIds() method for device ID attestation.
1410 return ErrorCode::INVALID_ARGUMENT;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001411 }
1412
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001413 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1414
Shawn Willdene2a7b522017-04-11 09:27:40 -06001415 AuthorizationSet mutableParams = params;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001416 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1417 if (!rc.isOk()) {
1418 return rc;
1419 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001420
Shawn Willden50eb1b22016-01-21 12:41:23 -07001421 Blob keyBlob;
1422 String8 name8(name);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001423 rc = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
1424 if (!rc.isOk()) {
1425 return rc;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001426 }
1427
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001428 KeyStoreServiceReturnCode error;
1429 auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1430 error = ret;
1431 if (!error.isOk()) {
1432 return;
1433 }
1434 if (outChain) *outChain = certChain;
1435 };
1436
1437 auto hidlKey = blob2hidlVec(keyBlob);
1438 auto& dev = mKeyStore->getDevice(keyBlob);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001439 rc = KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
1440 if (!rc.isOk()) {
1441 return rc;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001442 }
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001443 return error;
1444}
1445
1446KeyStoreServiceReturnCode KeyStoreService::attestDeviceIds(const hidl_vec<KeyParameter>& params,
1447 hidl_vec<hidl_vec<uint8_t>>* outChain) {
1448 if (!outChain) {
1449 return ErrorCode::OUTPUT_PARAMETER_NULL;
1450 }
1451
1452 if (!checkAllowedOperationParams(params)) {
1453 return ErrorCode::INVALID_ARGUMENT;
1454 }
1455
1456 if (!isDeviceIdAttestationRequested(params)) {
1457 // There is an attestKey() method for attesting keys without device ID attestation.
1458 return ErrorCode::INVALID_ARGUMENT;
1459 }
1460
1461 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1462 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1463 if (binder == 0) {
1464 return ErrorCode::CANNOT_ATTEST_IDS;
1465 }
1466 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1467 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1468 IPCThreadState::self()->getCallingPid(), callingUid)) {
1469 return ErrorCode::CANNOT_ATTEST_IDS;
1470 }
1471
1472 AuthorizationSet mutableParams = params;
1473 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1474 if (!rc.isOk()) {
1475 return rc;
1476 }
1477
1478 // Generate temporary key.
1479 auto& dev = mKeyStore->getDevice();
1480 KeyStoreServiceReturnCode error;
1481 hidl_vec<uint8_t> hidlKey;
1482
1483 AuthorizationSet keyCharacteristics;
1484 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1485 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1486 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1487 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1488 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
1489 auto generateHidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
1490 const KeyCharacteristics&) {
1491 error = ret;
1492 if (!error.isOk()) {
1493 return;
1494 }
1495 hidlKey = hidlKeyBlob;
1496 };
1497
1498 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(keyCharacteristics.hidl_data(), generateHidlCb));
1499 if (!rc.isOk()) {
1500 return rc;
1501 }
1502 if (!error.isOk()) {
1503 return error;
1504 }
1505
1506 // Attest key and device IDs.
1507 auto attestHidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1508 error = ret;
1509 if (!error.isOk()) {
1510 return;
1511 }
1512 *outChain = certChain;
1513 };
1514 KeyStoreServiceReturnCode attestationRc =
1515 KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), attestHidlCb));
1516
1517 // Delete temporary key.
1518 KeyStoreServiceReturnCode deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001519
1520 if (!attestationRc.isOk()) {
1521 return attestationRc;
1522 }
1523 if (!error.isOk()) {
1524 return error;
1525 }
1526 return deletionRc;
Shawn Willden50eb1b22016-01-21 12:41:23 -07001527}
1528
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001529KeyStoreServiceReturnCode KeyStoreService::onDeviceOffBody() {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001530 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1531 mAuthTokenTable.onDeviceOffBody();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001532 return ResponseCode::NO_ERROR;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001533}
1534
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001535/**
1536 * Prune the oldest pruneable operation.
1537 */
1538bool KeyStoreService::pruneOperation() {
1539 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1540 ALOGD("Trying to prune operation %p", oldest.get());
1541 size_t op_count_before_abort = mOperationMap.getOperationCount();
1542 // We mostly ignore errors from abort() because all we care about is whether at least
1543 // one operation has been removed.
1544 int abort_error = abort(oldest);
1545 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1546 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1547 return false;
1548 }
1549 return true;
1550}
1551
1552/**
1553 * Get the effective target uid for a binder operation that takes an
1554 * optional uid as the target.
1555 */
1556uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1557 if (targetUid == UID_SELF) {
1558 return IPCThreadState::self()->getCallingUid();
1559 }
1560 return static_cast<uid_t>(targetUid);
1561}
1562
1563/**
1564 * Check if the caller of the current binder method has the required
1565 * permission and if acting on other uids the grants to do so.
1566 */
1567bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1568 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1569 pid_t spid = IPCThreadState::self()->getCallingPid();
1570 if (!has_permission(callingUid, permission, spid)) {
1571 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1572 return false;
1573 }
1574 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1575 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1576 return false;
1577 }
1578 return true;
1579}
1580
1581/**
1582 * Check if the caller of the current binder method has the required
1583 * permission and the target uid is the caller or the caller is system.
1584 */
1585bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1586 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1587 pid_t spid = IPCThreadState::self()->getCallingPid();
1588 if (!has_permission(callingUid, permission, spid)) {
1589 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1590 return false;
1591 }
1592 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1593}
1594
1595/**
1596 * Check if the caller of the current binder method has the required
1597 * permission or the target of the operation is the caller's uid. This is
1598 * for operation where the permission is only for cross-uid activity and all
1599 * uids are allowed to act on their own (ie: clearing all entries for a
1600 * given uid).
1601 */
1602bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1603 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1604 if (getEffectiveUid(targetUid) == callingUid) {
1605 return true;
1606 } else {
1607 return checkBinderPermission(permission, targetUid);
1608 }
1609}
1610
1611/**
1612 * Helper method to check that the caller has the required permission as
1613 * well as the keystore is in the unlocked state if checkUnlocked is true.
1614 *
1615 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1616 * otherwise the state of keystore when not unlocked and checkUnlocked is
1617 * true.
1618 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001619KeyStoreServiceReturnCode
1620KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1621 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001622 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001623 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001624 }
1625 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1626 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001627 // All State values coincide with ResponseCodes
1628 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001629 }
1630
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001631 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001632}
1633
1634bool KeyStoreService::isKeystoreUnlocked(State state) {
1635 switch (state) {
1636 case ::STATE_NO_ERROR:
1637 return true;
1638 case ::STATE_UNINITIALIZED:
1639 case ::STATE_LOCKED:
1640 return false;
1641 }
1642 return false;
1643}
1644
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001645/**
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001646 * Check that all KeyParameter's provided by the application are
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001647 * allowed. Any parameter that keystore adds itself should be disallowed here.
1648 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001649bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1650 for (size_t i = 0; i < params.size(); ++i) {
1651 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001652 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001653 case Tag::AUTH_TOKEN:
1654 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001655 return false;
1656 default:
1657 break;
1658 }
1659 }
1660 return true;
1661}
1662
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001663ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
1664 km_device_t* dev,
1665 const AuthorizationSet& params,
1666 KeyCharacteristics* out) {
1667 hidl_vec<uint8_t> appId;
1668 hidl_vec<uint8_t> appData;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001669 for (auto param : params) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001670 if (param.tag == Tag::APPLICATION_ID) {
1671 appId = authorizationValue(TAG_APPLICATION_ID, param).value();
1672 } else if (param.tag == Tag::APPLICATION_DATA) {
1673 appData = authorizationValue(TAG_APPLICATION_DATA, param).value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001674 }
1675 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001676 ErrorCode error = ErrorCode::OK;
1677
1678 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
1679 error = ret;
1680 if (error != ErrorCode::OK) {
1681 return;
1682 }
1683 if (out) *out = keyCharacteristics;
1684 };
1685
1686 ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appData, hidlCb));
1687 if (rc != ErrorCode::OK) {
1688 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001689 }
1690 return error;
1691}
1692
1693/**
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001694 * Get the auth token for this operation from the auth token table.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001695 *
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001696 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
1697 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1698 * authorization token exists for that operation and
1699 * failOnTokenMissing is false.
1700 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1701 * token for the operation
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001702 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001703KeyStoreServiceReturnCode KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics,
1704 uint64_t handle, KeyPurpose purpose,
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001705 const HardwareAuthToken** authToken,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001706 bool failOnTokenMissing) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001707
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001708 AuthorizationSet allCharacteristics;
1709 for (size_t i = 0; i < characteristics.softwareEnforced.size(); i++) {
1710 allCharacteristics.push_back(characteristics.softwareEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001711 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001712 for (size_t i = 0; i < characteristics.teeEnforced.size(); i++) {
1713 allCharacteristics.push_back(characteristics.teeEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001714 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001715 AuthTokenTable::Error err =
1716 mAuthTokenTable.FindAuthorization(allCharacteristics, purpose, handle, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001717 switch (err) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001718 case AuthTokenTable::OK:
1719 case AuthTokenTable::AUTH_NOT_REQUIRED:
1720 return ResponseCode::NO_ERROR;
1721 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1722 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
1723 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
Rubin Xuce99f582017-10-12 10:50:11 +01001724 ALOGE("getAuthToken failed: %d", err); //STOPSHIP: debug only, to be removed
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001725 return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1726 case AuthTokenTable::OP_HANDLE_REQUIRED:
1727 return failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
1728 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001729 default:
1730 ALOGE("Unexpected FindAuthorization return value %d", err);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001731 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001732 }
1733}
1734
1735/**
1736 * Add the auth token for the operation to the param list if the operation
1737 * requires authorization. Uses the cached result in the OperationMap if available
1738 * otherwise gets the token from the AuthTokenTable and caches the result.
1739 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001740 * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001741 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1742 * authenticated.
1743 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1744 * operation token.
1745 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001746KeyStoreServiceReturnCode KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
1747 AuthorizationSet* params) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001748 const HardwareAuthToken* authToken = nullptr;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001749 mOperationMap.getOperationAuthToken(token, &authToken);
1750 if (!authToken) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001751 km_device_t dev;
1752 uint64_t handle;
1753 const KeyCharacteristics* characteristics = nullptr;
1754 KeyPurpose purpose;
1755 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001756 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001757 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001758 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001759 auto result = getAuthToken(*characteristics, handle, purpose, &authToken);
1760 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001761 return result;
1762 }
1763 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001764 mOperationMap.setOperationAuthToken(token, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001765 }
1766 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001767 addAuthTokenToParams(params, authToken);
1768 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001769}
1770
1771/**
1772 * Translate a result value to a legacy return value. All keystore errors are
1773 * preserved and keymaster errors become SYSTEM_ERRORs
1774 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001775KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001776 if (result > 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001777 return static_cast<ResponseCode>(result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001778 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001779 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001780}
1781
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001782static NullOr<const Algorithm&>
1783getKeyAlgoritmFromKeyCharacteristics(const KeyCharacteristics& characteristics) {
1784 for (size_t i = 0; i < characteristics.teeEnforced.size(); ++i) {
1785 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.teeEnforced[i]);
1786 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001787 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001788 for (size_t i = 0; i < characteristics.softwareEnforced.size(); ++i) {
1789 auto algo = authorizationValue(TAG_ALGORITHM, characteristics.softwareEnforced[i]);
1790 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001791 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001792 return {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001793}
1794
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001795void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001796 // All legacy keys are DIGEST_NONE/PAD_NONE.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001797 params->push_back(TAG_DIGEST, Digest::NONE);
1798 params->push_back(TAG_PADDING, PaddingMode::NONE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001799
1800 // Look up the algorithm of the key.
1801 KeyCharacteristics characteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001802 auto rc = getKeyCharacteristics(name, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF,
1803 &characteristics);
1804 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001805 ALOGE("Failed to get key characteristics");
1806 return;
1807 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001808 auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
1809 if (!algorithm.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001810 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1811 return;
1812 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001813 params->push_back(TAG_ALGORITHM, algorithm.value());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001814}
1815
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001816KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
1817 const hidl_vec<uint8_t>& data,
1818 hidl_vec<uint8_t>* out,
1819 const hidl_vec<uint8_t>& signature,
1820 KeyPurpose purpose) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001821
1822 std::basic_stringstream<uint8_t> outBuffer;
1823 OperationResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001824 AuthorizationSet inArgs;
1825 addLegacyBeginParams(name, &inArgs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001826 sp<IBinder> appToken(new BBinder);
1827 sp<IBinder> token;
1828
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001829 begin(appToken, name, purpose, true, inArgs.hidl_data(), hidl_vec<uint8_t>(), UID_SELF,
1830 &result);
1831 if (!result.resultCode.isOk()) {
1832 if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001833 ALOGW("Key not found");
1834 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001835 ALOGW("Error in begin: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001836 }
1837 return translateResultToLegacyResult(result.resultCode);
1838 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001839 inArgs.Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001840 token = result.token;
1841 size_t consumed = 0;
1842 size_t lastConsumed = 0;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001843 hidl_vec<uint8_t> data_view;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001844 do {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001845 data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
1846 update(token, inArgs.hidl_data(), data_view, &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001847 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001848 ALOGW("Error in update: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001849 return translateResultToLegacyResult(result.resultCode);
1850 }
1851 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001852 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001853 }
1854 lastConsumed = result.inputConsumed;
1855 consumed += lastConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001856 } while (consumed < data.size() && lastConsumed > 0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001857
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001858 if (consumed != data.size()) {
1859 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
1860 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001861 }
1862
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001863 finish(token, inArgs.hidl_data(), signature, hidl_vec<uint8_t>(), &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001864 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001865 ALOGW("Error in finish: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001866 return translateResultToLegacyResult(result.resultCode);
1867 }
1868 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001869 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001870 }
1871
1872 if (out) {
1873 auto buf = outBuffer.str();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001874 out->resize(buf.size());
1875 memcpy(&(*out)[0], buf.data(), out->size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001876 }
1877
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001878 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001879}
1880
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001881KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
1882 const AuthorizationSet& params,
1883 Blob* blob) {
Shawn Willden98c59162016-03-20 09:10:18 -06001884 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
1885 String8 name8(name);
1886 ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001887 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willden98c59162016-03-20 09:10:18 -06001888 return responseCode;
1889 }
Rubin Xu7675c9f2017-03-15 19:26:52 +00001890 ALOGI("upgradeKeyBlob %s %d", name8.string(), uid);
Shawn Willden98c59162016-03-20 09:10:18 -06001891
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001892 auto hidlKey = blob2hidlVec(*blob);
1893 auto& dev = mKeyStore->getDevice(*blob);
Shawn Willden98c59162016-03-20 09:10:18 -06001894
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001895 KeyStoreServiceReturnCode error;
1896 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
1897 error = ret;
1898 if (!error.isOk()) {
1899 return;
1900 }
1901
Janis Danisevskisaf7783f2017-09-21 11:29:47 -07001902 auto filename = mKeyStore->getBlobFileNameIfExists(name8, uid, ::TYPE_KEYMASTER_10);
1903 if (!filename.isOk()) {
1904 ALOGI("trying to upgrade a non existing blob");
1905 return;
1906 }
1907 error = mKeyStore->del(filename.value().string(), ::TYPE_ANY, get_user_id(uid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001908 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001909 ALOGI("upgradeKeyBlob keystore->del failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001910 return;
1911 }
1912
1913 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
1914 0 /* infoLength */, ::TYPE_KEYMASTER_10);
1915 newBlob.setFallback(blob->isFallback());
1916 newBlob.setEncrypted(blob->isEncrypted());
Rubin Xu67899de2017-04-21 19:15:13 +01001917 newBlob.setSuperEncrypted(blob->isSuperEncrypted());
1918 newBlob.setCriticalToDeviceEncryption(blob->isCriticalToDeviceEncryption());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001919
Janis Danisevskisaf7783f2017-09-21 11:29:47 -07001920 error = mKeyStore->put(filename.value().string(), &newBlob, get_user_id(uid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001921 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00001922 ALOGI("upgradeKeyBlob keystore->put failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001923 return;
1924 }
1925
1926 // Re-read blob for caller. We can't use newBlob because writing it modified it.
1927 error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1928 };
1929
1930 KeyStoreServiceReturnCode rc =
1931 KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
1932 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06001933 return rc;
1934 }
1935
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001936 return error;
Shawn Willden98c59162016-03-20 09:10:18 -06001937}
1938
Shawn Willdene2a7b522017-04-11 09:27:40 -06001939} // namespace keystore