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