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