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 #define LOG_TAG "keystore"
     18 
     19 #include "key_store_service.h"
     20 
     21 #include <fcntl.h>
     22 #include <sys/stat.h>
     23 
     24 #include <algorithm>
     25 #include <sstream>
     26 
     27 #include <binder/IInterface.h>
     28 #include <binder/IPCThreadState.h>
     29 #include <binder/IPermissionController.h>
     30 #include <binder/IServiceManager.h>
     31 
     32 #include <private/android_filesystem_config.h>
     33 
     34 #include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
     35 
     36 #include "defaults.h"
     37 #include "keystore_attestation_id.h"
     38 #include "keystore_keymaster_enforcement.h"
     39 #include "keystore_utils.h"
     40 #include <keystore/keystore_hidl_support.h>
     41 
     42 namespace keystore {
     43 
     44 using namespace android;
     45 
     46 namespace {
     47 
     48 constexpr size_t kMaxOperations = 15;
     49 constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
     50 const char* kTimestampFilePath = "timestamp";
     51 
     52 struct BIGNUM_Delete {
     53     void operator()(BIGNUM* p) const { BN_free(p); }
     54 };
     55 typedef std::unique_ptr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
     56 
     57 bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
     58     return params.end() != std::find_if(params.begin(), params.end(),
     59                                         [&](auto& param) { return param.tag == tag; });
     60 }
     61 
     62 bool isAuthenticationBound(const hidl_vec<KeyParameter>& params) {
     63     return !containsTag(params, Tag::NO_AUTH_REQUIRED);
     64 }
     65 
     66 std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
     67     struct stat sbuf;
     68     if (stat(kTimestampFilePath, &sbuf) == 0) {
     69         double diff_secs = difftime(time(NULL), sbuf.st_ctime);
     70         return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
     71     }
     72 
     73     if (errno != ENOENT) {
     74         ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
     75         return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
     76     }
     77 
     78     int fd = creat(kTimestampFilePath, 0600);
     79     if (fd < 0) {
     80         ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
     81         return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
     82     }
     83 
     84     if (close(fd)) {
     85         ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
     86         return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
     87     }
     88 
     89     return {ResponseCode::NO_ERROR, true};
     90 }
     91 
     92 constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
     93 
     94 KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
     95     KeyStoreServiceReturnCode responseCode;
     96     bool factoryResetSinceIdRotation;
     97     std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
     98 
     99     if (!responseCode.isOk()) return responseCode;
    100     if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
    101 
    102     auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
    103     if (!asn1_attestation_id_result.isOk()) {
    104         ALOGE("failed to gather attestation_id");
    105         return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
    106     }
    107     std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
    108 
    109     /*
    110      * The attestation application ID cannot be longer than
    111      * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, so we truncate if too long.
    112      */
    113     if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
    114         asn1_attestation_id.resize(KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE);
    115     }
    116 
    117     params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
    118 
    119     return ResponseCode::NO_ERROR;
    120 }
    121 
    122 }  // anonymous namespace
    123 
    124 void KeyStoreService::binderDied(const wp<IBinder>& who) {
    125     auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
    126     for (const auto& token : operations) {
    127         abort(token);
    128     }
    129 }
    130 
    131 KeyStoreServiceReturnCode KeyStoreService::getState(int32_t userId) {
    132     if (!checkBinderPermission(P_GET_STATE)) {
    133         return ResponseCode::PERMISSION_DENIED;
    134     }
    135 
    136     return ResponseCode(mKeyStore->getState(userId));
    137 }
    138 
    139 KeyStoreServiceReturnCode KeyStoreService::get(const String16& name, int32_t uid,
    140                                                hidl_vec<uint8_t>* item) {
    141     uid_t targetUid = getEffectiveUid(uid);
    142     if (!checkBinderPermission(P_GET, targetUid)) {
    143         return ResponseCode::PERMISSION_DENIED;
    144     }
    145 
    146     String8 name8(name);
    147     Blob keyBlob;
    148 
    149     KeyStoreServiceReturnCode rc =
    150         mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
    151     if (!rc.isOk()) {
    152         if (item) *item = hidl_vec<uint8_t>();
    153         return rc;
    154     }
    155 
    156     // Do not replace this with "if (item) *item = blob2hidlVec(keyBlob)"!
    157     // blob2hidlVec creates a hidl_vec<uint8_t> that references, but not owns, the data in keyBlob
    158     // the subsequent assignment (*item = resultBlob) makes a deep copy, so that *item will own the
    159     // corresponding resources.
    160     auto resultBlob = blob2hidlVec(keyBlob);
    161     if (item) {
    162         *item = resultBlob;
    163     }
    164 
    165     return ResponseCode::NO_ERROR;
    166 }
    167 
    168 KeyStoreServiceReturnCode KeyStoreService::insert(const String16& name,
    169                                                   const hidl_vec<uint8_t>& item, int targetUid,
    170                                                   int32_t flags) {
    171     targetUid = getEffectiveUid(targetUid);
    172     auto result =
    173         checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
    174     if (!result.isOk()) {
    175         return result;
    176     }
    177 
    178     String8 name8(name);
    179     String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_GENERIC));
    180 
    181     Blob keyBlob(&item[0], item.size(), NULL, 0, ::TYPE_GENERIC);
    182     keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
    183 
    184     return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
    185 }
    186 
    187 KeyStoreServiceReturnCode KeyStoreService::del(const String16& name, int targetUid) {
    188     targetUid = getEffectiveUid(targetUid);
    189     if (!checkBinderPermission(P_DELETE, targetUid)) {
    190         return ResponseCode::PERMISSION_DENIED;
    191     }
    192     String8 name8(name);
    193     ALOGI("del %s %d", name8.string(), targetUid);
    194     auto filename = mKeyStore->getBlobFileNameIfExists(name8, targetUid, ::TYPE_ANY);
    195     if (!filename.isOk()) return ResponseCode::KEY_NOT_FOUND;
    196 
    197     ResponseCode result = mKeyStore->del(filename.value().string(), ::TYPE_ANY,
    198             get_user_id(targetUid));
    199     if (result != ResponseCode::NO_ERROR) {
    200         return result;
    201     }
    202 
    203     filename = mKeyStore->getBlobFileNameIfExists(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS);
    204     if (filename.isOk()) {
    205         return mKeyStore->del(filename.value().string(), ::TYPE_KEY_CHARACTERISTICS,
    206                 get_user_id(targetUid));
    207     }
    208     return ResponseCode::NO_ERROR;
    209 }
    210 
    211 KeyStoreServiceReturnCode KeyStoreService::exist(const String16& name, int targetUid) {
    212     targetUid = getEffectiveUid(targetUid);
    213     if (!checkBinderPermission(P_EXIST, targetUid)) {
    214         return ResponseCode::PERMISSION_DENIED;
    215     }
    216 
    217     auto filename = mKeyStore->getBlobFileNameIfExists(String8(name), targetUid, ::TYPE_ANY);
    218     return filename.isOk() ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND;
    219 }
    220 
    221 KeyStoreServiceReturnCode KeyStoreService::list(const String16& prefix, int targetUid,
    222                                                 Vector<String16>* matches) {
    223     targetUid = getEffectiveUid(targetUid);
    224     if (!checkBinderPermission(P_LIST, targetUid)) {
    225         return ResponseCode::PERMISSION_DENIED;
    226     }
    227     const String8 prefix8(prefix);
    228     String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid, TYPE_ANY));
    229 
    230     if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
    231         return ResponseCode::SYSTEM_ERROR;
    232     }
    233     return ResponseCode::NO_ERROR;
    234 }
    235 
    236 KeyStoreServiceReturnCode KeyStoreService::reset() {
    237     if (!checkBinderPermission(P_RESET)) {
    238         return ResponseCode::PERMISSION_DENIED;
    239     }
    240 
    241     uid_t callingUid = IPCThreadState::self()->getCallingUid();
    242     mKeyStore->resetUser(get_user_id(callingUid), false);
    243     return ResponseCode::NO_ERROR;
    244 }
    245 
    246 KeyStoreServiceReturnCode KeyStoreService::onUserPasswordChanged(int32_t userId,
    247                                                                  const String16& password) {
    248     if (!checkBinderPermission(P_PASSWORD)) {
    249         return ResponseCode::PERMISSION_DENIED;
    250     }
    251 
    252     const String8 password8(password);
    253     // Flush the auth token table to prevent stale tokens from sticking
    254     // around.
    255     mAuthTokenTable.Clear();
    256 
    257     if (password.size() == 0) {
    258         ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
    259         mKeyStore->resetUser(userId, true);
    260         return ResponseCode::NO_ERROR;
    261     } else {
    262         switch (mKeyStore->getState(userId)) {
    263         case ::STATE_UNINITIALIZED: {
    264             // generate master key, encrypt with password, write to file,
    265             // initialize mMasterKey*.
    266             return mKeyStore->initializeUser(password8, userId);
    267         }
    268         case ::STATE_NO_ERROR: {
    269             // rewrite master key with new password.
    270             return mKeyStore->writeMasterKey(password8, userId);
    271         }
    272         case ::STATE_LOCKED: {
    273             ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
    274             mKeyStore->resetUser(userId, true);
    275             return mKeyStore->initializeUser(password8, userId);
    276         }
    277         }
    278         return ResponseCode::SYSTEM_ERROR;
    279     }
    280 }
    281 
    282 KeyStoreServiceReturnCode KeyStoreService::onUserAdded(int32_t userId, int32_t parentId) {
    283     if (!checkBinderPermission(P_USER_CHANGED)) {
    284         return ResponseCode::PERMISSION_DENIED;
    285     }
    286 
    287     // Sanity check that the new user has an empty keystore.
    288     if (!mKeyStore->isEmpty(userId)) {
    289         ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
    290     }
    291     // Unconditionally clear the keystore, just to be safe.
    292     mKeyStore->resetUser(userId, false);
    293     if (parentId != -1) {
    294         // This profile must share the same master key password as the parent profile. Because the
    295         // password of the parent profile is not known here, the best we can do is copy the parent's
    296         // master key and master key file. This makes this profile use the same master key as the
    297         // parent profile, forever.
    298         return mKeyStore->copyMasterKey(parentId, userId);
    299     } else {
    300         return ResponseCode::NO_ERROR;
    301     }
    302 }
    303 
    304 KeyStoreServiceReturnCode KeyStoreService::onUserRemoved(int32_t userId) {
    305     if (!checkBinderPermission(P_USER_CHANGED)) {
    306         return ResponseCode::PERMISSION_DENIED;
    307     }
    308 
    309     mKeyStore->resetUser(userId, false);
    310     return ResponseCode::NO_ERROR;
    311 }
    312 
    313 KeyStoreServiceReturnCode KeyStoreService::lock(int32_t userId) {
    314     if (!checkBinderPermission(P_LOCK)) {
    315         return ResponseCode::PERMISSION_DENIED;
    316     }
    317 
    318     State state = mKeyStore->getState(userId);
    319     if (state != ::STATE_NO_ERROR) {
    320         ALOGD("calling lock in state: %d", state);
    321         return ResponseCode(state);
    322     }
    323 
    324     mKeyStore->lock(userId);
    325     return ResponseCode::NO_ERROR;
    326 }
    327 
    328 KeyStoreServiceReturnCode KeyStoreService::unlock(int32_t userId, const String16& pw) {
    329     if (!checkBinderPermission(P_UNLOCK)) {
    330         return ResponseCode::PERMISSION_DENIED;
    331     }
    332 
    333     State state = mKeyStore->getState(userId);
    334     if (state != ::STATE_LOCKED) {
    335         switch (state) {
    336         case ::STATE_NO_ERROR:
    337             ALOGI("calling unlock when already unlocked, ignoring.");
    338             break;
    339         case ::STATE_UNINITIALIZED:
    340             ALOGE("unlock called on uninitialized keystore.");
    341             break;
    342         default:
    343             ALOGE("unlock called on keystore in unknown state: %d", state);
    344             break;
    345         }
    346         return ResponseCode(state);
    347     }
    348 
    349     const String8 password8(pw);
    350     // read master key, decrypt with password, initialize mMasterKey*.
    351     return mKeyStore->readMasterKey(password8, userId);
    352 }
    353 
    354 bool KeyStoreService::isEmpty(int32_t userId) {
    355     if (!checkBinderPermission(P_IS_EMPTY)) {
    356         return false;
    357     }
    358 
    359     return mKeyStore->isEmpty(userId);
    360 }
    361 
    362 KeyStoreServiceReturnCode KeyStoreService::generate(const String16& name, int32_t targetUid,
    363                                                     int32_t keyType, int32_t keySize, int32_t flags,
    364                                                     Vector<sp<KeystoreArg>>* args) {
    365     targetUid = getEffectiveUid(targetUid);
    366     auto result =
    367         checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
    368     if (!result.isOk()) {
    369         return result;
    370     }
    371 
    372     keystore::AuthorizationSet params;
    373     add_legacy_key_authorizations(keyType, &params);
    374 
    375     switch (keyType) {
    376     case EVP_PKEY_EC: {
    377         params.push_back(TAG_ALGORITHM, Algorithm::EC);
    378         if (keySize == -1) {
    379             keySize = EC_DEFAULT_KEY_SIZE;
    380         } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
    381             ALOGI("invalid key size %d", keySize);
    382             return ResponseCode::SYSTEM_ERROR;
    383         }
    384         params.push_back(TAG_KEY_SIZE, keySize);
    385         break;
    386     }
    387     case EVP_PKEY_RSA: {
    388         params.push_back(TAG_ALGORITHM, Algorithm::RSA);
    389         if (keySize == -1) {
    390             keySize = RSA_DEFAULT_KEY_SIZE;
    391         } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
    392             ALOGI("invalid key size %d", keySize);
    393             return ResponseCode::SYSTEM_ERROR;
    394         }
    395         params.push_back(TAG_KEY_SIZE, keySize);
    396         unsigned long exponent = RSA_DEFAULT_EXPONENT;
    397         if (args->size() > 1) {
    398             ALOGI("invalid number of arguments: %zu", args->size());
    399             return ResponseCode::SYSTEM_ERROR;
    400         } else if (args->size() == 1) {
    401             const sp<KeystoreArg>& expArg = args->itemAt(0);
    402             if (expArg != NULL) {
    403                 Unique_BIGNUM pubExpBn(BN_bin2bn(
    404                     reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
    405                 if (pubExpBn.get() == NULL) {
    406                     ALOGI("Could not convert public exponent to BN");
    407                     return ResponseCode::SYSTEM_ERROR;
    408                 }
    409                 exponent = BN_get_word(pubExpBn.get());
    410                 if (exponent == 0xFFFFFFFFL) {
    411                     ALOGW("cannot represent public exponent as a long value");
    412                     return ResponseCode::SYSTEM_ERROR;
    413                 }
    414             } else {
    415                 ALOGW("public exponent not read");
    416                 return ResponseCode::SYSTEM_ERROR;
    417             }
    418         }
    419         params.push_back(TAG_RSA_PUBLIC_EXPONENT, exponent);
    420         break;
    421     }
    422     default: {
    423         ALOGW("Unsupported key type %d", keyType);
    424         return ResponseCode::SYSTEM_ERROR;
    425     }
    426     }
    427 
    428     auto rc = generateKey(name, params.hidl_data(), hidl_vec<uint8_t>(), targetUid, flags,
    429                           /*outCharacteristics*/ NULL);
    430     if (!rc.isOk()) {
    431         ALOGW("generate failed: %d", int32_t(rc));
    432     }
    433     return translateResultToLegacyResult(rc);
    434 }
    435 
    436 KeyStoreServiceReturnCode KeyStoreService::import(const String16& name,
    437                                                   const hidl_vec<uint8_t>& data, int targetUid,
    438                                                   int32_t flags) {
    439 
    440     const uint8_t* ptr = &data[0];
    441 
    442     Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, data.size()));
    443     if (!pkcs8.get()) {
    444         return ResponseCode::SYSTEM_ERROR;
    445     }
    446     Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
    447     if (!pkey.get()) {
    448         return ResponseCode::SYSTEM_ERROR;
    449     }
    450     int type = EVP_PKEY_type(pkey->type);
    451     AuthorizationSet params;
    452     add_legacy_key_authorizations(type, &params);
    453     switch (type) {
    454     case EVP_PKEY_RSA:
    455         params.push_back(TAG_ALGORITHM, Algorithm::RSA);
    456         break;
    457     case EVP_PKEY_EC:
    458         params.push_back(TAG_ALGORITHM, Algorithm::EC);
    459         break;
    460     default:
    461         ALOGW("Unsupported key type %d", type);
    462         return ResponseCode::SYSTEM_ERROR;
    463     }
    464 
    465     auto rc = importKey(name, params.hidl_data(), KeyFormat::PKCS8, data, targetUid, flags,
    466                         /*outCharacteristics*/ NULL);
    467 
    468     if (!rc.isOk()) {
    469         ALOGW("importKey failed: %d", int32_t(rc));
    470     }
    471     return translateResultToLegacyResult(rc);
    472 }
    473 
    474 KeyStoreServiceReturnCode KeyStoreService::sign(const String16& name, const hidl_vec<uint8_t>& data,
    475                                                 hidl_vec<uint8_t>* out) {
    476     if (!checkBinderPermission(P_SIGN)) {
    477         return ResponseCode::PERMISSION_DENIED;
    478     }
    479     return doLegacySignVerify(name, data, out, hidl_vec<uint8_t>(), KeyPurpose::SIGN);
    480 }
    481 
    482 KeyStoreServiceReturnCode KeyStoreService::verify(const String16& name,
    483                                                   const hidl_vec<uint8_t>& data,
    484                                                   const hidl_vec<uint8_t>& signature) {
    485     if (!checkBinderPermission(P_VERIFY)) {
    486         return ResponseCode::PERMISSION_DENIED;
    487     }
    488     return doLegacySignVerify(name, data, nullptr, signature, KeyPurpose::VERIFY);
    489 }
    490 
    491 /*
    492  * TODO: The abstraction between things stored in hardware and regular blobs
    493  * of data stored on the filesystem should be moved down to keystore itself.
    494  * Unfortunately the Java code that calls this has naming conventions that it
    495  * knows about. Ideally keystore shouldn't be used to store random blobs of
    496  * data.
    497  *
    498  * Until that happens, it's necessary to have a separate "get_pubkey" and
    499  * "del_key" since the Java code doesn't really communicate what it's
    500  * intentions are.
    501  */
    502 KeyStoreServiceReturnCode KeyStoreService::get_pubkey(const String16& name,
    503                                                       hidl_vec<uint8_t>* pubKey) {
    504     ExportResult result;
    505     exportKey(name, KeyFormat::X509, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF, &result);
    506     if (!result.resultCode.isOk()) {
    507         ALOGW("export failed: %d", int32_t(result.resultCode));
    508         return translateResultToLegacyResult(result.resultCode);
    509     }
    510 
    511     if (pubKey) *pubKey = std::move(result.exportData);
    512     return ResponseCode::NO_ERROR;
    513 }
    514 
    515 String16 KeyStoreService::grant(const String16& name, int32_t granteeUid) {
    516     uid_t callingUid = IPCThreadState::self()->getCallingUid();
    517     auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
    518     if (!result.isOk()) {
    519         return String16();
    520     }
    521 
    522     String8 name8(name);
    523     String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
    524 
    525     if (access(filename.string(), R_OK) == -1) {
    526         return String16();
    527     }
    528 
    529     return String16(mKeyStore->addGrant(String8(name).string(), callingUid, granteeUid).c_str());
    530 }
    531 
    532 KeyStoreServiceReturnCode KeyStoreService::ungrant(const String16& name, int32_t granteeUid) {
    533     uid_t callingUid = IPCThreadState::self()->getCallingUid();
    534     auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
    535     if (!result.isOk()) {
    536         return result;
    537     }
    538 
    539     String8 name8(name);
    540     String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
    541 
    542     if (access(filename.string(), R_OK) == -1) {
    543         return (errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::KEY_NOT_FOUND;
    544     }
    545 
    546     return mKeyStore->removeGrant(name8, callingUid, granteeUid) ? ResponseCode::NO_ERROR
    547                                                      : ResponseCode::KEY_NOT_FOUND;
    548 }
    549 
    550 int64_t KeyStoreService::getmtime(const String16& name, int32_t uid) {
    551     uid_t targetUid = getEffectiveUid(uid);
    552     if (!checkBinderPermission(P_GET, targetUid)) {
    553         ALOGW("permission denied for %d: getmtime", targetUid);
    554         return -1L;
    555     }
    556 
    557     auto filename = mKeyStore->getBlobFileNameIfExists(String8(name), targetUid, ::TYPE_ANY);
    558 
    559     if (!filename.isOk()) {
    560         ALOGW("could not access %s for getmtime", filename.value().string());
    561         return -1L;
    562     }
    563 
    564     int fd = TEMP_FAILURE_RETRY(open(filename.value().string(), O_NOFOLLOW, O_RDONLY));
    565     if (fd < 0) {
    566         ALOGW("could not open %s for getmtime", filename.value().string());
    567         return -1L;
    568     }
    569 
    570     struct stat s;
    571     int ret = fstat(fd, &s);
    572     close(fd);
    573     if (ret == -1) {
    574         ALOGW("could not stat %s for getmtime", filename.value().string());
    575         return -1L;
    576     }
    577 
    578     return static_cast<int64_t>(s.st_mtime);
    579 }
    580 
    581 // TODO(tuckeris): This is dead code, remove it.  Don't bother copying over key characteristics here
    582 KeyStoreServiceReturnCode KeyStoreService::duplicate(const String16& srcKey, int32_t srcUid,
    583                                                      const String16& destKey, int32_t destUid) {
    584     uid_t callingUid = IPCThreadState::self()->getCallingUid();
    585     pid_t spid = IPCThreadState::self()->getCallingPid();
    586     if (!has_permission(callingUid, P_DUPLICATE, spid)) {
    587         ALOGW("permission denied for %d: duplicate", callingUid);
    588         return ResponseCode::PERMISSION_DENIED;
    589     }
    590 
    591     State state = mKeyStore->getState(get_user_id(callingUid));
    592     if (!isKeystoreUnlocked(state)) {
    593         ALOGD("calling duplicate in state: %d", state);
    594         return ResponseCode(state);
    595     }
    596 
    597     if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
    598         srcUid = callingUid;
    599     } else if (!is_granted_to(callingUid, srcUid)) {
    600         ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
    601         return ResponseCode::PERMISSION_DENIED;
    602     }
    603 
    604     if (destUid == -1) {
    605         destUid = callingUid;
    606     }
    607 
    608     if (srcUid != destUid) {
    609         if (static_cast<uid_t>(srcUid) != callingUid) {
    610             ALOGD("can only duplicate from caller to other or to same uid: "
    611                   "calling=%d, srcUid=%d, destUid=%d",
    612                   callingUid, srcUid, destUid);
    613             return ResponseCode::PERMISSION_DENIED;
    614         }
    615 
    616         if (!is_granted_to(callingUid, destUid)) {
    617             ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
    618             return ResponseCode::PERMISSION_DENIED;
    619         }
    620     }
    621 
    622     String8 source8(srcKey);
    623     String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid, ::TYPE_ANY));
    624 
    625     String8 target8(destKey);
    626     String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid, ::TYPE_ANY));
    627 
    628     if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
    629         ALOGD("destination already exists: %s", targetFile.string());
    630         return ResponseCode::SYSTEM_ERROR;
    631     }
    632 
    633     Blob keyBlob;
    634     ResponseCode responseCode =
    635         mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, get_user_id(srcUid));
    636     if (responseCode != ResponseCode::NO_ERROR) {
    637         return responseCode;
    638     }
    639 
    640     return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
    641 }
    642 
    643 int32_t KeyStoreService::is_hardware_backed(const String16& keyType) {
    644     return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
    645 }
    646 
    647 KeyStoreServiceReturnCode KeyStoreService::clear_uid(int64_t targetUid64) {
    648     uid_t targetUid = getEffectiveUid(targetUid64);
    649     if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
    650         return ResponseCode::PERMISSION_DENIED;
    651     }
    652     ALOGI("clear_uid %" PRId64, targetUid64);
    653 
    654     mKeyStore->removeAllGrantsToUid(targetUid);
    655 
    656     String8 prefix = String8::format("%u_", targetUid);
    657     Vector<String16> aliases;
    658     if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
    659         return ResponseCode::SYSTEM_ERROR;
    660     }
    661 
    662     for (uint32_t i = 0; i < aliases.size(); i++) {
    663         String8 name8(aliases[i]);
    664         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
    665 
    666         if (get_app_id(targetUid) == AID_SYSTEM) {
    667             Blob keyBlob;
    668             ResponseCode responseCode =
    669                 mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, get_user_id(targetUid));
    670             if (responseCode == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
    671                 // Do not clear keys critical to device encryption under system uid.
    672                 continue;
    673             }
    674         }
    675 
    676         mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
    677 
    678         // del() will fail silently if no cached characteristics are present for this alias.
    679         String8 chr_filename(
    680             mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
    681         mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
    682     }
    683     return ResponseCode::NO_ERROR;
    684 }
    685 
    686 KeyStoreServiceReturnCode KeyStoreService::addRngEntropy(const hidl_vec<uint8_t>& entropy) {
    687     const auto& device = mKeyStore->getDevice();
    688     return KS_HANDLE_HIDL_ERROR(device->addRngEntropy(entropy));
    689 }
    690 
    691 KeyStoreServiceReturnCode KeyStoreService::generateKey(const String16& name,
    692                                                        const hidl_vec<KeyParameter>& params,
    693                                                        const hidl_vec<uint8_t>& entropy, int uid,
    694                                                        int flags,
    695                                                        KeyCharacteristics* outCharacteristics) {
    696     uid = getEffectiveUid(uid);
    697     KeyStoreServiceReturnCode rc =
    698         checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
    699     if (!rc.isOk()) {
    700         return rc;
    701     }
    702     if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
    703         ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
    704         return ResponseCode::PERMISSION_DENIED;
    705     }
    706 
    707     if (containsTag(params, Tag::INCLUDE_UNIQUE_ID)) {
    708         if (!checkBinderPermission(P_GEN_UNIQUE_ID)) return ResponseCode::PERMISSION_DENIED;
    709     }
    710 
    711     bool usingFallback = false;
    712     auto& dev = mKeyStore->getDevice();
    713     AuthorizationSet keyCharacteristics = params;
    714 
    715     // TODO: Seed from Linux RNG before this.
    716     rc = addRngEntropy(entropy);
    717     if (!rc.isOk()) {
    718         return rc;
    719     }
    720 
    721     KeyStoreServiceReturnCode error;
    722     auto hidl_cb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
    723                        const KeyCharacteristics& keyCharacteristics) {
    724         error = ret;
    725         if (!error.isOk()) {
    726             return;
    727         }
    728         if (outCharacteristics) *outCharacteristics = keyCharacteristics;
    729 
    730         // Write the key
    731         String8 name8(name);
    732         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
    733 
    734         Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
    735         keyBlob.setFallback(usingFallback);
    736         keyBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
    737         if (isAuthenticationBound(params) && !keyBlob.isCriticalToDeviceEncryption()) {
    738             keyBlob.setSuperEncrypted(true);
    739         }
    740         keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
    741 
    742         error = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
    743     };
    744 
    745     rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(params, hidl_cb));
    746     if (!rc.isOk()) {
    747         return rc;
    748     }
    749     if (!error.isOk()) {
    750         ALOGE("Failed to generate key -> falling back to software keymaster");
    751         usingFallback = true;
    752         auto fallback = mKeyStore->getFallbackDevice();
    753         if (!fallback.isOk()) {
    754             return error;
    755         }
    756         rc = KS_HANDLE_HIDL_ERROR(fallback.value()->generateKey(params, hidl_cb));
    757         if (!rc.isOk()) {
    758             return rc;
    759         }
    760         if (!error.isOk()) {
    761             return error;
    762         }
    763     }
    764 
    765     // Write the characteristics:
    766     String8 name8(name);
    767     String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
    768 
    769     std::stringstream kc_stream;
    770     keyCharacteristics.Serialize(&kc_stream);
    771     if (kc_stream.bad()) {
    772         return ResponseCode::SYSTEM_ERROR;
    773     }
    774     auto kc_buf = kc_stream.str();
    775     Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
    776                   ::TYPE_KEY_CHARACTERISTICS);
    777     charBlob.setFallback(usingFallback);
    778     charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
    779 
    780     return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
    781 }
    782 
    783 KeyStoreServiceReturnCode
    784 KeyStoreService::getKeyCharacteristics(const String16& name, const hidl_vec<uint8_t>& clientId,
    785                                        const hidl_vec<uint8_t>& appData, int32_t uid,
    786                                        KeyCharacteristics* outCharacteristics) {
    787     if (!outCharacteristics) {
    788         return ErrorCode::UNEXPECTED_NULL_POINTER;
    789     }
    790 
    791     uid_t targetUid = getEffectiveUid(uid);
    792     uid_t callingUid = IPCThreadState::self()->getCallingUid();
    793     if (!is_granted_to(callingUid, targetUid)) {
    794         ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
    795               targetUid);
    796         return ResponseCode::PERMISSION_DENIED;
    797     }
    798 
    799     Blob keyBlob;
    800     String8 name8(name);
    801 
    802     KeyStoreServiceReturnCode rc =
    803         mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
    804     if (rc == ResponseCode::UNINITIALIZED) {
    805         /*
    806          * If we fail reading the blob because the master key is missing we try to retrieve the
    807          * key characteristics from the characteristics file. This happens when auth-bound
    808          * keys are used after a screen lock has been removed by the user.
    809          */
    810         rc = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
    811         if (!rc.isOk()) {
    812             return rc;
    813         }
    814         AuthorizationSet keyCharacteristics;
    815         // TODO write one shot stream buffer to avoid copying (twice here)
    816         std::string charBuffer(reinterpret_cast<const char*>(keyBlob.getValue()),
    817                                keyBlob.getLength());
    818         std::stringstream charStream(charBuffer);
    819         keyCharacteristics.Deserialize(&charStream);
    820 
    821         outCharacteristics->softwareEnforced = keyCharacteristics.hidl_data();
    822         return rc;
    823     } else if (!rc.isOk()) {
    824         return rc;
    825     }
    826 
    827     auto hidlKeyBlob = blob2hidlVec(keyBlob);
    828     auto& dev = mKeyStore->getDevice(keyBlob);
    829 
    830     KeyStoreServiceReturnCode error;
    831 
    832     auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
    833         error = ret;
    834         if (!error.isOk()) {
    835             return;
    836         }
    837         *outCharacteristics = keyCharacteristics;
    838     };
    839 
    840     rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(hidlKeyBlob, clientId, appData, hidlCb));
    841     if (!rc.isOk()) {
    842         return rc;
    843     }
    844 
    845     if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
    846         AuthorizationSet upgradeParams;
    847         if (clientId.size()) {
    848             upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
    849         }
    850         if (appData.size()) {
    851             upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
    852         }
    853         rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
    854         if (!rc.isOk()) {
    855             return rc;
    856         }
    857 
    858         auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
    859 
    860         rc = KS_HANDLE_HIDL_ERROR(
    861             dev->getKeyCharacteristics(upgradedHidlKeyBlob, clientId, appData, hidlCb));
    862         if (!rc.isOk()) {
    863             return rc;
    864         }
    865         // Note that, on success, "error" will have been updated by the hidlCB callback.
    866         // So it is fine to return "error" below.
    867     }
    868     return error;
    869 }
    870 
    871 KeyStoreServiceReturnCode
    872 KeyStoreService::importKey(const String16& name, const hidl_vec<KeyParameter>& params,
    873                            KeyFormat format, const hidl_vec<uint8_t>& keyData, int uid, int flags,
    874                            KeyCharacteristics* outCharacteristics) {
    875     uid = getEffectiveUid(uid);
    876     KeyStoreServiceReturnCode rc =
    877         checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
    878     if (!rc.isOk()) {
    879         return rc;
    880     }
    881     if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
    882         ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
    883         return ResponseCode::PERMISSION_DENIED;
    884     }
    885 
    886     bool usingFallback = false;
    887     auto& dev = mKeyStore->getDevice();
    888 
    889     String8 name8(name);
    890 
    891     KeyStoreServiceReturnCode error;
    892 
    893     auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
    894                       const KeyCharacteristics& keyCharacteristics) {
    895         error = ret;
    896         if (!error.isOk()) {
    897             return;
    898         }
    899 
    900         if (outCharacteristics) *outCharacteristics = keyCharacteristics;
    901 
    902         // Write the key:
    903         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
    904 
    905         Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
    906         ksBlob.setFallback(usingFallback);
    907         ksBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
    908         if (isAuthenticationBound(params) && !ksBlob.isCriticalToDeviceEncryption()) {
    909             ksBlob.setSuperEncrypted(true);
    910         }
    911         ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
    912 
    913         error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
    914     };
    915 
    916     rc = KS_HANDLE_HIDL_ERROR(dev->importKey(params, format, keyData, hidlCb));
    917     // possible hidl error
    918     if (!rc.isOk()) {
    919         return rc;
    920     }
    921     // now check error from callback
    922     if (!error.isOk()) {
    923         ALOGE("Failed to import key -> falling back to software keymaster");
    924         usingFallback = true;
    925         auto fallback = mKeyStore->getFallbackDevice();
    926         if (!fallback.isOk()) {
    927             return error;
    928         }
    929         rc = KS_HANDLE_HIDL_ERROR(fallback.value()->importKey(params, format, keyData, hidlCb));
    930         // possible hidl error
    931         if (!rc.isOk()) {
    932             return rc;
    933         }
    934         // now check error from callback
    935         if (!error.isOk()) {
    936             return error;
    937         }
    938     }
    939 
    940     // Write the characteristics:
    941     String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
    942 
    943     AuthorizationSet opParams = params;
    944     std::stringstream kcStream;
    945     opParams.Serialize(&kcStream);
    946     if (kcStream.bad()) return ResponseCode::SYSTEM_ERROR;
    947     auto kcBuf = kcStream.str();
    948 
    949     Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
    950                   ::TYPE_KEY_CHARACTERISTICS);
    951     charBlob.setFallback(usingFallback);
    952     charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
    953 
    954     return mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid));
    955 }
    956 
    957 void KeyStoreService::exportKey(const String16& name, KeyFormat format,
    958                                 const hidl_vec<uint8_t>& clientId, const hidl_vec<uint8_t>& appData,
    959                                 int32_t uid, ExportResult* result) {
    960 
    961     uid_t targetUid = getEffectiveUid(uid);
    962     uid_t callingUid = IPCThreadState::self()->getCallingUid();
    963     if (!is_granted_to(callingUid, targetUid)) {
    964         ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
    965         result->resultCode = ResponseCode::PERMISSION_DENIED;
    966         return;
    967     }
    968 
    969     Blob keyBlob;
    970     String8 name8(name);
    971 
    972     result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
    973     if (!result->resultCode.isOk()) {
    974         return;
    975     }
    976 
    977     auto key = blob2hidlVec(keyBlob);
    978     auto& dev = mKeyStore->getDevice(keyBlob);
    979 
    980     auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
    981         result->resultCode = ret;
    982         if (!result->resultCode.isOk()) {
    983             return;
    984         }
    985         result->exportData = keyMaterial;
    986     };
    987     KeyStoreServiceReturnCode rc =
    988         KS_HANDLE_HIDL_ERROR(dev->exportKey(format, key, clientId, appData, hidlCb));
    989     // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
    990     // callback hidlCb.
    991     if (!rc.isOk()) {
    992         result->resultCode = rc;
    993     }
    994 
    995     if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
    996         AuthorizationSet upgradeParams;
    997         if (clientId.size()) {
    998             upgradeParams.push_back(TAG_APPLICATION_ID, clientId);
    999         }
   1000         if (appData.size()) {
   1001             upgradeParams.push_back(TAG_APPLICATION_DATA, appData);
   1002         }
   1003         result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
   1004         if (!result->resultCode.isOk()) {
   1005             return;
   1006         }
   1007 
   1008         auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
   1009 
   1010         result->resultCode = KS_HANDLE_HIDL_ERROR(
   1011             dev->exportKey(format, upgradedHidlKeyBlob, clientId, appData, hidlCb));
   1012         if (!result->resultCode.isOk()) {
   1013             return;
   1014         }
   1015     }
   1016 }
   1017 
   1018 static inline void addAuthTokenToParams(AuthorizationSet* params, const HardwareAuthToken* token) {
   1019     if (token) {
   1020         params->push_back(TAG_AUTH_TOKEN, authToken2HidlVec(*token));
   1021     }
   1022 }
   1023 
   1024 void KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, KeyPurpose purpose,
   1025                             bool pruneable, const hidl_vec<KeyParameter>& params,
   1026                             const hidl_vec<uint8_t>& entropy, int32_t uid,
   1027                             OperationResult* result) {
   1028     uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1029     uid_t targetUid = getEffectiveUid(uid);
   1030     if (!is_granted_to(callingUid, targetUid)) {
   1031         ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
   1032         result->resultCode = ResponseCode::PERMISSION_DENIED;
   1033         return;
   1034     }
   1035     if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
   1036         ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
   1037         result->resultCode = ResponseCode::PERMISSION_DENIED;
   1038         return;
   1039     }
   1040     if (!checkAllowedOperationParams(params)) {
   1041         result->resultCode = ErrorCode::INVALID_ARGUMENT;
   1042         return;
   1043     }
   1044     Blob keyBlob;
   1045     String8 name8(name);
   1046     result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
   1047     if (result->resultCode == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
   1048         result->resultCode = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
   1049     }
   1050     if (!result->resultCode.isOk()) {
   1051         return;
   1052     }
   1053 
   1054     auto key = blob2hidlVec(keyBlob);
   1055     auto& dev = mKeyStore->getDevice(keyBlob);
   1056     AuthorizationSet opParams = params;
   1057     KeyCharacteristics characteristics;
   1058     result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
   1059 
   1060     if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
   1061         result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
   1062         if (!result->resultCode.isOk()) {
   1063             return;
   1064         }
   1065         key = blob2hidlVec(keyBlob);
   1066         result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
   1067     }
   1068     if (!result->resultCode.isOk()) {
   1069         return;
   1070     }
   1071 
   1072     const HardwareAuthToken* authToken = NULL;
   1073 
   1074     // Merge these characteristics with the ones cached when the key was generated or imported
   1075     Blob charBlob;
   1076     AuthorizationSet persistedCharacteristics;
   1077     result->resultCode =
   1078         mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
   1079     if (result->resultCode.isOk()) {
   1080         // TODO write one shot stream buffer to avoid copying (twice here)
   1081         std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
   1082                                charBlob.getLength());
   1083         std::stringstream charStream(charBuffer);
   1084         persistedCharacteristics.Deserialize(&charStream);
   1085     } else {
   1086         ALOGD("Unable to read cached characteristics for key");
   1087     }
   1088 
   1089     // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
   1090     AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
   1091     AuthorizationSet teeEnforced = characteristics.teeEnforced;
   1092     persistedCharacteristics.Union(softwareEnforced);
   1093     persistedCharacteristics.Subtract(teeEnforced);
   1094     characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
   1095 
   1096     auto authResult = getAuthToken(characteristics, 0, purpose, &authToken,
   1097                                    /*failOnTokenMissing*/ false);
   1098     // If per-operation auth is needed we need to begin the operation and
   1099     // the client will need to authorize that operation before calling
   1100     // update. Any other auth issues stop here.
   1101     if (!authResult.isOk() && authResult != ResponseCode::OP_AUTH_NEEDED) {
   1102         result->resultCode = authResult;
   1103         return;
   1104     }
   1105 
   1106     addAuthTokenToParams(&opParams, authToken);
   1107 
   1108     // Add entropy to the device first.
   1109     if (entropy.size()) {
   1110         result->resultCode = addRngEntropy(entropy);
   1111         if (!result->resultCode.isOk()) {
   1112             return;
   1113         }
   1114     }
   1115 
   1116     // Create a keyid for this key.
   1117     km_id_t keyid;
   1118     if (!enforcement_policy.CreateKeyId(key, &keyid)) {
   1119         ALOGE("Failed to create a key ID for authorization checking.");
   1120         result->resultCode = ErrorCode::UNKNOWN_ERROR;
   1121         return;
   1122     }
   1123 
   1124     // Check that all key authorization policy requirements are met.
   1125     AuthorizationSet key_auths = characteristics.teeEnforced;
   1126     key_auths.append(&characteristics.softwareEnforced[0],
   1127                      &characteristics.softwareEnforced[characteristics.softwareEnforced.size()]);
   1128 
   1129     result->resultCode = enforcement_policy.AuthorizeOperation(
   1130         purpose, keyid, key_auths, opParams, 0 /* op_handle */, true /* is_begin_operation */);
   1131     if (!result->resultCode.isOk()) {
   1132         return;
   1133     }
   1134 
   1135     // If there are more than kMaxOperations, abort the oldest operation that was started as
   1136     // pruneable.
   1137     while (mOperationMap.getOperationCount() >= kMaxOperations) {
   1138         ALOGD("Reached or exceeded concurrent operations limit");
   1139         if (!pruneOperation()) {
   1140             break;
   1141         }
   1142     }
   1143 
   1144     auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
   1145                       uint64_t operationHandle) {
   1146         result->resultCode = ret;
   1147         if (!result->resultCode.isOk()) {
   1148             return;
   1149         }
   1150         result->handle = operationHandle;
   1151         result->outParams = outParams;
   1152     };
   1153 
   1154     ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
   1155     if (rc != ErrorCode::OK) {
   1156         ALOGW("Got error %d from begin()", rc);
   1157     }
   1158 
   1159     // If there are too many operations abort the oldest operation that was
   1160     // started as pruneable and try again.
   1161     while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
   1162         ALOGW("Ran out of operation handles");
   1163         if (!pruneOperation()) {
   1164             break;
   1165         }
   1166         rc = KS_HANDLE_HIDL_ERROR(dev->begin(purpose, key, opParams.hidl_data(), hidlCb));
   1167     }
   1168     if (rc != ErrorCode::OK) {
   1169         result->resultCode = rc;
   1170         return;
   1171     }
   1172 
   1173     // Note: The operation map takes possession of the contents of "characteristics".
   1174     // It is safe to use characteristics after the following line but it will be empty.
   1175     sp<IBinder> operationToken = mOperationMap.addOperation(
   1176         result->handle, keyid, purpose, dev, appToken, std::move(characteristics), pruneable);
   1177     assert(characteristics.teeEnforced.size() == 0);
   1178     assert(characteristics.softwareEnforced.size() == 0);
   1179     result->token = operationToken;
   1180 
   1181     if (authToken) {
   1182         mOperationMap.setOperationAuthToken(operationToken, authToken);
   1183     }
   1184     // Return the authentication lookup result. If this is a per operation
   1185     // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
   1186     // application should get an auth token using the handle before the
   1187     // first call to update, which will fail if keystore hasn't received the
   1188     // auth token.
   1189     if (result->resultCode == ErrorCode::OK) {
   1190         result->resultCode = authResult;
   1191     }
   1192 
   1193     // Other result fields were set in the begin operation's callback.
   1194 }
   1195 
   1196 void KeyStoreService::update(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
   1197                              const hidl_vec<uint8_t>& data, OperationResult* result) {
   1198     if (!checkAllowedOperationParams(params)) {
   1199         result->resultCode = ErrorCode::INVALID_ARGUMENT;
   1200         return;
   1201     }
   1202     km_device_t dev;
   1203     uint64_t handle;
   1204     KeyPurpose purpose;
   1205     km_id_t keyid;
   1206     const KeyCharacteristics* characteristics;
   1207     if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
   1208         result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
   1209         return;
   1210     }
   1211     AuthorizationSet opParams = params;
   1212     result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
   1213     if (!result->resultCode.isOk()) {
   1214         return;
   1215     }
   1216 
   1217     // Check that all key authorization policy requirements are met.
   1218     AuthorizationSet key_auths(characteristics->teeEnforced);
   1219     key_auths.append(&characteristics->softwareEnforced[0],
   1220                      &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
   1221     result->resultCode = enforcement_policy.AuthorizeOperation(
   1222         purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
   1223     if (!result->resultCode.isOk()) {
   1224         return;
   1225     }
   1226 
   1227     auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
   1228                       const hidl_vec<KeyParameter>& outParams, const hidl_vec<uint8_t>& output) {
   1229         result->resultCode = ret;
   1230         if (!result->resultCode.isOk()) {
   1231             return;
   1232         }
   1233         result->inputConsumed = inputConsumed;
   1234         result->outParams = outParams;
   1235         result->data = output;
   1236     };
   1237 
   1238     KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->update(handle, opParams.hidl_data(),
   1239                                                         data, hidlCb));
   1240     // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
   1241     // it if there was a communication error indicated by the ErrorCode.
   1242     if (!rc.isOk()) {
   1243         result->resultCode = rc;
   1244     }
   1245 }
   1246 
   1247 void KeyStoreService::finish(const sp<IBinder>& token, const hidl_vec<KeyParameter>& params,
   1248                              const hidl_vec<uint8_t>& signature, const hidl_vec<uint8_t>& entropy,
   1249                              OperationResult* result) {
   1250     if (!checkAllowedOperationParams(params)) {
   1251         result->resultCode = ErrorCode::INVALID_ARGUMENT;
   1252         return;
   1253     }
   1254     km_device_t dev;
   1255     uint64_t handle;
   1256     KeyPurpose purpose;
   1257     km_id_t keyid;
   1258     const KeyCharacteristics* characteristics;
   1259     if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
   1260         result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
   1261         return;
   1262     }
   1263     AuthorizationSet opParams = params;
   1264     result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
   1265     if (!result->resultCode.isOk()) {
   1266         return;
   1267     }
   1268 
   1269     if (entropy.size()) {
   1270         result->resultCode = addRngEntropy(entropy);
   1271         if (!result->resultCode.isOk()) {
   1272             return;
   1273         }
   1274     }
   1275 
   1276     // Check that all key authorization policy requirements are met.
   1277     AuthorizationSet key_auths(characteristics->teeEnforced);
   1278     key_auths.append(&characteristics->softwareEnforced[0],
   1279                      &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
   1280     result->resultCode = enforcement_policy.AuthorizeOperation(
   1281         purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
   1282     if (!result->resultCode.isOk()) return;
   1283 
   1284     auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
   1285                       const hidl_vec<uint8_t>& output) {
   1286         result->resultCode = ret;
   1287         if (!result->resultCode.isOk()) {
   1288             return;
   1289         }
   1290         result->outParams = outParams;
   1291         result->data = output;
   1292     };
   1293 
   1294     KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(dev->finish(
   1295         handle, opParams.hidl_data(),
   1296         hidl_vec<uint8_t>() /* TODO(swillden): wire up input to finish() */, signature, hidlCb));
   1297     // Remove the operation regardless of the result
   1298     mOperationMap.removeOperation(token);
   1299     mAuthTokenTable.MarkCompleted(handle);
   1300 
   1301     // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
   1302     // it if there was a communication error indicated by the ErrorCode.
   1303     if (!rc.isOk()) {
   1304         result->resultCode = rc;
   1305     }
   1306 }
   1307 
   1308 KeyStoreServiceReturnCode KeyStoreService::abort(const sp<IBinder>& token) {
   1309     km_device_t dev;
   1310     uint64_t handle;
   1311     KeyPurpose purpose;
   1312     km_id_t keyid;
   1313     if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
   1314         return ErrorCode::INVALID_OPERATION_HANDLE;
   1315     }
   1316     mOperationMap.removeOperation(token);
   1317 
   1318     ErrorCode rc = KS_HANDLE_HIDL_ERROR(dev->abort(handle));
   1319     mAuthTokenTable.MarkCompleted(handle);
   1320     return rc;
   1321 }
   1322 
   1323 bool KeyStoreService::isOperationAuthorized(const sp<IBinder>& token) {
   1324     km_device_t dev;
   1325     uint64_t handle;
   1326     const KeyCharacteristics* characteristics;
   1327     KeyPurpose purpose;
   1328     km_id_t keyid;
   1329     if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
   1330         return false;
   1331     }
   1332     const HardwareAuthToken* authToken = NULL;
   1333     mOperationMap.getOperationAuthToken(token, &authToken);
   1334     AuthorizationSet ignored;
   1335     auto authResult = addOperationAuthTokenIfNeeded(token, &ignored);
   1336     return authResult.isOk();
   1337 }
   1338 
   1339 KeyStoreServiceReturnCode KeyStoreService::addAuthToken(const uint8_t* token, size_t length) {
   1340     // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
   1341     // receive a HardwareAuthToken, rather than an opaque byte array.
   1342 
   1343     if (!checkBinderPermission(P_ADD_AUTH)) {
   1344         ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
   1345         return ResponseCode::PERMISSION_DENIED;
   1346     }
   1347     if (length != sizeof(hw_auth_token_t)) {
   1348         return ErrorCode::INVALID_ARGUMENT;
   1349     }
   1350 
   1351     hw_auth_token_t authToken;
   1352     memcpy(reinterpret_cast<void*>(&authToken), token, sizeof(hw_auth_token_t));
   1353     if (authToken.version != 0) {
   1354         return ErrorCode::INVALID_ARGUMENT;
   1355     }
   1356 
   1357     std::unique_ptr<HardwareAuthToken> hidlAuthToken(new HardwareAuthToken);
   1358     hidlAuthToken->challenge = authToken.challenge;
   1359     hidlAuthToken->userId = authToken.user_id;
   1360     hidlAuthToken->authenticatorId = authToken.authenticator_id;
   1361     hidlAuthToken->authenticatorType = authToken.authenticator_type;
   1362     hidlAuthToken->timestamp = authToken.timestamp;
   1363     static_assert(
   1364         std::is_same<decltype(hidlAuthToken->hmac),
   1365                      ::android::hardware::hidl_array<uint8_t, sizeof(authToken.hmac)>>::value,
   1366         "This function assumes token HMAC is 32 bytes, but it might not be.");
   1367     std::copy(authToken.hmac, authToken.hmac + sizeof(authToken.hmac), hidlAuthToken->hmac.data());
   1368 
   1369     // The table takes ownership of authToken.
   1370     mAuthTokenTable.AddAuthenticationToken(hidlAuthToken.release());
   1371     return ResponseCode::NO_ERROR;
   1372 }
   1373 
   1374 bool isDeviceIdAttestationRequested(const hidl_vec<KeyParameter>& params) {
   1375     for (size_t i = 0; i < params.size(); ++i) {
   1376         switch (params[i].tag) {
   1377         case Tag::ATTESTATION_ID_BRAND:
   1378         case Tag::ATTESTATION_ID_DEVICE:
   1379         case Tag::ATTESTATION_ID_IMEI:
   1380         case Tag::ATTESTATION_ID_MANUFACTURER:
   1381         case Tag::ATTESTATION_ID_MEID:
   1382         case Tag::ATTESTATION_ID_MODEL:
   1383         case Tag::ATTESTATION_ID_PRODUCT:
   1384         case Tag::ATTESTATION_ID_SERIAL:
   1385             return true;
   1386         default:
   1387             break;
   1388         }
   1389     }
   1390     return false;
   1391 }
   1392 
   1393 KeyStoreServiceReturnCode KeyStoreService::attestKey(const String16& name,
   1394                                                      const hidl_vec<KeyParameter>& params,
   1395                                                      hidl_vec<hidl_vec<uint8_t>>* outChain) {
   1396     if (!outChain) {
   1397         return ErrorCode::OUTPUT_PARAMETER_NULL;
   1398     }
   1399 
   1400     if (!checkAllowedOperationParams(params)) {
   1401         return ErrorCode::INVALID_ARGUMENT;
   1402     }
   1403 
   1404     if (isDeviceIdAttestationRequested(params)) {
   1405         // There is a dedicated attestDeviceIds() method for device ID attestation.
   1406         return ErrorCode::INVALID_ARGUMENT;
   1407     }
   1408 
   1409     uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1410 
   1411     AuthorizationSet mutableParams = params;
   1412     KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
   1413     if (!rc.isOk()) {
   1414         return rc;
   1415     }
   1416 
   1417     Blob keyBlob;
   1418     String8 name8(name);
   1419     rc = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
   1420     if (!rc.isOk()) {
   1421         return rc;
   1422     }
   1423 
   1424     KeyStoreServiceReturnCode error;
   1425     auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
   1426         error = ret;
   1427         if (!error.isOk()) {
   1428             return;
   1429         }
   1430         if (outChain) *outChain = certChain;
   1431     };
   1432 
   1433     auto hidlKey = blob2hidlVec(keyBlob);
   1434     auto& dev = mKeyStore->getDevice(keyBlob);
   1435     rc = KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
   1436     if (!rc.isOk()) {
   1437         return rc;
   1438     }
   1439     return error;
   1440 }
   1441 
   1442 KeyStoreServiceReturnCode KeyStoreService::attestDeviceIds(const hidl_vec<KeyParameter>& params,
   1443                                                            hidl_vec<hidl_vec<uint8_t>>* outChain) {
   1444     if (!outChain) {
   1445         return ErrorCode::OUTPUT_PARAMETER_NULL;
   1446     }
   1447 
   1448     if (!checkAllowedOperationParams(params)) {
   1449         return ErrorCode::INVALID_ARGUMENT;
   1450     }
   1451 
   1452     if (!isDeviceIdAttestationRequested(params)) {
   1453         // There is an attestKey() method for attesting keys without device ID attestation.
   1454         return ErrorCode::INVALID_ARGUMENT;
   1455     }
   1456 
   1457     uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1458     sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
   1459     if (binder == 0) {
   1460         return ErrorCode::CANNOT_ATTEST_IDS;
   1461     }
   1462     if (!interface_cast<IPermissionController>(binder)->checkPermission(
   1463             String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
   1464             IPCThreadState::self()->getCallingPid(), callingUid)) {
   1465         return ErrorCode::CANNOT_ATTEST_IDS;
   1466     }
   1467 
   1468     AuthorizationSet mutableParams = params;
   1469     KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
   1470     if (!rc.isOk()) {
   1471         return rc;
   1472     }
   1473 
   1474     // Generate temporary key.
   1475     auto& dev = mKeyStore->getDevice();
   1476     KeyStoreServiceReturnCode error;
   1477     hidl_vec<uint8_t> hidlKey;
   1478 
   1479     AuthorizationSet keyCharacteristics;
   1480     keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
   1481     keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
   1482     keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
   1483     keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
   1484     keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
   1485     auto generateHidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& hidlKeyBlob,
   1486                               const KeyCharacteristics&) {
   1487         error = ret;
   1488         if (!error.isOk()) {
   1489             return;
   1490         }
   1491         hidlKey = hidlKeyBlob;
   1492     };
   1493 
   1494     rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(keyCharacteristics.hidl_data(), generateHidlCb));
   1495     if (!rc.isOk()) {
   1496         return rc;
   1497     }
   1498     if (!error.isOk()) {
   1499         return error;
   1500     }
   1501 
   1502     // Attest key and device IDs.
   1503     auto attestHidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
   1504         error = ret;
   1505         if (!error.isOk()) {
   1506             return;
   1507         }
   1508         *outChain = certChain;
   1509     };
   1510     KeyStoreServiceReturnCode attestationRc =
   1511             KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), attestHidlCb));
   1512 
   1513     // Delete temporary key.
   1514     KeyStoreServiceReturnCode deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
   1515 
   1516     if (!attestationRc.isOk()) {
   1517         return attestationRc;
   1518     }
   1519     if (!error.isOk()) {
   1520         return error;
   1521     }
   1522     return deletionRc;
   1523 }
   1524 
   1525 KeyStoreServiceReturnCode KeyStoreService::onDeviceOffBody() {
   1526     // TODO(tuckeris): add permission check.  This should be callable from ClockworkHome only.
   1527     mAuthTokenTable.onDeviceOffBody();
   1528     return ResponseCode::NO_ERROR;
   1529 }
   1530 
   1531 /**
   1532  * Prune the oldest pruneable operation.
   1533  */
   1534 bool KeyStoreService::pruneOperation() {
   1535     sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
   1536     ALOGD("Trying to prune operation %p", oldest.get());
   1537     size_t op_count_before_abort = mOperationMap.getOperationCount();
   1538     // We mostly ignore errors from abort() because all we care about is whether at least
   1539     // one operation has been removed.
   1540     int abort_error = abort(oldest);
   1541     if (mOperationMap.getOperationCount() >= op_count_before_abort) {
   1542         ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
   1543         return false;
   1544     }
   1545     return true;
   1546 }
   1547 
   1548 /**
   1549  * Get the effective target uid for a binder operation that takes an
   1550  * optional uid as the target.
   1551  */
   1552 uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
   1553     if (targetUid == UID_SELF) {
   1554         return IPCThreadState::self()->getCallingUid();
   1555     }
   1556     return static_cast<uid_t>(targetUid);
   1557 }
   1558 
   1559 /**
   1560  * Check if the caller of the current binder method has the required
   1561  * permission and if acting on other uids the grants to do so.
   1562  */
   1563 bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
   1564     uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1565     pid_t spid = IPCThreadState::self()->getCallingPid();
   1566     if (!has_permission(callingUid, permission, spid)) {
   1567         ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
   1568         return false;
   1569     }
   1570     if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
   1571         ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
   1572         return false;
   1573     }
   1574     return true;
   1575 }
   1576 
   1577 /**
   1578  * Check if the caller of the current binder method has the required
   1579  * permission and the target uid is the caller or the caller is system.
   1580  */
   1581 bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
   1582     uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1583     pid_t spid = IPCThreadState::self()->getCallingPid();
   1584     if (!has_permission(callingUid, permission, spid)) {
   1585         ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
   1586         return false;
   1587     }
   1588     return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
   1589 }
   1590 
   1591 /**
   1592  * Check if the caller of the current binder method has the required
   1593  * permission or the target of the operation is the caller's uid. This is
   1594  * for operation where the permission is only for cross-uid activity and all
   1595  * uids are allowed to act on their own (ie: clearing all entries for a
   1596  * given uid).
   1597  */
   1598 bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
   1599     uid_t callingUid = IPCThreadState::self()->getCallingUid();
   1600     if (getEffectiveUid(targetUid) == callingUid) {
   1601         return true;
   1602     } else {
   1603         return checkBinderPermission(permission, targetUid);
   1604     }
   1605 }
   1606 
   1607 /**
   1608  * Helper method to check that the caller has the required permission as
   1609  * well as the keystore is in the unlocked state if checkUnlocked is true.
   1610  *
   1611  * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
   1612  * otherwise the state of keystore when not unlocked and checkUnlocked is
   1613  * true.
   1614  */
   1615 KeyStoreServiceReturnCode
   1616 KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
   1617                                                        bool checkUnlocked) {
   1618     if (!checkBinderPermission(permission, targetUid)) {
   1619         return ResponseCode::PERMISSION_DENIED;
   1620     }
   1621     State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
   1622     if (checkUnlocked && !isKeystoreUnlocked(state)) {
   1623         // All State values coincide with ResponseCodes
   1624         return static_cast<ResponseCode>(state);
   1625     }
   1626 
   1627     return ResponseCode::NO_ERROR;
   1628 }
   1629 
   1630 bool KeyStoreService::isKeystoreUnlocked(State state) {
   1631     switch (state) {
   1632     case ::STATE_NO_ERROR:
   1633         return true;
   1634     case ::STATE_UNINITIALIZED:
   1635     case ::STATE_LOCKED:
   1636         return false;
   1637     }
   1638     return false;
   1639 }
   1640 
   1641 /**
   1642  * Check that all KeyParameter's provided by the application are
   1643  * allowed. Any parameter that keystore adds itself should be disallowed here.
   1644  */
   1645 bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
   1646     for (size_t i = 0; i < params.size(); ++i) {
   1647         switch (params[i].tag) {
   1648         case Tag::ATTESTATION_APPLICATION_ID:
   1649         case Tag::AUTH_TOKEN:
   1650         case Tag::RESET_SINCE_ID_ROTATION:
   1651             return false;
   1652         default:
   1653             break;
   1654         }
   1655     }
   1656     return true;
   1657 }
   1658 
   1659 ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
   1660                                                        km_device_t* dev,
   1661                                                        const AuthorizationSet& params,
   1662                                                        KeyCharacteristics* out) {
   1663     hidl_vec<uint8_t> appId;
   1664     hidl_vec<uint8_t> appData;
   1665     for (auto param : params) {
   1666         if (param.tag == Tag::APPLICATION_ID) {
   1667             appId = authorizationValue(TAG_APPLICATION_ID, param).value();
   1668         } else if (param.tag == Tag::APPLICATION_DATA) {
   1669             appData = authorizationValue(TAG_APPLICATION_DATA, param).value();
   1670         }
   1671     }
   1672     ErrorCode error = ErrorCode::OK;
   1673 
   1674     auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
   1675         error = ret;
   1676         if (error != ErrorCode::OK) {
   1677             return;
   1678         }
   1679         if (out) *out = keyCharacteristics;
   1680     };
   1681 
   1682     ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appData, hidlCb));
   1683     if (rc != ErrorCode::OK) {
   1684         return rc;
   1685     }
   1686     return error;
   1687 }
   1688 
   1689 /**
   1690  * Get the auth token for this operation from the auth token table.
   1691  *
   1692  * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
   1693  *         ::OP_AUTH_NEEDED if it is a per op authorization, no
   1694  *         authorization token exists for that operation and
   1695  *         failOnTokenMissing is false.
   1696  *         KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
   1697  *         token for the operation
   1698  */
   1699 KeyStoreServiceReturnCode KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics,
   1700                                                         uint64_t handle, KeyPurpose purpose,
   1701                                                         const HardwareAuthToken** authToken,
   1702                                                         bool failOnTokenMissing) {
   1703 
   1704     AuthorizationSet allCharacteristics;
   1705     for (size_t i = 0; i < characteristics.softwareEnforced.size(); i++) {
   1706         allCharacteristics.push_back(characteristics.softwareEnforced[i]);
   1707     }
   1708     for (size_t i = 0; i < characteristics.teeEnforced.size(); i++) {
   1709         allCharacteristics.push_back(characteristics.teeEnforced[i]);
   1710     }
   1711     AuthTokenTable::Error err =
   1712         mAuthTokenTable.FindAuthorization(allCharacteristics, purpose, handle, authToken);
   1713     switch (err) {
   1714     case AuthTokenTable::OK:
   1715     case AuthTokenTable::AUTH_NOT_REQUIRED:
   1716         return ResponseCode::NO_ERROR;
   1717     case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
   1718     case AuthTokenTable::AUTH_TOKEN_EXPIRED:
   1719     case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
   1720         ALOGE("getAuthToken failed: %d", err); //STOPSHIP: debug only, to be removed
   1721         return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
   1722     case AuthTokenTable::OP_HANDLE_REQUIRED:
   1723         return failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
   1724                                   : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
   1725     default:
   1726         ALOGE("Unexpected FindAuthorization return value %d", err);
   1727         return ErrorCode::INVALID_ARGUMENT;
   1728     }
   1729 }
   1730 
   1731 /**
   1732  * Add the auth token for the operation to the param list if the operation
   1733  * requires authorization. Uses the cached result in the OperationMap if available
   1734  * otherwise gets the token from the AuthTokenTable and caches the result.
   1735  *
   1736  * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
   1737  *         KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
   1738  *         authenticated.
   1739  *         KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
   1740  *         operation token.
   1741  */
   1742 KeyStoreServiceReturnCode KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
   1743                                                                          AuthorizationSet* params) {
   1744     const HardwareAuthToken* authToken = nullptr;
   1745     mOperationMap.getOperationAuthToken(token, &authToken);
   1746     if (!authToken) {
   1747         km_device_t dev;
   1748         uint64_t handle;
   1749         const KeyCharacteristics* characteristics = nullptr;
   1750         KeyPurpose purpose;
   1751         km_id_t keyid;
   1752         if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
   1753             return ErrorCode::INVALID_OPERATION_HANDLE;
   1754         }
   1755         auto result = getAuthToken(*characteristics, handle, purpose, &authToken);
   1756         if (!result.isOk()) {
   1757             return result;
   1758         }
   1759         if (authToken) {
   1760             mOperationMap.setOperationAuthToken(token, authToken);
   1761         }
   1762     }
   1763     addAuthTokenToParams(params, authToken);
   1764     return ResponseCode::NO_ERROR;
   1765 }
   1766 
   1767 /**
   1768  * Translate a result value to a legacy return value. All keystore errors are
   1769  * preserved and keymaster errors become SYSTEM_ERRORs
   1770  */
   1771 KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
   1772     if (result > 0) {
   1773         return static_cast<ResponseCode>(result);
   1774     }
   1775     return ResponseCode::SYSTEM_ERROR;
   1776 }
   1777 
   1778 static NullOr<const Algorithm&>
   1779 getKeyAlgoritmFromKeyCharacteristics(const KeyCharacteristics& characteristics) {
   1780     for (size_t i = 0; i < characteristics.teeEnforced.size(); ++i) {
   1781         auto algo = authorizationValue(TAG_ALGORITHM, characteristics.teeEnforced[i]);
   1782         if (algo.isOk()) return algo.value();
   1783     }
   1784     for (size_t i = 0; i < characteristics.softwareEnforced.size(); ++i) {
   1785         auto algo = authorizationValue(TAG_ALGORITHM, characteristics.softwareEnforced[i]);
   1786         if (algo.isOk()) return algo.value();
   1787     }
   1788     return {};
   1789 }
   1790 
   1791 void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
   1792     // All legacy keys are DIGEST_NONE/PAD_NONE.
   1793     params->push_back(TAG_DIGEST, Digest::NONE);
   1794     params->push_back(TAG_PADDING, PaddingMode::NONE);
   1795 
   1796     // Look up the algorithm of the key.
   1797     KeyCharacteristics characteristics;
   1798     auto rc = getKeyCharacteristics(name, hidl_vec<uint8_t>(), hidl_vec<uint8_t>(), UID_SELF,
   1799                                     &characteristics);
   1800     if (!rc.isOk()) {
   1801         ALOGE("Failed to get key characteristics");
   1802         return;
   1803     }
   1804     auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
   1805     if (!algorithm.isOk()) {
   1806         ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
   1807         return;
   1808     }
   1809     params->push_back(TAG_ALGORITHM, algorithm.value());
   1810 }
   1811 
   1812 KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
   1813                                                               const hidl_vec<uint8_t>& data,
   1814                                                               hidl_vec<uint8_t>* out,
   1815                                                               const hidl_vec<uint8_t>& signature,
   1816                                                               KeyPurpose purpose) {
   1817 
   1818     std::basic_stringstream<uint8_t> outBuffer;
   1819     OperationResult result;
   1820     AuthorizationSet inArgs;
   1821     addLegacyBeginParams(name, &inArgs);
   1822     sp<IBinder> appToken(new BBinder);
   1823     sp<IBinder> token;
   1824 
   1825     begin(appToken, name, purpose, true, inArgs.hidl_data(), hidl_vec<uint8_t>(), UID_SELF,
   1826           &result);
   1827     if (!result.resultCode.isOk()) {
   1828         if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
   1829             ALOGW("Key not found");
   1830         } else {
   1831             ALOGW("Error in begin: %d", int32_t(result.resultCode));
   1832         }
   1833         return translateResultToLegacyResult(result.resultCode);
   1834     }
   1835     inArgs.Clear();
   1836     token = result.token;
   1837     size_t consumed = 0;
   1838     size_t lastConsumed = 0;
   1839     hidl_vec<uint8_t> data_view;
   1840     do {
   1841         data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
   1842         update(token, inArgs.hidl_data(), data_view, &result);
   1843         if (result.resultCode != ResponseCode::NO_ERROR) {
   1844             ALOGW("Error in update: %d", int32_t(result.resultCode));
   1845             return translateResultToLegacyResult(result.resultCode);
   1846         }
   1847         if (out) {
   1848             outBuffer.write(&result.data[0], result.data.size());
   1849         }
   1850         lastConsumed = result.inputConsumed;
   1851         consumed += lastConsumed;
   1852     } while (consumed < data.size() && lastConsumed > 0);
   1853 
   1854     if (consumed != data.size()) {
   1855         ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
   1856         return ResponseCode::SYSTEM_ERROR;
   1857     }
   1858 
   1859     finish(token, inArgs.hidl_data(), signature, hidl_vec<uint8_t>(), &result);
   1860     if (result.resultCode != ResponseCode::NO_ERROR) {
   1861         ALOGW("Error in finish: %d", int32_t(result.resultCode));
   1862         return translateResultToLegacyResult(result.resultCode);
   1863     }
   1864     if (out) {
   1865         outBuffer.write(&result.data[0], result.data.size());
   1866     }
   1867 
   1868     if (out) {
   1869         auto buf = outBuffer.str();
   1870         out->resize(buf.size());
   1871         memcpy(&(*out)[0], buf.data(), out->size());
   1872     }
   1873 
   1874     return ResponseCode::NO_ERROR;
   1875 }
   1876 
   1877 KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
   1878                                                           const AuthorizationSet& params,
   1879                                                           Blob* blob) {
   1880     // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
   1881     String8 name8(name);
   1882     ResponseCode responseCode = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
   1883     if (responseCode != ResponseCode::NO_ERROR) {
   1884         return responseCode;
   1885     }
   1886     ALOGI("upgradeKeyBlob %s %d", name8.string(), uid);
   1887 
   1888     auto hidlKey = blob2hidlVec(*blob);
   1889     auto& dev = mKeyStore->getDevice(*blob);
   1890 
   1891     KeyStoreServiceReturnCode error;
   1892     auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& upgradedKeyBlob) {
   1893         error = ret;
   1894         if (!error.isOk()) {
   1895             return;
   1896         }
   1897 
   1898         auto filename = mKeyStore->getBlobFileNameIfExists(name8, uid, ::TYPE_KEYMASTER_10);
   1899         if (!filename.isOk()) {
   1900             ALOGI("trying to upgrade a non existing blob");
   1901             return;
   1902         }
   1903         error = mKeyStore->del(filename.value().string(), ::TYPE_ANY, get_user_id(uid));
   1904         if (!error.isOk()) {
   1905             ALOGI("upgradeKeyBlob keystore->del failed %d", (int)error);
   1906             return;
   1907         }
   1908 
   1909         Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
   1910                      0 /* infoLength */, ::TYPE_KEYMASTER_10);
   1911         newBlob.setFallback(blob->isFallback());
   1912         newBlob.setEncrypted(blob->isEncrypted());
   1913         newBlob.setSuperEncrypted(blob->isSuperEncrypted());
   1914         newBlob.setCriticalToDeviceEncryption(blob->isCriticalToDeviceEncryption());
   1915 
   1916         error = mKeyStore->put(filename.value().string(), &newBlob, get_user_id(uid));
   1917         if (!error.isOk()) {
   1918             ALOGI("upgradeKeyBlob keystore->put failed %d", (int)error);
   1919             return;
   1920         }
   1921 
   1922         // Re-read blob for caller.  We can't use newBlob because writing it modified it.
   1923         error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
   1924     };
   1925 
   1926     KeyStoreServiceReturnCode rc =
   1927         KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
   1928     if (!rc.isOk()) {
   1929         return rc;
   1930     }
   1931 
   1932     return error;
   1933 }
   1934 
   1935 }  // namespace keystore
   1936