1 /* 2 * Copyright (C) 2014 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 <keymaster/keymaster_enforcement.h> 18 19 #include <assert.h> 20 #include <limits.h> 21 #include <string.h> 22 23 #include <openssl/evp.h> 24 25 #include <hardware/hw_auth_token.h> 26 #include <keymaster/android_keymaster_utils.h> 27 #include <keymaster/logger.h> 28 #include <keymaster/List.h> 29 30 namespace keymaster { 31 32 class AccessTimeMap { 33 public: 34 explicit AccessTimeMap(uint32_t max_size) : max_size_(max_size) {} 35 36 /* If the key is found, returns true and fills \p last_access_time. If not found returns 37 * false. */ 38 bool LastKeyAccessTime(km_id_t keyid, uint32_t* last_access_time) const; 39 40 /* Updates the last key access time with the currentTime parameter. Adds the key if 41 * needed, returning false if key cannot be added because list is full. */ 42 bool UpdateKeyAccessTime(km_id_t keyid, uint32_t current_time, uint32_t timeout); 43 44 private: 45 struct AccessTime { 46 km_id_t keyid; 47 uint32_t access_time; 48 uint32_t timeout; 49 }; 50 List<AccessTime> last_access_list_; 51 const uint32_t max_size_; 52 }; 53 54 class AccessCountMap { 55 public: 56 explicit AccessCountMap(uint32_t max_size) : max_size_(max_size) {} 57 58 /* If the key is found, returns true and fills \p count. If not found returns 59 * false. */ 60 bool KeyAccessCount(km_id_t keyid, uint32_t* count) const; 61 62 /* Increments key access count, adding an entry if the key has never been used. Returns 63 * false if the list has reached maximum size. */ 64 bool IncrementKeyAccessCount(km_id_t keyid); 65 66 private: 67 struct AccessCount { 68 km_id_t keyid; 69 uint64_t access_count; 70 }; 71 List<AccessCount> access_count_list_; 72 const uint32_t max_size_; 73 }; 74 75 bool is_public_key_algorithm(const AuthProxy& auth_set) { 76 keymaster_algorithm_t algorithm; 77 return auth_set.GetTagValue(TAG_ALGORITHM, &algorithm) && 78 (algorithm == KM_ALGORITHM_RSA || algorithm == KM_ALGORITHM_EC); 79 } 80 81 static keymaster_error_t authorized_purpose(const keymaster_purpose_t purpose, 82 const AuthProxy& auth_set) { 83 switch (purpose) { 84 case KM_PURPOSE_VERIFY: 85 case KM_PURPOSE_ENCRYPT: 86 case KM_PURPOSE_SIGN: 87 case KM_PURPOSE_DECRYPT: 88 case KM_PURPOSE_WRAP: 89 if (auth_set.Contains(TAG_PURPOSE, purpose)) 90 return KM_ERROR_OK; 91 return KM_ERROR_INCOMPATIBLE_PURPOSE; 92 93 default: 94 return KM_ERROR_UNSUPPORTED_PURPOSE; 95 } 96 } 97 98 inline bool is_origination_purpose(keymaster_purpose_t purpose) { 99 return purpose == KM_PURPOSE_ENCRYPT || purpose == KM_PURPOSE_SIGN; 100 } 101 102 inline bool is_usage_purpose(keymaster_purpose_t purpose) { 103 return purpose == KM_PURPOSE_DECRYPT || purpose == KM_PURPOSE_VERIFY; 104 } 105 106 KeymasterEnforcement::KeymasterEnforcement(uint32_t max_access_time_map_size, 107 uint32_t max_access_count_map_size) 108 : access_time_map_(new (std::nothrow) AccessTimeMap(max_access_time_map_size)), 109 access_count_map_(new (std::nothrow) AccessCountMap(max_access_count_map_size)) {} 110 111 KeymasterEnforcement::~KeymasterEnforcement() { 112 delete access_time_map_; 113 delete access_count_map_; 114 } 115 116 keymaster_error_t KeymasterEnforcement::AuthorizeOperation(const keymaster_purpose_t purpose, 117 const km_id_t keyid, 118 const AuthProxy& auth_set, 119 const AuthorizationSet& operation_params, 120 keymaster_operation_handle_t op_handle, 121 bool is_begin_operation) { 122 if (is_public_key_algorithm(auth_set)) { 123 switch (purpose) { 124 case KM_PURPOSE_ENCRYPT: 125 case KM_PURPOSE_VERIFY: 126 /* Public key operations are always authorized. */ 127 return KM_ERROR_OK; 128 129 case KM_PURPOSE_DECRYPT: 130 case KM_PURPOSE_SIGN: 131 case KM_PURPOSE_DERIVE_KEY: 132 case KM_PURPOSE_WRAP: 133 break; 134 }; 135 }; 136 137 if (is_begin_operation) 138 return AuthorizeBegin(purpose, keyid, auth_set, operation_params); 139 else 140 return AuthorizeUpdateOrFinish(auth_set, operation_params, op_handle); 141 } 142 143 // For update and finish the only thing to check is user authentication, and then only if it's not 144 // timeout-based. 145 keymaster_error_t 146 KeymasterEnforcement::AuthorizeUpdateOrFinish(const AuthProxy& auth_set, 147 const AuthorizationSet& operation_params, 148 keymaster_operation_handle_t op_handle) { 149 int auth_type_index = -1; 150 for (size_t pos = 0; pos < auth_set.size(); ++pos) { 151 switch (auth_set[pos].tag) { 152 case KM_TAG_NO_AUTH_REQUIRED: 153 case KM_TAG_AUTH_TIMEOUT: 154 // If no auth is required or if auth is timeout-based, we have nothing to check. 155 return KM_ERROR_OK; 156 157 case KM_TAG_USER_AUTH_TYPE: 158 auth_type_index = pos; 159 break; 160 161 default: 162 break; 163 } 164 } 165 166 // Note that at this point we should be able to assume that authentication is required, because 167 // authentication is required if KM_TAG_NO_AUTH_REQUIRED is absent. However, there are legacy 168 // keys which have no authentication-related tags, so we assume that absence is equivalent to 169 // presence of KM_TAG_NO_AUTH_REQUIRED. 170 // 171 // So, if we found KM_TAG_USER_AUTH_TYPE or if we find KM_TAG_USER_SECURE_ID then authentication 172 // is required. If we find neither, then we assume authentication is not required and return 173 // success. 174 bool authentication_required = (auth_type_index != -1); 175 for (auto& param : auth_set) { 176 if (param.tag == KM_TAG_USER_SECURE_ID) { 177 authentication_required = true; 178 int auth_timeout_index = -1; 179 if (AuthTokenMatches(auth_set, operation_params, param.long_integer, auth_type_index, 180 auth_timeout_index, op_handle, false /* is_begin_operation */)) 181 return KM_ERROR_OK; 182 } 183 } 184 185 if (authentication_required) { 186 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED; 187 } 188 189 return KM_ERROR_OK; 190 } 191 192 keymaster_error_t KeymasterEnforcement::AuthorizeBegin(const keymaster_purpose_t purpose, 193 const km_id_t keyid, 194 const AuthProxy& auth_set, 195 const AuthorizationSet& operation_params) { 196 // Find some entries that may be needed to handle KM_TAG_USER_SECURE_ID 197 int auth_timeout_index = -1; 198 int auth_type_index = -1; 199 int no_auth_required_index = -1; 200 for (size_t pos = 0; pos < auth_set.size(); ++pos) { 201 switch (auth_set[pos].tag) { 202 case KM_TAG_AUTH_TIMEOUT: 203 auth_timeout_index = pos; 204 break; 205 case KM_TAG_USER_AUTH_TYPE: 206 auth_type_index = pos; 207 break; 208 case KM_TAG_NO_AUTH_REQUIRED: 209 no_auth_required_index = pos; 210 break; 211 default: 212 break; 213 } 214 } 215 216 keymaster_error_t error = authorized_purpose(purpose, auth_set); 217 if (error != KM_ERROR_OK) 218 return error; 219 220 // If successful, and if key has a min time between ops, this will be set to the time limit 221 uint32_t min_ops_timeout = UINT32_MAX; 222 223 bool update_access_count = false; 224 bool caller_nonce_authorized_by_key = false; 225 bool authentication_required = false; 226 bool auth_token_matched = false; 227 228 for (auto& param : auth_set) { 229 230 // KM_TAG_PADDING_OLD and KM_TAG_DIGEST_OLD aren't actually members of the enum, so we can't 231 // switch on them. There's nothing to validate for them, though, so just ignore them. 232 if (param.tag == KM_TAG_PADDING_OLD || param.tag == KM_TAG_DIGEST_OLD) 233 continue; 234 235 switch (param.tag) { 236 237 case KM_TAG_ACTIVE_DATETIME: 238 if (!activation_date_valid(param.date_time)) 239 return KM_ERROR_KEY_NOT_YET_VALID; 240 break; 241 242 case KM_TAG_ORIGINATION_EXPIRE_DATETIME: 243 if (is_origination_purpose(purpose) && expiration_date_passed(param.date_time)) 244 return KM_ERROR_KEY_EXPIRED; 245 break; 246 247 case KM_TAG_USAGE_EXPIRE_DATETIME: 248 if (is_usage_purpose(purpose) && expiration_date_passed(param.date_time)) 249 return KM_ERROR_KEY_EXPIRED; 250 break; 251 252 case KM_TAG_MIN_SECONDS_BETWEEN_OPS: 253 min_ops_timeout = param.integer; 254 if (!MinTimeBetweenOpsPassed(min_ops_timeout, keyid)) 255 return KM_ERROR_KEY_RATE_LIMIT_EXCEEDED; 256 break; 257 258 case KM_TAG_MAX_USES_PER_BOOT: 259 update_access_count = true; 260 if (!MaxUsesPerBootNotExceeded(keyid, param.integer)) 261 return KM_ERROR_KEY_MAX_OPS_EXCEEDED; 262 break; 263 264 case KM_TAG_USER_SECURE_ID: 265 if (no_auth_required_index != -1) { 266 // Key has both KM_TAG_USER_SECURE_ID and KM_TAG_NO_AUTH_REQUIRED 267 return KM_ERROR_INVALID_KEY_BLOB; 268 } 269 270 if (auth_timeout_index != -1) { 271 authentication_required = true; 272 if (AuthTokenMatches(auth_set, operation_params, param.long_integer, 273 auth_type_index, auth_timeout_index, 0 /* op_handle */, 274 true /* is_begin_operation */)) 275 auth_token_matched = true; 276 } 277 break; 278 279 case KM_TAG_CALLER_NONCE: 280 caller_nonce_authorized_by_key = true; 281 break; 282 283 /* Tags should never be in key auths. */ 284 case KM_TAG_INVALID: 285 case KM_TAG_AUTH_TOKEN: 286 case KM_TAG_ROOT_OF_TRUST: 287 case KM_TAG_APPLICATION_DATA: 288 case KM_TAG_ATTESTATION_CHALLENGE: 289 case KM_TAG_ATTESTATION_APPLICATION_ID: 290 case KM_TAG_ATTESTATION_ID_BRAND: 291 case KM_TAG_ATTESTATION_ID_DEVICE: 292 case KM_TAG_ATTESTATION_ID_PRODUCT: 293 case KM_TAG_ATTESTATION_ID_SERIAL: 294 case KM_TAG_ATTESTATION_ID_IMEI: 295 case KM_TAG_ATTESTATION_ID_MEID: 296 case KM_TAG_ATTESTATION_ID_MANUFACTURER: 297 case KM_TAG_ATTESTATION_ID_MODEL: 298 return KM_ERROR_INVALID_KEY_BLOB; 299 300 /* Tags used for cryptographic parameters in keygen. Nothing to enforce. */ 301 case KM_TAG_PURPOSE: 302 case KM_TAG_ALGORITHM: 303 case KM_TAG_KEY_SIZE: 304 case KM_TAG_BLOCK_MODE: 305 case KM_TAG_DIGEST: 306 case KM_TAG_MAC_LENGTH: 307 case KM_TAG_PADDING: 308 case KM_TAG_NONCE: 309 case KM_TAG_MIN_MAC_LENGTH: 310 case KM_TAG_KDF: 311 case KM_TAG_EC_CURVE: 312 313 /* Tags not used for operations. */ 314 case KM_TAG_BLOB_USAGE_REQUIREMENTS: 315 case KM_TAG_EXPORTABLE: 316 317 /* Algorithm specific parameters not used for access control. */ 318 case KM_TAG_RSA_PUBLIC_EXPONENT: 319 case KM_TAG_ECIES_SINGLE_HASH_MODE: 320 321 /* Informational tags. */ 322 case KM_TAG_CREATION_DATETIME: 323 case KM_TAG_ORIGIN: 324 case KM_TAG_ROLLBACK_RESISTANT: 325 326 /* Tags handled when KM_TAG_USER_SECURE_ID is handled */ 327 case KM_TAG_NO_AUTH_REQUIRED: 328 case KM_TAG_USER_AUTH_TYPE: 329 case KM_TAG_AUTH_TIMEOUT: 330 331 /* Tag to provide data to operations. */ 332 case KM_TAG_ASSOCIATED_DATA: 333 334 /* Tags that are implicitly verified by secure side */ 335 case KM_TAG_ALL_APPLICATIONS: 336 case KM_TAG_APPLICATION_ID: 337 case KM_TAG_OS_VERSION: 338 case KM_TAG_OS_PATCHLEVEL: 339 340 /* Ignored pending removal */ 341 case KM_TAG_ALL_USERS: 342 343 /* TODO(swillden): Handle these */ 344 case KM_TAG_INCLUDE_UNIQUE_ID: 345 case KM_TAG_UNIQUE_ID: 346 case KM_TAG_RESET_SINCE_ID_ROTATION: 347 case KM_TAG_ALLOW_WHILE_ON_BODY: 348 break; 349 350 /* TODO(bcyoung): This is currently handled in keystore, but may move to keymaster in the 351 * future */ 352 case KM_TAG_USER_ID: 353 case KM_TAG_UNLOCKED_DEVICE_REQUIRED: 354 break; 355 356 case KM_TAG_BOOTLOADER_ONLY: 357 return KM_ERROR_INVALID_KEY_BLOB; 358 } 359 } 360 361 if (authentication_required && !auth_token_matched) { 362 LOG_E("Auth required but no matching auth token found", 0); 363 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED; 364 } 365 366 if (!caller_nonce_authorized_by_key && is_origination_purpose(purpose) && 367 operation_params.find(KM_TAG_NONCE) != -1) 368 return KM_ERROR_CALLER_NONCE_PROHIBITED; 369 370 if (min_ops_timeout != UINT32_MAX) { 371 if (!access_time_map_) { 372 LOG_S("Rate-limited keys table not allocated. Rate-limited keys disabled", 0); 373 return KM_ERROR_MEMORY_ALLOCATION_FAILED; 374 } 375 376 if (!access_time_map_->UpdateKeyAccessTime(keyid, get_current_time(), min_ops_timeout)) { 377 LOG_E("Rate-limited keys table full. Entries will time out.", 0); 378 return KM_ERROR_TOO_MANY_OPERATIONS; 379 } 380 } 381 382 if (update_access_count) { 383 if (!access_count_map_) { 384 LOG_S("Usage-count limited keys tabel not allocated. Count-limited keys disabled", 0); 385 return KM_ERROR_MEMORY_ALLOCATION_FAILED; 386 } 387 388 if (!access_count_map_->IncrementKeyAccessCount(keyid)) { 389 LOG_E("Usage count-limited keys table full, until reboot.", 0); 390 return KM_ERROR_TOO_MANY_OPERATIONS; 391 } 392 } 393 394 return KM_ERROR_OK; 395 } 396 397 bool KeymasterEnforcement::MinTimeBetweenOpsPassed(uint32_t min_time_between, const km_id_t keyid) { 398 if (!access_time_map_) 399 return false; 400 401 uint32_t last_access_time; 402 if (!access_time_map_->LastKeyAccessTime(keyid, &last_access_time)) 403 return true; 404 return min_time_between <= static_cast<int64_t>(get_current_time()) - last_access_time; 405 } 406 407 bool KeymasterEnforcement::MaxUsesPerBootNotExceeded(const km_id_t keyid, uint32_t max_uses) { 408 if (!access_count_map_) 409 return false; 410 411 uint32_t key_access_count; 412 if (!access_count_map_->KeyAccessCount(keyid, &key_access_count)) 413 return true; 414 return key_access_count < max_uses; 415 } 416 417 bool KeymasterEnforcement::AuthTokenMatches(const AuthProxy& auth_set, 418 const AuthorizationSet& operation_params, 419 const uint64_t user_secure_id, 420 const int auth_type_index, const int auth_timeout_index, 421 const keymaster_operation_handle_t op_handle, 422 bool is_begin_operation) const { 423 assert(auth_type_index < static_cast<int>(auth_set.size())); 424 assert(auth_timeout_index < static_cast<int>(auth_set.size())); 425 426 keymaster_blob_t auth_token_blob; 427 if (!operation_params.GetTagValue(TAG_AUTH_TOKEN, &auth_token_blob)) { 428 LOG_E("Authentication required, but auth token not provided", 0); 429 return false; 430 } 431 432 if (auth_token_blob.data_length != sizeof(hw_auth_token_t)) { 433 LOG_E("Bug: Auth token is the wrong size (%d expected, %d found)", sizeof(hw_auth_token_t), 434 auth_token_blob.data_length); 435 return false; 436 } 437 438 hw_auth_token_t auth_token; 439 memcpy(&auth_token, auth_token_blob.data, sizeof(hw_auth_token_t)); 440 if (auth_token.version != HW_AUTH_TOKEN_VERSION) { 441 LOG_E("Bug: Auth token is the version %d (or is not an auth token). Expected %d", 442 auth_token.version, HW_AUTH_TOKEN_VERSION); 443 return false; 444 } 445 446 if (!ValidateTokenSignature(auth_token)) { 447 LOG_E("Auth token signature invalid", 0); 448 return false; 449 } 450 451 if (auth_timeout_index == -1 && op_handle && op_handle != auth_token.challenge) { 452 LOG_E("Auth token has the challenge %llu, need %llu", auth_token.challenge, op_handle); 453 return false; 454 } 455 456 if (user_secure_id != auth_token.user_id && user_secure_id != auth_token.authenticator_id) { 457 LOG_I("Auth token SIDs %llu and %llu do not match key SID %llu", auth_token.user_id, 458 auth_token.authenticator_id, user_secure_id); 459 return false; 460 } 461 462 if (auth_type_index < 0 || auth_type_index > static_cast<int>(auth_set.size())) { 463 LOG_E("Auth required but no auth type found", 0); 464 return false; 465 } 466 467 assert(auth_set[auth_type_index].tag == KM_TAG_USER_AUTH_TYPE); 468 if (auth_set[auth_type_index].tag != KM_TAG_USER_AUTH_TYPE) 469 return false; 470 471 uint32_t key_auth_type_mask = auth_set[auth_type_index].integer; 472 uint32_t token_auth_type = ntoh(auth_token.authenticator_type); 473 if ((key_auth_type_mask & token_auth_type) == 0) { 474 LOG_E("Key requires match of auth type mask 0%uo, but token contained 0%uo", 475 key_auth_type_mask, token_auth_type); 476 return false; 477 } 478 479 if (auth_timeout_index != -1 && is_begin_operation) { 480 assert(auth_set[auth_timeout_index].tag == KM_TAG_AUTH_TIMEOUT); 481 if (auth_set[auth_timeout_index].tag != KM_TAG_AUTH_TIMEOUT) 482 return false; 483 484 if (auth_token_timed_out(auth_token, auth_set[auth_timeout_index].integer)) { 485 LOG_E("Auth token has timed out", 0); 486 return false; 487 } 488 } 489 490 // Survived the whole gauntlet. We have authentage! 491 return true; 492 } 493 494 bool AccessTimeMap::LastKeyAccessTime(km_id_t keyid, uint32_t* last_access_time) const { 495 for (auto& entry : last_access_list_) 496 if (entry.keyid == keyid) { 497 *last_access_time = entry.access_time; 498 return true; 499 } 500 return false; 501 } 502 503 bool AccessTimeMap::UpdateKeyAccessTime(km_id_t keyid, uint32_t current_time, uint32_t timeout) { 504 List<AccessTime>::iterator iter; 505 for (iter = last_access_list_.begin(); iter != last_access_list_.end();) { 506 if (iter->keyid == keyid) { 507 iter->access_time = current_time; 508 return true; 509 } 510 511 // Expire entry if possible. 512 assert(current_time >= iter->access_time); 513 if (current_time - iter->access_time >= iter->timeout) 514 iter = last_access_list_.erase(iter); 515 else 516 ++iter; 517 } 518 519 if (last_access_list_.size() >= max_size_) 520 return false; 521 522 AccessTime new_entry; 523 new_entry.keyid = keyid; 524 new_entry.access_time = current_time; 525 new_entry.timeout = timeout; 526 last_access_list_.push_front(new_entry); 527 return true; 528 } 529 530 bool AccessCountMap::KeyAccessCount(km_id_t keyid, uint32_t* count) const { 531 for (auto& entry : access_count_list_) 532 if (entry.keyid == keyid) { 533 *count = entry.access_count; 534 return true; 535 } 536 return false; 537 } 538 539 bool AccessCountMap::IncrementKeyAccessCount(km_id_t keyid) { 540 for (auto& entry : access_count_list_) 541 if (entry.keyid == keyid) { 542 // Note that the 'if' below will always be true because KM_TAG_MAX_USES_PER_BOOT is a 543 // uint32_t, and as soon as entry.access_count reaches the specified maximum value 544 // operation requests will be rejected and access_count won't be incremented any more. 545 // And, besides, UINT64_MAX is huge. But we ensure that it doesn't wrap anyway, out of 546 // an abundance of caution. 547 if (entry.access_count < UINT64_MAX) 548 ++entry.access_count; 549 return true; 550 } 551 552 if (access_count_list_.size() >= max_size_) 553 return false; 554 555 AccessCount new_entry; 556 new_entry.keyid = keyid; 557 new_entry.access_count = 1; 558 access_count_list_.push_front(new_entry); 559 return true; 560 } 561 }; /* namespace keymaster */ 562