• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
17 #include "key_store_service.h"
18 
19 #include <fcntl.h>
20 #include <sys/stat.h>
21 
22 #include <sstream>
23 
24 #include <binder/IPCThreadState.h>
25 
26 #include <private/android_filesystem_config.h>
27 
28 #include <hardware/keymaster_defs.h>
29 
30 #include "defaults.h"
31 #include "keystore_utils.h"
32 
33 using keymaster::AuthorizationSet;
34 using keymaster::AuthorizationSetBuilder;
35 using keymaster::TAG_APPLICATION_DATA;
36 using keymaster::TAG_APPLICATION_ID;
37 
38 namespace android {
39 
40 const size_t MAX_OPERATIONS = 15;
41 
42 struct BIGNUM_Delete {
operator ()android::BIGNUM_Delete43     void operator()(BIGNUM* p) const { BN_free(p); }
44 };
45 typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
46 
47 struct Malloc_Delete {
operator ()android::Malloc_Delete48     void operator()(uint8_t* p) const { free(p); }
49 };
50 
binderDied(const wp<IBinder> & who)51 void KeyStoreService::binderDied(const wp<IBinder>& who) {
52     auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
53     for (auto token : operations) {
54         abort(token);
55     }
56 }
57 
getState(int32_t userId)58 int32_t KeyStoreService::getState(int32_t userId) {
59     if (!checkBinderPermission(P_GET_STATE)) {
60         return ::PERMISSION_DENIED;
61     }
62 
63     return mKeyStore->getState(userId);
64 }
65 
get(const String16 & name,int32_t uid,uint8_t ** item,size_t * itemLength)66 int32_t KeyStoreService::get(const String16& name, int32_t uid, uint8_t** item,
67                              size_t* itemLength) {
68     uid_t targetUid = getEffectiveUid(uid);
69     if (!checkBinderPermission(P_GET, targetUid)) {
70         return ::PERMISSION_DENIED;
71     }
72 
73     String8 name8(name);
74     Blob keyBlob;
75 
76     ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
77     if (responseCode != ::NO_ERROR) {
78         *item = NULL;
79         *itemLength = 0;
80         return responseCode;
81     }
82 
83     *item = (uint8_t*)malloc(keyBlob.getLength());
84     memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
85     *itemLength = keyBlob.getLength();
86 
87     return ::NO_ERROR;
88 }
89 
insert(const String16 & name,const uint8_t * item,size_t itemLength,int targetUid,int32_t flags)90 int32_t KeyStoreService::insert(const String16& name, const uint8_t* item, size_t itemLength,
91                                 int targetUid, int32_t flags) {
92     targetUid = getEffectiveUid(targetUid);
93     int32_t result =
94         checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
95     if (result != ::NO_ERROR) {
96         return result;
97     }
98 
99     String8 name8(name);
100     String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_GENERIC));
101 
102     Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
103     keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
104 
105     return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
106 }
107 
del(const String16 & name,int targetUid)108 int32_t KeyStoreService::del(const String16& name, int targetUid) {
109     targetUid = getEffectiveUid(targetUid);
110     if (!checkBinderPermission(P_DELETE, targetUid)) {
111         return ::PERMISSION_DENIED;
112     }
113     String8 name8(name);
114     String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
115     int32_t result = mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
116     if (result != ::NO_ERROR) {
117         return result;
118     }
119 
120     // Also delete any characteristics files
121     String8 chrFilename(mKeyStore->getKeyNameForUidWithDir(
122         name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
123     return mKeyStore->del(chrFilename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
124 }
125 
exist(const String16 & name,int targetUid)126 int32_t KeyStoreService::exist(const String16& name, int targetUid) {
127     targetUid = getEffectiveUid(targetUid);
128     if (!checkBinderPermission(P_EXIST, targetUid)) {
129         return ::PERMISSION_DENIED;
130     }
131 
132     String8 name8(name);
133     String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
134 
135     if (access(filename.string(), R_OK) == -1) {
136         return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
137     }
138     return ::NO_ERROR;
139 }
140 
list(const String16 & prefix,int targetUid,Vector<String16> * matches)141 int32_t KeyStoreService::list(const String16& prefix, int targetUid, Vector<String16>* matches) {
142     targetUid = getEffectiveUid(targetUid);
143     if (!checkBinderPermission(P_LIST, targetUid)) {
144         return ::PERMISSION_DENIED;
145     }
146     const String8 prefix8(prefix);
147     String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid, TYPE_ANY));
148 
149     if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
150         return ::SYSTEM_ERROR;
151     }
152     return ::NO_ERROR;
153 }
154 
reset()155 int32_t KeyStoreService::reset() {
156     if (!checkBinderPermission(P_RESET)) {
157         return ::PERMISSION_DENIED;
158     }
159 
160     uid_t callingUid = IPCThreadState::self()->getCallingUid();
161     mKeyStore->resetUser(get_user_id(callingUid), false);
162     return ::NO_ERROR;
163 }
164 
onUserPasswordChanged(int32_t userId,const String16 & password)165 int32_t KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password) {
166     if (!checkBinderPermission(P_PASSWORD)) {
167         return ::PERMISSION_DENIED;
168     }
169 
170     const String8 password8(password);
171     // Flush the auth token table to prevent stale tokens from sticking
172     // around.
173     mAuthTokenTable.Clear();
174 
175     if (password.size() == 0) {
176         ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
177         mKeyStore->resetUser(userId, true);
178         return ::NO_ERROR;
179     } else {
180         switch (mKeyStore->getState(userId)) {
181         case ::STATE_UNINITIALIZED: {
182             // generate master key, encrypt with password, write to file,
183             // initialize mMasterKey*.
184             return mKeyStore->initializeUser(password8, userId);
185         }
186         case ::STATE_NO_ERROR: {
187             // rewrite master key with new password.
188             return mKeyStore->writeMasterKey(password8, userId);
189         }
190         case ::STATE_LOCKED: {
191             ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
192             mKeyStore->resetUser(userId, true);
193             return mKeyStore->initializeUser(password8, userId);
194         }
195         }
196         return ::SYSTEM_ERROR;
197     }
198 }
199 
onUserAdded(int32_t userId,int32_t parentId)200 int32_t KeyStoreService::onUserAdded(int32_t userId, int32_t parentId) {
201     if (!checkBinderPermission(P_USER_CHANGED)) {
202         return ::PERMISSION_DENIED;
203     }
204 
205     // Sanity check that the new user has an empty keystore.
206     if (!mKeyStore->isEmpty(userId)) {
207         ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
208     }
209     // Unconditionally clear the keystore, just to be safe.
210     mKeyStore->resetUser(userId, false);
211     if (parentId != -1) {
212         // This profile must share the same master key password as the parent profile. Because the
213         // password of the parent profile is not known here, the best we can do is copy the parent's
214         // master key and master key file. This makes this profile use the same master key as the
215         // parent profile, forever.
216         return mKeyStore->copyMasterKey(parentId, userId);
217     } else {
218         return ::NO_ERROR;
219     }
220 }
221 
onUserRemoved(int32_t userId)222 int32_t KeyStoreService::onUserRemoved(int32_t userId) {
223     if (!checkBinderPermission(P_USER_CHANGED)) {
224         return ::PERMISSION_DENIED;
225     }
226 
227     mKeyStore->resetUser(userId, false);
228     return ::NO_ERROR;
229 }
230 
lock(int32_t userId)231 int32_t KeyStoreService::lock(int32_t userId) {
232     if (!checkBinderPermission(P_LOCK)) {
233         return ::PERMISSION_DENIED;
234     }
235 
236     State state = mKeyStore->getState(userId);
237     if (state != ::STATE_NO_ERROR) {
238         ALOGD("calling lock in state: %d", state);
239         return state;
240     }
241 
242     mKeyStore->lock(userId);
243     return ::NO_ERROR;
244 }
245 
unlock(int32_t userId,const String16 & pw)246 int32_t KeyStoreService::unlock(int32_t userId, const String16& pw) {
247     if (!checkBinderPermission(P_UNLOCK)) {
248         return ::PERMISSION_DENIED;
249     }
250 
251     State state = mKeyStore->getState(userId);
252     if (state != ::STATE_LOCKED) {
253         switch (state) {
254         case ::STATE_NO_ERROR:
255             ALOGI("calling unlock when already unlocked, ignoring.");
256             break;
257         case ::STATE_UNINITIALIZED:
258             ALOGE("unlock called on uninitialized keystore.");
259             break;
260         default:
261             ALOGE("unlock called on keystore in unknown state: %d", state);
262             break;
263         }
264         return state;
265     }
266 
267     const String8 password8(pw);
268     // read master key, decrypt with password, initialize mMasterKey*.
269     return mKeyStore->readMasterKey(password8, userId);
270 }
271 
isEmpty(int32_t userId)272 bool KeyStoreService::isEmpty(int32_t userId) {
273     if (!checkBinderPermission(P_IS_EMPTY)) {
274         return false;
275     }
276 
277     return mKeyStore->isEmpty(userId);
278 }
279 
generate(const String16 & name,int32_t targetUid,int32_t keyType,int32_t keySize,int32_t flags,Vector<sp<KeystoreArg>> * args)280 int32_t KeyStoreService::generate(const String16& name, int32_t targetUid, int32_t keyType,
281                                   int32_t keySize, int32_t flags, Vector<sp<KeystoreArg>>* args) {
282     targetUid = getEffectiveUid(targetUid);
283     int32_t result =
284         checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
285     if (result != ::NO_ERROR) {
286         return result;
287     }
288 
289     KeymasterArguments params;
290     add_legacy_key_authorizations(keyType, &params.params);
291 
292     switch (keyType) {
293     case EVP_PKEY_EC: {
294         params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
295         if (keySize == -1) {
296             keySize = EC_DEFAULT_KEY_SIZE;
297         } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
298             ALOGI("invalid key size %d", keySize);
299             return ::SYSTEM_ERROR;
300         }
301         params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
302         break;
303     }
304     case EVP_PKEY_RSA: {
305         params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
306         if (keySize == -1) {
307             keySize = RSA_DEFAULT_KEY_SIZE;
308         } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
309             ALOGI("invalid key size %d", keySize);
310             return ::SYSTEM_ERROR;
311         }
312         params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
313         unsigned long exponent = RSA_DEFAULT_EXPONENT;
314         if (args->size() > 1) {
315             ALOGI("invalid number of arguments: %zu", args->size());
316             return ::SYSTEM_ERROR;
317         } else if (args->size() == 1) {
318             sp<KeystoreArg> expArg = args->itemAt(0);
319             if (expArg != NULL) {
320                 Unique_BIGNUM pubExpBn(BN_bin2bn(
321                     reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
322                 if (pubExpBn.get() == NULL) {
323                     ALOGI("Could not convert public exponent to BN");
324                     return ::SYSTEM_ERROR;
325                 }
326                 exponent = BN_get_word(pubExpBn.get());
327                 if (exponent == 0xFFFFFFFFL) {
328                     ALOGW("cannot represent public exponent as a long value");
329                     return ::SYSTEM_ERROR;
330                 }
331             } else {
332                 ALOGW("public exponent not read");
333                 return ::SYSTEM_ERROR;
334             }
335         }
336         params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, exponent));
337         break;
338     }
339     default: {
340         ALOGW("Unsupported key type %d", keyType);
341         return ::SYSTEM_ERROR;
342     }
343     }
344 
345     int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
346                              /*outCharacteristics*/ NULL);
347     if (rc != ::NO_ERROR) {
348         ALOGW("generate failed: %d", rc);
349     }
350     return translateResultToLegacyResult(rc);
351 }
352 
import(const String16 & name,const uint8_t * data,size_t length,int targetUid,int32_t flags)353 int32_t KeyStoreService::import(const String16& name, const uint8_t* data, size_t length,
354                                 int targetUid, int32_t flags) {
355     const uint8_t* ptr = data;
356 
357     Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
358     if (!pkcs8.get()) {
359         return ::SYSTEM_ERROR;
360     }
361     Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
362     if (!pkey.get()) {
363         return ::SYSTEM_ERROR;
364     }
365     int type = EVP_PKEY_type(pkey->type);
366     KeymasterArguments params;
367     add_legacy_key_authorizations(type, &params.params);
368     switch (type) {
369     case EVP_PKEY_RSA:
370         params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
371         break;
372     case EVP_PKEY_EC:
373         params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
374         break;
375     default:
376         ALOGW("Unsupported key type %d", type);
377         return ::SYSTEM_ERROR;
378     }
379     int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
380                            /*outCharacteristics*/ NULL);
381     if (rc != ::NO_ERROR) {
382         ALOGW("importKey failed: %d", rc);
383     }
384     return translateResultToLegacyResult(rc);
385 }
386 
sign(const String16 & name,const uint8_t * data,size_t length,uint8_t ** out,size_t * outLength)387 int32_t KeyStoreService::sign(const String16& name, const uint8_t* data, size_t length,
388                               uint8_t** out, size_t* outLength) {
389     if (!checkBinderPermission(P_SIGN)) {
390         return ::PERMISSION_DENIED;
391     }
392     return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
393 }
394 
verify(const String16 & name,const uint8_t * data,size_t dataLength,const uint8_t * signature,size_t signatureLength)395 int32_t KeyStoreService::verify(const String16& name, const uint8_t* data, size_t dataLength,
396                                 const uint8_t* signature, size_t signatureLength) {
397     if (!checkBinderPermission(P_VERIFY)) {
398         return ::PERMISSION_DENIED;
399     }
400     return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
401                               KM_PURPOSE_VERIFY);
402 }
403 
404 /*
405  * TODO: The abstraction between things stored in hardware and regular blobs
406  * of data stored on the filesystem should be moved down to keystore itself.
407  * Unfortunately the Java code that calls this has naming conventions that it
408  * knows about. Ideally keystore shouldn't be used to store random blobs of
409  * data.
410  *
411  * Until that happens, it's necessary to have a separate "get_pubkey" and
412  * "del_key" since the Java code doesn't really communicate what it's
413  * intentions are.
414  */
get_pubkey(const String16 & name,uint8_t ** pubkey,size_t * pubkeyLength)415 int32_t KeyStoreService::get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
416     ExportResult result;
417     exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, UID_SELF, &result);
418     if (result.resultCode != ::NO_ERROR) {
419         ALOGW("export failed: %d", result.resultCode);
420         return translateResultToLegacyResult(result.resultCode);
421     }
422 
423     *pubkey = result.exportData.release();
424     *pubkeyLength = result.dataLength;
425     return ::NO_ERROR;
426 }
427 
grant(const String16 & name,int32_t granteeUid)428 int32_t KeyStoreService::grant(const String16& name, int32_t granteeUid) {
429     uid_t callingUid = IPCThreadState::self()->getCallingUid();
430     int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
431     if (result != ::NO_ERROR) {
432         return result;
433     }
434 
435     String8 name8(name);
436     String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
437 
438     if (access(filename.string(), R_OK) == -1) {
439         return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
440     }
441 
442     mKeyStore->addGrant(filename.string(), granteeUid);
443     return ::NO_ERROR;
444 }
445 
ungrant(const String16 & name,int32_t granteeUid)446 int32_t KeyStoreService::ungrant(const String16& name, int32_t granteeUid) {
447     uid_t callingUid = IPCThreadState::self()->getCallingUid();
448     int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
449     if (result != ::NO_ERROR) {
450         return result;
451     }
452 
453     String8 name8(name);
454     String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
455 
456     if (access(filename.string(), R_OK) == -1) {
457         return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
458     }
459 
460     return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
461 }
462 
getmtime(const String16 & name,int32_t uid)463 int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
464     uid_t targetUid = getEffectiveUid(uid);
465     if (!checkBinderPermission(P_GET, targetUid)) {
466         ALOGW("permission denied for %d: getmtime", targetUid);
467         return -1L;
468     }
469 
470     String8 name8(name);
471     String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
472 
473     if (access(filename.string(), R_OK) == -1) {
474         ALOGW("could not access %s for getmtime", filename.string());
475         return -1L;
476     }
477 
478     int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
479     if (fd < 0) {
480         ALOGW("could not open %s for getmtime", filename.string());
481         return -1L;
482     }
483 
484     struct stat s;
485     int ret = fstat(fd, &s);
486     close(fd);
487     if (ret == -1) {
488         ALOGW("could not stat %s for getmtime", filename.string());
489         return -1L;
490     }
491 
492     return static_cast<int64_t>(s.st_mtime);
493 }
494 
495 // TODO(tuckeris): This is dead code, remove it.  Don't bother copying over key characteristics here
duplicate(const String16 & srcKey,int32_t srcUid,const String16 & destKey,int32_t destUid)496 int32_t KeyStoreService::duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
497                                    int32_t destUid) {
498     uid_t callingUid = IPCThreadState::self()->getCallingUid();
499     pid_t spid = IPCThreadState::self()->getCallingPid();
500     if (!has_permission(callingUid, P_DUPLICATE, spid)) {
501         ALOGW("permission denied for %d: duplicate", callingUid);
502         return -1L;
503     }
504 
505     State state = mKeyStore->getState(get_user_id(callingUid));
506     if (!isKeystoreUnlocked(state)) {
507         ALOGD("calling duplicate in state: %d", state);
508         return state;
509     }
510 
511     if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
512         srcUid = callingUid;
513     } else if (!is_granted_to(callingUid, srcUid)) {
514         ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
515         return ::PERMISSION_DENIED;
516     }
517 
518     if (destUid == -1) {
519         destUid = callingUid;
520     }
521 
522     if (srcUid != destUid) {
523         if (static_cast<uid_t>(srcUid) != callingUid) {
524             ALOGD("can only duplicate from caller to other or to same uid: "
525                   "calling=%d, srcUid=%d, destUid=%d",
526                   callingUid, srcUid, destUid);
527             return ::PERMISSION_DENIED;
528         }
529 
530         if (!is_granted_to(callingUid, destUid)) {
531             ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
532             return ::PERMISSION_DENIED;
533         }
534     }
535 
536     String8 source8(srcKey);
537     String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid, ::TYPE_ANY));
538 
539     String8 target8(destKey);
540     String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid, ::TYPE_ANY));
541 
542     if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
543         ALOGD("destination already exists: %s", targetFile.string());
544         return ::SYSTEM_ERROR;
545     }
546 
547     Blob keyBlob;
548     ResponseCode responseCode =
549         mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, get_user_id(srcUid));
550     if (responseCode != ::NO_ERROR) {
551         return responseCode;
552     }
553 
554     return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
555 }
556 
is_hardware_backed(const String16 & keyType)557 int32_t KeyStoreService::is_hardware_backed(const String16& keyType) {
558     return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
559 }
560 
clear_uid(int64_t targetUid64)561 int32_t KeyStoreService::clear_uid(int64_t targetUid64) {
562     uid_t targetUid = getEffectiveUid(targetUid64);
563     if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
564         return ::PERMISSION_DENIED;
565     }
566 
567     String8 prefix = String8::format("%u_", targetUid);
568     Vector<String16> aliases;
569     if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
570         return ::SYSTEM_ERROR;
571     }
572 
573     for (uint32_t i = 0; i < aliases.size(); i++) {
574         String8 name8(aliases[i]);
575         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
576         mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
577 
578         // del() will fail silently if no cached characteristics are present for this alias.
579         String8 chr_filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid,
580             ::TYPE_KEY_CHARACTERISTICS));
581         mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
582     }
583     return ::NO_ERROR;
584 }
585 
addRngEntropy(const uint8_t * data,size_t dataLength)586 int32_t KeyStoreService::addRngEntropy(const uint8_t* data, size_t dataLength) {
587     const auto* device = mKeyStore->getDevice();
588     const auto* fallback = mKeyStore->getFallbackDevice();
589     int32_t devResult = KM_ERROR_UNIMPLEMENTED;
590     int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
591     if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
592         device->add_rng_entropy != NULL) {
593         devResult = device->add_rng_entropy(device, data, dataLength);
594     }
595     if (fallback->add_rng_entropy) {
596         fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
597     }
598     if (devResult) {
599         return devResult;
600     }
601     if (fallbackResult) {
602         return fallbackResult;
603     }
604     return ::NO_ERROR;
605 }
606 
generateKey(const String16 & name,const KeymasterArguments & params,const uint8_t * entropy,size_t entropyLength,int uid,int flags,KeyCharacteristics * outCharacteristics)607 int32_t KeyStoreService::generateKey(const String16& name, const KeymasterArguments& params,
608                                      const uint8_t* entropy, size_t entropyLength, int uid,
609                                      int flags, KeyCharacteristics* outCharacteristics) {
610     uid = getEffectiveUid(uid);
611     int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
612     if (rc != ::NO_ERROR) {
613         return rc;
614     }
615 
616     rc = KM_ERROR_UNIMPLEMENTED;
617     bool isFallback = false;
618     keymaster_key_blob_t blob;
619     keymaster_key_characteristics_t out = {{nullptr, 0}, {nullptr, 0}};
620 
621     const auto* device = mKeyStore->getDevice();
622     const auto* fallback = mKeyStore->getFallbackDevice();
623     std::vector<keymaster_key_param_t> opParams(params.params);
624     const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
625     if (device == NULL) {
626         return ::SYSTEM_ERROR;
627     }
628 
629     // Capture characteristics before they're potentially stripped by the device
630     AuthorizationSet keyCharacteristics(opParams.data(), opParams.size());
631     if (keyCharacteristics.is_valid() != AuthorizationSet::Error::OK) {
632         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
633     }
634     UniquePtr<uint8_t[]> kc_buf;
635     kc_buf.reset(new (std::nothrow) uint8_t[keyCharacteristics.SerializedSize()]);
636     if (!kc_buf.get()) {
637         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
638     }
639     keyCharacteristics.Serialize(kc_buf.get(), kc_buf.get() + keyCharacteristics.SerializedSize());
640 
641     // TODO: Seed from Linux RNG before this.
642     if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
643         device->generate_key != NULL) {
644         if (!entropy) {
645             rc = KM_ERROR_OK;
646         } else if (device->add_rng_entropy) {
647             rc = device->add_rng_entropy(device, entropy, entropyLength);
648         } else {
649             rc = KM_ERROR_UNIMPLEMENTED;
650         }
651         if (rc == KM_ERROR_OK) {
652             rc =
653                 device->generate_key(device, &inParams, &blob, outCharacteristics ? &out : nullptr);
654         }
655     }
656     // If the HW device didn't support generate_key or generate_key failed
657     // fall back to the software implementation.
658     if (rc && fallback->generate_key != NULL) {
659         ALOGW("Primary keymaster device failed to generate key, falling back to SW.");
660         isFallback = true;
661         if (!entropy) {
662             rc = KM_ERROR_OK;
663         } else if (fallback->add_rng_entropy) {
664             rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
665         } else {
666             rc = KM_ERROR_UNIMPLEMENTED;
667         }
668         if (rc == KM_ERROR_OK) {
669             rc = fallback->generate_key(fallback, &inParams, &blob,
670                                         outCharacteristics ? &out : nullptr);
671         }
672     }
673 
674     if (outCharacteristics) {
675         outCharacteristics->characteristics = out;
676     }
677 
678     if (rc) {
679         return rc;
680     }
681 
682     // Write the key:
683     String8 name8(name);
684     String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
685 
686     Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
687     keyBlob.setFallback(isFallback);
688     keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
689 
690     free(const_cast<uint8_t*>(blob.key_material));
691     rc = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
692 
693     if (rc != ::NO_ERROR) {
694         return rc;
695     }
696 
697     // Write the characteristics:
698     String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
699 
700     Blob charBlob(kc_buf.get(), keyCharacteristics.SerializedSize(),
701         NULL, 0, ::TYPE_KEY_CHARACTERISTICS);
702     charBlob.setFallback(isFallback);
703     charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
704 
705     return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
706 }
707 
getKeyCharacteristics(const String16 & name,const keymaster_blob_t * clientId,const keymaster_blob_t * appData,int32_t uid,KeyCharacteristics * outCharacteristics)708 int32_t KeyStoreService::getKeyCharacteristics(const String16& name,
709                                                const keymaster_blob_t* clientId,
710                                                const keymaster_blob_t* appData, int32_t uid,
711                                                KeyCharacteristics* outCharacteristics) {
712     if (!outCharacteristics) {
713         return KM_ERROR_UNEXPECTED_NULL_POINTER;
714     }
715 
716     uid_t targetUid = getEffectiveUid(uid);
717     uid_t callingUid = IPCThreadState::self()->getCallingUid();
718     if (!is_granted_to(callingUid, targetUid)) {
719         ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
720               targetUid);
721         return ::PERMISSION_DENIED;
722     }
723 
724     Blob keyBlob;
725     String8 name8(name);
726     int rc;
727 
728     ResponseCode responseCode =
729         mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
730     if (responseCode != ::NO_ERROR) {
731         return responseCode;
732     }
733     keymaster_key_blob_t key = {keyBlob.getValue(), static_cast<size_t>(keyBlob.getLength())};
734     auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
735     keymaster_key_characteristics_t out = {};
736     if (!dev->get_key_characteristics) {
737         ALOGE("device does not implement get_key_characteristics");
738         return KM_ERROR_UNIMPLEMENTED;
739     }
740     rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
741     if (rc == KM_ERROR_KEY_REQUIRES_UPGRADE) {
742         AuthorizationSet upgradeParams;
743         if (clientId && clientId->data && clientId->data_length) {
744             upgradeParams.push_back(TAG_APPLICATION_ID, *clientId);
745         }
746         if (appData && appData->data && appData->data_length) {
747             upgradeParams.push_back(TAG_APPLICATION_DATA, *appData);
748         }
749         rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
750         if (rc != ::NO_ERROR) {
751             return rc;
752         }
753         key = {keyBlob.getValue(), static_cast<size_t>(keyBlob.getLength())};
754         rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
755     }
756     if (rc != KM_ERROR_OK) {
757         return rc;
758     }
759 
760     outCharacteristics->characteristics = out;
761     return ::NO_ERROR;
762 }
763 
importKey(const String16 & name,const KeymasterArguments & params,keymaster_key_format_t format,const uint8_t * keyData,size_t keyLength,int uid,int flags,KeyCharacteristics * outCharacteristics)764 int32_t KeyStoreService::importKey(const String16& name, const KeymasterArguments& params,
765                                    keymaster_key_format_t format, const uint8_t* keyData,
766                                    size_t keyLength, int uid, int flags,
767                                    KeyCharacteristics* outCharacteristics) {
768     uid = getEffectiveUid(uid);
769     int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
770     if (rc != ::NO_ERROR) {
771         return rc;
772     }
773 
774     rc = KM_ERROR_UNIMPLEMENTED;
775     bool isFallback = false;
776     keymaster_key_blob_t blob;
777     keymaster_key_characteristics_t out = {{nullptr, 0}, {nullptr, 0}};
778 
779     const auto* device = mKeyStore->getDevice();
780     const auto* fallback = mKeyStore->getFallbackDevice();
781     std::vector<keymaster_key_param_t> opParams(params.params);
782     const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
783     const keymaster_blob_t input = {keyData, keyLength};
784     if (device == NULL) {
785         return ::SYSTEM_ERROR;
786     }
787 
788     // Capture characteristics before they're potentially stripped
789     AuthorizationSet keyCharacteristics(opParams.data(), opParams.size());
790     if (keyCharacteristics.is_valid() != AuthorizationSet::Error::OK) {
791         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
792     }
793     UniquePtr<uint8_t[]> kc_buf;
794     kc_buf.reset(new (std::nothrow) uint8_t[keyCharacteristics.SerializedSize()]);
795     if (!kc_buf.get()) {
796         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
797     }
798     keyCharacteristics.Serialize(kc_buf.get(), kc_buf.get() + keyCharacteristics.SerializedSize());
799 
800     if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
801         device->import_key != NULL) {
802         rc = device->import_key(device, &inParams, format, &input, &blob,
803                                 outCharacteristics ? &out : nullptr);
804     }
805     if (rc && fallback->import_key != NULL) {
806         ALOGW("Primary keymaster device failed to import key, falling back to SW.");
807         isFallback = true;
808         rc = fallback->import_key(fallback, &inParams, format, &input, &blob,
809                                   outCharacteristics ? &out : nullptr);
810     }
811     if (outCharacteristics) {
812         outCharacteristics->characteristics = out;
813     }
814 
815     if (rc) {
816         return rc;
817     }
818 
819     // Write the key:
820     String8 name8(name);
821     String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
822 
823     Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
824     keyBlob.setFallback(isFallback);
825     keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
826 
827     free(const_cast<uint8_t*>(blob.key_material));
828     rc = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
829 
830     if (rc != ::NO_ERROR) {
831         return rc;
832     }
833 
834     // Write the characteristics:
835     String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
836 
837     Blob charBlob(kc_buf.get(), keyCharacteristics.SerializedSize(),
838         NULL, 0, ::TYPE_KEY_CHARACTERISTICS);
839     charBlob.setFallback(isFallback);
840     charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
841 
842     return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
843 }
844 
exportKey(const String16 & name,keymaster_key_format_t format,const keymaster_blob_t * clientId,const keymaster_blob_t * appData,int32_t uid,ExportResult * result)845 void KeyStoreService::exportKey(const String16& name, keymaster_key_format_t format,
846                                 const keymaster_blob_t* clientId, const keymaster_blob_t* appData,
847                                 int32_t uid, ExportResult* result) {
848 
849     uid_t targetUid = getEffectiveUid(uid);
850     uid_t callingUid = IPCThreadState::self()->getCallingUid();
851     if (!is_granted_to(callingUid, targetUid)) {
852         ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
853         result->resultCode = ::PERMISSION_DENIED;
854         return;
855     }
856 
857     Blob keyBlob;
858     String8 name8(name);
859     int rc;
860 
861     ResponseCode responseCode =
862         mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
863     if (responseCode != ::NO_ERROR) {
864         result->resultCode = responseCode;
865         return;
866     }
867     keymaster_key_blob_t key;
868     key.key_material_size = keyBlob.getLength();
869     key.key_material = keyBlob.getValue();
870     auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
871     if (!dev->export_key) {
872         result->resultCode = KM_ERROR_UNIMPLEMENTED;
873         return;
874     }
875     keymaster_blob_t output = {NULL, 0};
876     rc = dev->export_key(dev, format, &key, clientId, appData, &output);
877     result->exportData.reset(const_cast<uint8_t*>(output.data));
878     result->dataLength = output.data_length;
879     result->resultCode = rc ? rc : ::NO_ERROR;
880 }
881 
begin(const sp<IBinder> & appToken,const String16 & name,keymaster_purpose_t purpose,bool pruneable,const KeymasterArguments & params,const uint8_t * entropy,size_t entropyLength,int32_t uid,OperationResult * result)882 void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name,
883                             keymaster_purpose_t purpose, bool pruneable,
884                             const KeymasterArguments& params, const uint8_t* entropy,
885                             size_t entropyLength, int32_t uid, OperationResult* result) {
886     uid_t callingUid = IPCThreadState::self()->getCallingUid();
887     uid_t targetUid = getEffectiveUid(uid);
888     if (!is_granted_to(callingUid, targetUid)) {
889         ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
890         result->resultCode = ::PERMISSION_DENIED;
891         return;
892     }
893     if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
894         ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
895         result->resultCode = ::PERMISSION_DENIED;
896         return;
897     }
898     if (!checkAllowedOperationParams(params.params)) {
899         result->resultCode = KM_ERROR_INVALID_ARGUMENT;
900         return;
901     }
902     Blob keyBlob;
903     String8 name8(name);
904     ResponseCode responseCode =
905         mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
906     if (responseCode != ::NO_ERROR) {
907         result->resultCode = responseCode;
908         return;
909     }
910     keymaster_key_blob_t key;
911     key.key_material_size = keyBlob.getLength();
912     key.key_material = keyBlob.getValue();
913     keymaster_operation_handle_t handle;
914     auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
915     keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
916     std::vector<keymaster_key_param_t> opParams(params.params);
917     Unique_keymaster_key_characteristics characteristics;
918     characteristics.reset(new keymaster_key_characteristics_t);
919     err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
920     if (err == KM_ERROR_KEY_REQUIRES_UPGRADE) {
921         int32_t rc = upgradeKeyBlob(name, targetUid,
922                                     AuthorizationSet(opParams.data(), opParams.size()), &keyBlob);
923         if (rc != ::NO_ERROR) {
924             result->resultCode = rc;
925             return;
926         }
927         key = {keyBlob.getValue(), static_cast<size_t>(keyBlob.getLength())};
928         err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
929     }
930     if (err) {
931         result->resultCode = err;
932         return;
933     }
934     const hw_auth_token_t* authToken = NULL;
935 
936     // Merge these characteristics with the ones cached when the key was generated or imported
937     Blob charBlob;
938     AuthorizationSet persistedCharacteristics;
939     responseCode = mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
940     if (responseCode == ::NO_ERROR) {
941         const uint8_t* serializedCharacteristics = charBlob.getValue();
942         persistedCharacteristics.Deserialize(&serializedCharacteristics,
943             serializedCharacteristics + charBlob.getLength());
944     } else {
945         ALOGD("Unable to read cached characteristics for key");
946     }
947 
948     // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
949     persistedCharacteristics.Union(characteristics.get()->sw_enforced);
950     persistedCharacteristics.Difference(characteristics.get()->hw_enforced);
951     persistedCharacteristics.CopyToParamSet(&characteristics.get()->sw_enforced);
952 
953     int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
954                                       /*failOnTokenMissing*/ false);
955     // If per-operation auth is needed we need to begin the operation and
956     // the client will need to authorize that operation before calling
957     // update. Any other auth issues stop here.
958     if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
959         result->resultCode = authResult;
960         return;
961     }
962     addAuthToParams(&opParams, authToken);
963     // Add entropy to the device first.
964     if (entropy) {
965         if (dev->add_rng_entropy) {
966             err = dev->add_rng_entropy(dev, entropy, entropyLength);
967         } else {
968             err = KM_ERROR_UNIMPLEMENTED;
969         }
970         if (err) {
971             result->resultCode = err;
972             return;
973         }
974     }
975     keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
976 
977     // Create a keyid for this key.
978     keymaster::km_id_t keyid;
979     if (!enforcement_policy.CreateKeyId(key, &keyid)) {
980         ALOGE("Failed to create a key ID for authorization checking.");
981         result->resultCode = KM_ERROR_UNKNOWN_ERROR;
982         return;
983     }
984 
985     // Check that all key authorization policy requirements are met.
986     keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
987     key_auths.push_back(characteristics->sw_enforced);
988     keymaster::AuthorizationSet operation_params(inParams);
989     err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params,
990                                                 0 /* op_handle */, true /* is_begin_operation */);
991     if (err) {
992         result->resultCode = err;
993         return;
994     }
995 
996     keymaster_key_param_set_t outParams = {NULL, 0};
997 
998     // If there are more than MAX_OPERATIONS, abort the oldest operation that was started as
999     // pruneable.
1000     while (mOperationMap.getOperationCount() >= MAX_OPERATIONS) {
1001         ALOGD("Reached or exceeded concurrent operations limit");
1002         if (!pruneOperation()) {
1003             break;
1004         }
1005     }
1006 
1007     err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
1008     if (err != KM_ERROR_OK) {
1009         ALOGE("Got error %d from begin()", err);
1010     }
1011 
1012     // If there are too many operations abort the oldest operation that was
1013     // started as pruneable and try again.
1014     while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1015         ALOGE("Ran out of operation handles");
1016         if (!pruneOperation()) {
1017             break;
1018         }
1019         err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
1020     }
1021     if (err) {
1022         result->resultCode = err;
1023         return;
1024     }
1025 
1026     sp<IBinder> operationToken = mOperationMap.addOperation(handle, keyid, purpose, dev, appToken,
1027                                                             characteristics.release(), pruneable);
1028     if (authToken) {
1029         mOperationMap.setOperationAuthToken(operationToken, authToken);
1030     }
1031     // Return the authentication lookup result. If this is a per operation
1032     // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1033     // application should get an auth token using the handle before the
1034     // first call to update, which will fail if keystore hasn't received the
1035     // auth token.
1036     result->resultCode = authResult;
1037     result->token = operationToken;
1038     result->handle = handle;
1039     if (outParams.params) {
1040         result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
1041         free(outParams.params);
1042     }
1043 }
1044 
update(const sp<IBinder> & token,const KeymasterArguments & params,const uint8_t * data,size_t dataLength,OperationResult * result)1045 void KeyStoreService::update(const sp<IBinder>& token, const KeymasterArguments& params,
1046                              const uint8_t* data, size_t dataLength, OperationResult* result) {
1047     if (!checkAllowedOperationParams(params.params)) {
1048         result->resultCode = KM_ERROR_INVALID_ARGUMENT;
1049         return;
1050     }
1051     const keymaster2_device_t* dev;
1052     keymaster_operation_handle_t handle;
1053     keymaster_purpose_t purpose;
1054     keymaster::km_id_t keyid;
1055     const keymaster_key_characteristics_t* characteristics;
1056     if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1057         result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
1058         return;
1059     }
1060     std::vector<keymaster_key_param_t> opParams(params.params);
1061     int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
1062     if (authResult != ::NO_ERROR) {
1063         result->resultCode = authResult;
1064         return;
1065     }
1066     keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
1067     keymaster_blob_t input = {data, dataLength};
1068     size_t consumed = 0;
1069     keymaster_blob_t output = {NULL, 0};
1070     keymaster_key_param_set_t outParams = {NULL, 0};
1071 
1072     // Check that all key authorization policy requirements are met.
1073     keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
1074     key_auths.push_back(characteristics->sw_enforced);
1075     keymaster::AuthorizationSet operation_params(inParams);
1076     result->resultCode = enforcement_policy.AuthorizeOperation(
1077         purpose, keyid, key_auths, operation_params, handle, false /* is_begin_operation */);
1078     if (result->resultCode) {
1079         return;
1080     }
1081 
1082     keymaster_error_t err =
1083         dev->update(dev, handle, &inParams, &input, &consumed, &outParams, &output);
1084     result->data.reset(const_cast<uint8_t*>(output.data));
1085     result->dataLength = output.data_length;
1086     result->inputConsumed = consumed;
1087     result->resultCode = err ? (int32_t)err : ::NO_ERROR;
1088     if (outParams.params) {
1089         result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
1090         free(outParams.params);
1091     }
1092 }
1093 
finish(const sp<IBinder> & token,const KeymasterArguments & params,const uint8_t * signature,size_t signatureLength,const uint8_t * entropy,size_t entropyLength,OperationResult * result)1094 void KeyStoreService::finish(const sp<IBinder>& token, const KeymasterArguments& params,
1095                              const uint8_t* signature, size_t signatureLength,
1096                              const uint8_t* entropy, size_t entropyLength,
1097                              OperationResult* result) {
1098     if (!checkAllowedOperationParams(params.params)) {
1099         result->resultCode = KM_ERROR_INVALID_ARGUMENT;
1100         return;
1101     }
1102     const keymaster2_device_t* dev;
1103     keymaster_operation_handle_t handle;
1104     keymaster_purpose_t purpose;
1105     keymaster::km_id_t keyid;
1106     const keymaster_key_characteristics_t* characteristics;
1107     if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1108         result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
1109         return;
1110     }
1111     std::vector<keymaster_key_param_t> opParams(params.params);
1112     int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
1113     if (authResult != ::NO_ERROR) {
1114         result->resultCode = authResult;
1115         return;
1116     }
1117     keymaster_error_t err;
1118     if (entropy) {
1119         if (dev->add_rng_entropy) {
1120             err = dev->add_rng_entropy(dev, entropy, entropyLength);
1121         } else {
1122             err = KM_ERROR_UNIMPLEMENTED;
1123         }
1124         if (err) {
1125             result->resultCode = err;
1126             return;
1127         }
1128     }
1129 
1130     keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
1131     keymaster_blob_t input = {nullptr, 0};
1132     keymaster_blob_t sig = {signature, signatureLength};
1133     keymaster_blob_t output = {nullptr, 0};
1134     keymaster_key_param_set_t outParams = {nullptr, 0};
1135 
1136     // Check that all key authorization policy requirements are met.
1137     keymaster::AuthorizationSet key_auths(characteristics->hw_enforced);
1138     key_auths.push_back(characteristics->sw_enforced);
1139     keymaster::AuthorizationSet operation_params(inParams);
1140     err = enforcement_policy.AuthorizeOperation(purpose, keyid, key_auths, operation_params, handle,
1141                                                 false /* is_begin_operation */);
1142     if (err) {
1143         result->resultCode = err;
1144         return;
1145     }
1146 
1147     err =
1148         dev->finish(dev, handle, &inParams, &input /* TODO(swillden): wire up input to finish() */,
1149                     &sig, &outParams, &output);
1150     // Remove the operation regardless of the result
1151     mOperationMap.removeOperation(token);
1152     mAuthTokenTable.MarkCompleted(handle);
1153 
1154     result->data.reset(const_cast<uint8_t*>(output.data));
1155     result->dataLength = output.data_length;
1156     result->resultCode = err ? (int32_t)err : ::NO_ERROR;
1157     if (outParams.params) {
1158         result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
1159         free(outParams.params);
1160     }
1161 }
1162 
abort(const sp<IBinder> & token)1163 int32_t KeyStoreService::abort(const sp<IBinder>& token) {
1164     const keymaster2_device_t* dev;
1165     keymaster_operation_handle_t handle;
1166     keymaster_purpose_t purpose;
1167     keymaster::km_id_t keyid;
1168     if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
1169         return KM_ERROR_INVALID_OPERATION_HANDLE;
1170     }
1171     mOperationMap.removeOperation(token);
1172     int32_t rc;
1173     if (!dev->abort) {
1174         rc = KM_ERROR_UNIMPLEMENTED;
1175     } else {
1176         rc = dev->abort(dev, handle);
1177     }
1178     mAuthTokenTable.MarkCompleted(handle);
1179     if (rc) {
1180         return rc;
1181     }
1182     return ::NO_ERROR;
1183 }
1184 
isOperationAuthorized(const sp<IBinder> & token)1185 bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
1186     const keymaster2_device_t* dev;
1187     keymaster_operation_handle_t handle;
1188     const keymaster_key_characteristics_t* characteristics;
1189     keymaster_purpose_t purpose;
1190     keymaster::km_id_t keyid;
1191     if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1192         return false;
1193     }
1194     const hw_auth_token_t* authToken = NULL;
1195     mOperationMap.getOperationAuthToken(token, &authToken);
1196     std::vector<keymaster_key_param_t> ignored;
1197     int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
1198     return authResult == ::NO_ERROR;
1199 }
1200 
addAuthToken(const uint8_t * token,size_t length)1201 int32_t KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
1202     if (!checkBinderPermission(P_ADD_AUTH)) {
1203         ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
1204         return ::PERMISSION_DENIED;
1205     }
1206     if (length != sizeof(hw_auth_token_t)) {
1207         return KM_ERROR_INVALID_ARGUMENT;
1208     }
1209     hw_auth_token_t* authToken = new hw_auth_token_t;
1210     memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
1211     // The table takes ownership of authToken.
1212     mAuthTokenTable.AddAuthenticationToken(authToken);
1213     return ::NO_ERROR;
1214 }
1215 
attestKey(const String16 & name,const KeymasterArguments & params,KeymasterCertificateChain * outChain)1216 int32_t KeyStoreService::attestKey(const String16& name, const KeymasterArguments& params,
1217                                    KeymasterCertificateChain* outChain) {
1218     if (!outChain)
1219         return KM_ERROR_OUTPUT_PARAMETER_NULL;
1220 
1221     if (!checkAllowedOperationParams(params.params)) {
1222         return KM_ERROR_INVALID_ARGUMENT;
1223     }
1224 
1225     uid_t callingUid = IPCThreadState::self()->getCallingUid();
1226 
1227     Blob keyBlob;
1228     String8 name8(name);
1229     ResponseCode responseCode =
1230         mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
1231     if (responseCode != ::NO_ERROR) {
1232         return responseCode;
1233     }
1234 
1235     keymaster_key_blob_t key = {keyBlob.getValue(),
1236                                 static_cast<size_t>(std::max(0, keyBlob.getLength()))};
1237     auto* dev = mKeyStore->getDeviceForBlob(keyBlob);
1238     if (!dev->attest_key)
1239         return KM_ERROR_UNIMPLEMENTED;
1240 
1241     const keymaster_key_param_set_t in_params = {
1242         const_cast<keymaster_key_param_t*>(params.params.data()), params.params.size()};
1243     outChain->chain = {nullptr, 0};
1244     int32_t rc = dev->attest_key(dev, &key, &in_params, &outChain->chain);
1245     if (rc)
1246         return rc;
1247     return ::NO_ERROR;
1248 }
1249 
onDeviceOffBody()1250 int32_t KeyStoreService::onDeviceOffBody() {
1251     // TODO(tuckeris): add permission check.  This should be callable from ClockworkHome only.
1252     mAuthTokenTable.onDeviceOffBody();
1253     return ::NO_ERROR;
1254 }
1255 
1256 /**
1257  * Prune the oldest pruneable operation.
1258  */
pruneOperation()1259 bool KeyStoreService::pruneOperation() {
1260     sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1261     ALOGD("Trying to prune operation %p", oldest.get());
1262     size_t op_count_before_abort = mOperationMap.getOperationCount();
1263     // We mostly ignore errors from abort() because all we care about is whether at least
1264     // one operation has been removed.
1265     int abort_error = abort(oldest);
1266     if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1267         ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1268         return false;
1269     }
1270     return true;
1271 }
1272 
1273 /**
1274  * Get the effective target uid for a binder operation that takes an
1275  * optional uid as the target.
1276  */
getEffectiveUid(int32_t targetUid)1277 uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1278     if (targetUid == UID_SELF) {
1279         return IPCThreadState::self()->getCallingUid();
1280     }
1281     return static_cast<uid_t>(targetUid);
1282 }
1283 
1284 /**
1285  * Check if the caller of the current binder method has the required
1286  * permission and if acting on other uids the grants to do so.
1287  */
checkBinderPermission(perm_t permission,int32_t targetUid)1288 bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1289     uid_t callingUid = IPCThreadState::self()->getCallingUid();
1290     pid_t spid = IPCThreadState::self()->getCallingPid();
1291     if (!has_permission(callingUid, permission, spid)) {
1292         ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1293         return false;
1294     }
1295     if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1296         ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1297         return false;
1298     }
1299     return true;
1300 }
1301 
1302 /**
1303  * Check if the caller of the current binder method has the required
1304  * permission and the target uid is the caller or the caller is system.
1305  */
checkBinderPermissionSelfOrSystem(perm_t permission,int32_t targetUid)1306 bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1307     uid_t callingUid = IPCThreadState::self()->getCallingUid();
1308     pid_t spid = IPCThreadState::self()->getCallingPid();
1309     if (!has_permission(callingUid, permission, spid)) {
1310         ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1311         return false;
1312     }
1313     return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1314 }
1315 
1316 /**
1317  * Check if the caller of the current binder method has the required
1318  * permission or the target of the operation is the caller's uid. This is
1319  * for operation where the permission is only for cross-uid activity and all
1320  * uids are allowed to act on their own (ie: clearing all entries for a
1321  * given uid).
1322  */
checkBinderPermissionOrSelfTarget(perm_t permission,int32_t targetUid)1323 bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1324     uid_t callingUid = IPCThreadState::self()->getCallingUid();
1325     if (getEffectiveUid(targetUid) == callingUid) {
1326         return true;
1327     } else {
1328         return checkBinderPermission(permission, targetUid);
1329     }
1330 }
1331 
1332 /**
1333  * Helper method to check that the caller has the required permission as
1334  * well as the keystore is in the unlocked state if checkUnlocked is true.
1335  *
1336  * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1337  * otherwise the state of keystore when not unlocked and checkUnlocked is
1338  * true.
1339  */
checkBinderPermissionAndKeystoreState(perm_t permission,int32_t targetUid,bool checkUnlocked)1340 int32_t KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1341                                                                bool checkUnlocked) {
1342     if (!checkBinderPermission(permission, targetUid)) {
1343         return ::PERMISSION_DENIED;
1344     }
1345     State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1346     if (checkUnlocked && !isKeystoreUnlocked(state)) {
1347         return state;
1348     }
1349 
1350     return ::NO_ERROR;
1351 }
1352 
isKeystoreUnlocked(State state)1353 bool KeyStoreService::isKeystoreUnlocked(State state) {
1354     switch (state) {
1355     case ::STATE_NO_ERROR:
1356         return true;
1357     case ::STATE_UNINITIALIZED:
1358     case ::STATE_LOCKED:
1359         return false;
1360     }
1361     return false;
1362 }
1363 
isKeyTypeSupported(const keymaster2_device_t * device,keymaster_keypair_t keyType)1364 bool KeyStoreService::isKeyTypeSupported(const keymaster2_device_t* device,
1365                                          keymaster_keypair_t keyType) {
1366     const int32_t device_api = device->common.module->module_api_version;
1367     if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
1368         switch (keyType) {
1369         case TYPE_RSA:
1370         case TYPE_DSA:
1371         case TYPE_EC:
1372             return true;
1373         default:
1374             return false;
1375         }
1376     } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
1377         switch (keyType) {
1378         case TYPE_RSA:
1379             return true;
1380         case TYPE_DSA:
1381             return device->flags & KEYMASTER_SUPPORTS_DSA;
1382         case TYPE_EC:
1383             return device->flags & KEYMASTER_SUPPORTS_EC;
1384         default:
1385             return false;
1386         }
1387     } else {
1388         return keyType == TYPE_RSA;
1389     }
1390 }
1391 
1392 /**
1393  * Check that all keymaster_key_param_t's provided by the application are
1394  * allowed. Any parameter that keystore adds itself should be disallowed here.
1395  */
checkAllowedOperationParams(const std::vector<keymaster_key_param_t> & params)1396 bool KeyStoreService::checkAllowedOperationParams(
1397     const std::vector<keymaster_key_param_t>& params) {
1398     for (auto param : params) {
1399         switch (param.tag) {
1400         case KM_TAG_AUTH_TOKEN:
1401             return false;
1402         default:
1403             break;
1404         }
1405     }
1406     return true;
1407 }
1408 
getOperationCharacteristics(const keymaster_key_blob_t & key,const keymaster2_device_t * dev,const std::vector<keymaster_key_param_t> & params,keymaster_key_characteristics_t * out)1409 keymaster_error_t KeyStoreService::getOperationCharacteristics(
1410     const keymaster_key_blob_t& key, const keymaster2_device_t* dev,
1411     const std::vector<keymaster_key_param_t>& params, keymaster_key_characteristics_t* out) {
1412     UniquePtr<keymaster_blob_t> appId;
1413     UniquePtr<keymaster_blob_t> appData;
1414     for (auto param : params) {
1415         if (param.tag == KM_TAG_APPLICATION_ID) {
1416             appId.reset(new keymaster_blob_t);
1417             appId->data = param.blob.data;
1418             appId->data_length = param.blob.data_length;
1419         } else if (param.tag == KM_TAG_APPLICATION_DATA) {
1420             appData.reset(new keymaster_blob_t);
1421             appData->data = param.blob.data;
1422             appData->data_length = param.blob.data_length;
1423         }
1424     }
1425     keymaster_key_characteristics_t result = {{nullptr, 0}, {nullptr, 0}};
1426     if (!dev->get_key_characteristics) {
1427         return KM_ERROR_UNIMPLEMENTED;
1428     }
1429     keymaster_error_t error =
1430         dev->get_key_characteristics(dev, &key, appId.get(), appData.get(), &result);
1431     if (error == KM_ERROR_OK) {
1432         *out = result;
1433     }
1434     return error;
1435 }
1436 
1437 /**
1438  * Get the auth token for this operation from the auth token table.
1439  *
1440  * Returns ::NO_ERROR if the auth token was set or none was required.
1441  *         ::OP_AUTH_NEEDED if it is a per op authorization, no
1442  *         authorization token exists for that operation and
1443  *         failOnTokenMissing is false.
1444  *         KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1445  *         token for the operation
1446  */
getAuthToken(const keymaster_key_characteristics_t * characteristics,keymaster_operation_handle_t handle,keymaster_purpose_t purpose,const hw_auth_token_t ** authToken,bool failOnTokenMissing)1447 int32_t KeyStoreService::getAuthToken(const keymaster_key_characteristics_t* characteristics,
1448                                       keymaster_operation_handle_t handle,
1449                                       keymaster_purpose_t purpose,
1450                                       const hw_auth_token_t** authToken, bool failOnTokenMissing) {
1451 
1452     std::vector<keymaster_key_param_t> allCharacteristics;
1453     for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
1454         allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
1455     }
1456     for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
1457         allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
1458     }
1459     keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
1460         allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
1461     switch (err) {
1462     case keymaster::AuthTokenTable::OK:
1463     case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
1464         return ::NO_ERROR;
1465     case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1466     case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
1467     case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
1468         return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
1469     case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
1470         return failOnTokenMissing ? (int32_t)KM_ERROR_KEY_USER_NOT_AUTHENTICATED
1471                                   : (int32_t)::OP_AUTH_NEEDED;
1472     default:
1473         ALOGE("Unexpected FindAuthorization return value %d", err);
1474         return KM_ERROR_INVALID_ARGUMENT;
1475     }
1476 }
1477 
addAuthToParams(std::vector<keymaster_key_param_t> * params,const hw_auth_token_t * token)1478 inline void KeyStoreService::addAuthToParams(std::vector<keymaster_key_param_t>* params,
1479                                              const hw_auth_token_t* token) {
1480     if (token) {
1481         params->push_back(keymaster_param_blob(
1482             KM_TAG_AUTH_TOKEN, reinterpret_cast<const uint8_t*>(token), sizeof(hw_auth_token_t)));
1483     }
1484 }
1485 
1486 /**
1487  * Add the auth token for the operation to the param list if the operation
1488  * requires authorization. Uses the cached result in the OperationMap if available
1489  * otherwise gets the token from the AuthTokenTable and caches the result.
1490  *
1491  * Returns ::NO_ERROR if the auth token was added or not needed.
1492  *         KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1493  *         authenticated.
1494  *         KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1495  *         operation token.
1496  */
addOperationAuthTokenIfNeeded(sp<IBinder> token,std::vector<keymaster_key_param_t> * params)1497 int32_t KeyStoreService::addOperationAuthTokenIfNeeded(sp<IBinder> token,
1498                                                        std::vector<keymaster_key_param_t>* params) {
1499     const hw_auth_token_t* authToken = NULL;
1500     mOperationMap.getOperationAuthToken(token, &authToken);
1501     if (!authToken) {
1502         const keymaster2_device_t* dev;
1503         keymaster_operation_handle_t handle;
1504         const keymaster_key_characteristics_t* characteristics = NULL;
1505         keymaster_purpose_t purpose;
1506         keymaster::km_id_t keyid;
1507         if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
1508             return KM_ERROR_INVALID_OPERATION_HANDLE;
1509         }
1510         int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
1511         if (result != ::NO_ERROR) {
1512             return result;
1513         }
1514         if (authToken) {
1515             mOperationMap.setOperationAuthToken(token, authToken);
1516         }
1517     }
1518     addAuthToParams(params, authToken);
1519     return ::NO_ERROR;
1520 }
1521 
1522 /**
1523  * Translate a result value to a legacy return value. All keystore errors are
1524  * preserved and keymaster errors become SYSTEM_ERRORs
1525  */
translateResultToLegacyResult(int32_t result)1526 int32_t KeyStoreService::translateResultToLegacyResult(int32_t result) {
1527     if (result > 0) {
1528         return result;
1529     }
1530     return ::SYSTEM_ERROR;
1531 }
1532 
1533 keymaster_key_param_t*
getKeyAlgorithm(keymaster_key_characteristics_t * characteristics)1534 KeyStoreService::getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
1535     for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
1536         if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
1537             return &characteristics->hw_enforced.params[i];
1538         }
1539     }
1540     for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
1541         if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
1542             return &characteristics->sw_enforced.params[i];
1543         }
1544     }
1545     return NULL;
1546 }
1547 
addLegacyBeginParams(const String16 & name,std::vector<keymaster_key_param_t> & params)1548 void KeyStoreService::addLegacyBeginParams(const String16& name,
1549                                            std::vector<keymaster_key_param_t>& params) {
1550     // All legacy keys are DIGEST_NONE/PAD_NONE.
1551     params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
1552     params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
1553 
1554     // Look up the algorithm of the key.
1555     KeyCharacteristics characteristics;
1556     int32_t rc = getKeyCharacteristics(name, NULL, NULL, UID_SELF, &characteristics);
1557     if (rc != ::NO_ERROR) {
1558         ALOGE("Failed to get key characteristics");
1559         return;
1560     }
1561     keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
1562     if (!algorithm) {
1563         ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
1564         return;
1565     }
1566     params.push_back(*algorithm);
1567 }
1568 
doLegacySignVerify(const String16 & name,const uint8_t * data,size_t length,uint8_t ** out,size_t * outLength,const uint8_t * signature,size_t signatureLength,keymaster_purpose_t purpose)1569 int32_t KeyStoreService::doLegacySignVerify(const String16& name, const uint8_t* data,
1570                                             size_t length, uint8_t** out, size_t* outLength,
1571                                             const uint8_t* signature, size_t signatureLength,
1572                                             keymaster_purpose_t purpose) {
1573 
1574     std::basic_stringstream<uint8_t> outBuffer;
1575     OperationResult result;
1576     KeymasterArguments inArgs;
1577     addLegacyBeginParams(name, inArgs.params);
1578     sp<IBinder> appToken(new BBinder);
1579     sp<IBinder> token;
1580 
1581     begin(appToken, name, purpose, true, inArgs, NULL, 0, UID_SELF, &result);
1582     if (result.resultCode != ResponseCode::NO_ERROR) {
1583         if (result.resultCode == ::KEY_NOT_FOUND) {
1584             ALOGW("Key not found");
1585         } else {
1586             ALOGW("Error in begin: %d", result.resultCode);
1587         }
1588         return translateResultToLegacyResult(result.resultCode);
1589     }
1590     inArgs.params.clear();
1591     token = result.token;
1592     size_t consumed = 0;
1593     size_t lastConsumed = 0;
1594     do {
1595         update(token, inArgs, data + consumed, length - consumed, &result);
1596         if (result.resultCode != ResponseCode::NO_ERROR) {
1597             ALOGW("Error in update: %d", result.resultCode);
1598             return translateResultToLegacyResult(result.resultCode);
1599         }
1600         if (out) {
1601             outBuffer.write(result.data.get(), result.dataLength);
1602         }
1603         lastConsumed = result.inputConsumed;
1604         consumed += lastConsumed;
1605     } while (consumed < length && lastConsumed > 0);
1606 
1607     if (consumed != length) {
1608         ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
1609         return ::SYSTEM_ERROR;
1610     }
1611 
1612     finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
1613     if (result.resultCode != ResponseCode::NO_ERROR) {
1614         ALOGW("Error in finish: %d", result.resultCode);
1615         return translateResultToLegacyResult(result.resultCode);
1616     }
1617     if (out) {
1618         outBuffer.write(result.data.get(), result.dataLength);
1619     }
1620 
1621     if (out) {
1622         auto buf = outBuffer.str();
1623         *out = new uint8_t[buf.size()];
1624         memcpy(*out, buf.c_str(), buf.size());
1625         *outLength = buf.size();
1626     }
1627 
1628     return ::NO_ERROR;
1629 }
1630 
upgradeKeyBlob(const String16 & name,uid_t uid,const AuthorizationSet & params,Blob * blob)1631 int32_t KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
1632                                         const AuthorizationSet& params, Blob* blob) {
1633     // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
1634     String8 name8(name);
1635     ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1636     if (responseCode != ::NO_ERROR) {
1637         return responseCode;
1638     }
1639 
1640     keymaster_key_blob_t key = {blob->getValue(), static_cast<size_t>(blob->getLength())};
1641     auto* dev = mKeyStore->getDeviceForBlob(*blob);
1642     keymaster_key_blob_t upgraded_key;
1643     int32_t rc = dev->upgrade_key(dev, &key, &params, &upgraded_key);
1644     if (rc != KM_ERROR_OK) {
1645         return rc;
1646     }
1647     UniquePtr<uint8_t, Malloc_Delete> upgraded_key_deleter(
1648         const_cast<uint8_t*>(upgraded_key.key_material));
1649 
1650     rc = del(name, uid);
1651     if (rc != ::NO_ERROR) {
1652         return rc;
1653     }
1654 
1655     String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1656     Blob newBlob(upgraded_key.key_material, upgraded_key.key_material_size, nullptr /* info */,
1657                  0 /* infoLength */, ::TYPE_KEYMASTER_10);
1658     newBlob.setFallback(blob->isFallback());
1659     newBlob.setEncrypted(blob->isEncrypted());
1660 
1661     rc = mKeyStore->put(filename.string(), &newBlob, get_user_id(uid));
1662 
1663     // Re-read blob for caller.  We can't use newBlob because writing it modified it.
1664     responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
1665     if (responseCode != ::NO_ERROR) {
1666         return responseCode;
1667     }
1668 
1669     return rc;
1670 }
1671 
1672 }  // namespace android
1673