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