blob: 117f048b74c023e733334172816f5205a0ad7530 [file] [log] [blame]
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001/*
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#define LOG_TAG "keystore"
18
19#include "keymaster_enforcement.h"
20
21#include <assert.h>
22#include <inttypes.h>
23#include <limits.h>
24#include <string.h>
25
26#include <openssl/evp.h>
27
28#include <cutils/log.h>
29#include <hardware/hw_auth_token.h>
30#include <list>
31
32namespace keystore {
33
34class AccessTimeMap {
35 public:
36 explicit AccessTimeMap(uint32_t max_size) : max_size_(max_size) {}
37
38 /* If the key is found, returns true and fills \p last_access_time. If not found returns
39 * false. */
40 bool LastKeyAccessTime(km_id_t keyid, uint32_t* last_access_time) const;
41
42 /* Updates the last key access time with the currentTime parameter. Adds the key if
43 * needed, returning false if key cannot be added because list is full. */
44 bool UpdateKeyAccessTime(km_id_t keyid, uint32_t current_time, uint32_t timeout);
45
46 private:
47 struct AccessTime {
48 km_id_t keyid;
49 uint32_t access_time;
50 uint32_t timeout;
51 };
52 std::list<AccessTime> last_access_list_;
53 const uint32_t max_size_;
54};
55
56class AccessCountMap {
57 public:
58 explicit AccessCountMap(uint32_t max_size) : max_size_(max_size) {}
59
60 /* If the key is found, returns true and fills \p count. If not found returns
61 * false. */
62 bool KeyAccessCount(km_id_t keyid, uint32_t* count) const;
63
64 /* Increments key access count, adding an entry if the key has never been used. Returns
65 * false if the list has reached maximum size. */
66 bool IncrementKeyAccessCount(km_id_t keyid);
67
68 private:
69 struct AccessCount {
70 km_id_t keyid;
71 uint64_t access_count;
72 };
73 std::list<AccessCount> access_count_list_;
74 const uint32_t max_size_;
75};
76
77bool is_public_key_algorithm(const AuthorizationSet& auth_set) {
78 auto algorithm = auth_set.GetTagValue(TAG_ALGORITHM);
79 return algorithm.isOk() &&
80 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC);
81}
82
83static ErrorCode authorized_purpose(const KeyPurpose purpose, const AuthorizationSet& auth_set) {
84 switch (purpose) {
85 case KeyPurpose::VERIFY:
86 case KeyPurpose::ENCRYPT:
87 case KeyPurpose::SIGN:
88 case KeyPurpose::DECRYPT:
89 if (auth_set.Contains(TAG_PURPOSE, purpose)) return ErrorCode::OK;
90 return ErrorCode::INCOMPATIBLE_PURPOSE;
91
92 default:
93 return ErrorCode::UNSUPPORTED_PURPOSE;
94 }
95}
96
97inline bool is_origination_purpose(KeyPurpose purpose) {
98 return purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN;
99}
100
101inline bool is_usage_purpose(KeyPurpose purpose) {
102 return purpose == KeyPurpose::DECRYPT || purpose == KeyPurpose::VERIFY;
103}
104
105KeymasterEnforcement::KeymasterEnforcement(uint32_t max_access_time_map_size,
106 uint32_t max_access_count_map_size)
107 : access_time_map_(new (std::nothrow) AccessTimeMap(max_access_time_map_size)),
108 access_count_map_(new (std::nothrow) AccessCountMap(max_access_count_map_size)) {}
109
110KeymasterEnforcement::~KeymasterEnforcement() {
111 delete access_time_map_;
112 delete access_count_map_;
113}
114
115ErrorCode KeymasterEnforcement::AuthorizeOperation(const KeyPurpose purpose, const km_id_t keyid,
116 const AuthorizationSet& auth_set,
117 const AuthorizationSet& operation_params,
118 uint64_t op_handle, bool is_begin_operation) {
119 if (is_public_key_algorithm(auth_set)) {
120 switch (purpose) {
121 case KeyPurpose::ENCRYPT:
122 case KeyPurpose::VERIFY:
123 /* Public key operations are always authorized. */
124 return ErrorCode::OK;
125
126 case KeyPurpose::DECRYPT:
127 case KeyPurpose::SIGN:
128 case KeyPurpose::DERIVE_KEY:
129 break;
130 case KeyPurpose::WRAP_KEY:
131 return ErrorCode::INCOMPATIBLE_PURPOSE;
132 };
133 };
134
135 if (is_begin_operation)
136 return AuthorizeBegin(purpose, keyid, auth_set, operation_params);
137 else
138 return AuthorizeUpdateOrFinish(auth_set, operation_params, op_handle);
139}
140
141// For update and finish the only thing to check is user authentication, and then only if it's not
142// timeout-based.
143ErrorCode KeymasterEnforcement::AuthorizeUpdateOrFinish(const AuthorizationSet& auth_set,
144 const AuthorizationSet& operation_params,
145 uint64_t op_handle) {
146 int auth_type_index = -1;
147 for (size_t pos = 0; pos < auth_set.size(); ++pos) {
148 switch (auth_set[pos].tag) {
149 case Tag::NO_AUTH_REQUIRED:
150 case Tag::AUTH_TIMEOUT:
151 // If no auth is required or if auth is timeout-based, we have nothing to check.
152 return ErrorCode::OK;
153
154 case Tag::USER_AUTH_TYPE:
155 auth_type_index = pos;
156 break;
157
158 default:
159 break;
160 }
161 }
162
163 // Note that at this point we should be able to assume that authentication is required, because
164 // authentication is required if KM_TAG_NO_AUTH_REQUIRED is absent. However, there are legacy
165 // keys which have no authentication-related tags, so we assume that absence is equivalent to
166 // presence of KM_TAG_NO_AUTH_REQUIRED.
167 //
168 // So, if we found KM_TAG_USER_AUTH_TYPE or if we find KM_TAG_USER_SECURE_ID then authentication
169 // is required. If we find neither, then we assume authentication is not required and return
170 // success.
171 bool authentication_required = (auth_type_index != -1);
172 for (auto& param : auth_set) {
173 auto user_secure_id = authorizationValue(TAG_USER_SECURE_ID, param);
174 if (user_secure_id.isOk()) {
175 authentication_required = true;
176 int auth_timeout_index = -1;
177 if (AuthTokenMatches(auth_set, operation_params, user_secure_id.value(),
178 auth_type_index, auth_timeout_index, op_handle,
179 false /* is_begin_operation */))
180 return ErrorCode::OK;
181 }
182 }
183
184 if (authentication_required) return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
185
186 return ErrorCode::OK;
187}
188
189ErrorCode KeymasterEnforcement::AuthorizeBegin(const KeyPurpose purpose, const km_id_t keyid,
190 const AuthorizationSet& auth_set,
191 const AuthorizationSet& operation_params) {
192 // Find some entries that may be needed to handle KM_TAG_USER_SECURE_ID
193 int auth_timeout_index = -1;
194 int auth_type_index = -1;
195 int no_auth_required_index = -1;
196 for (size_t pos = 0; pos < auth_set.size(); ++pos) {
197 switch (auth_set[pos].tag) {
198 case Tag::AUTH_TIMEOUT:
199 auth_timeout_index = pos;
200 break;
201 case Tag::USER_AUTH_TYPE:
202 auth_type_index = pos;
203 break;
204 case Tag::NO_AUTH_REQUIRED:
205 no_auth_required_index = pos;
206 break;
207 default:
208 break;
209 }
210 }
211
212 ErrorCode error = authorized_purpose(purpose, auth_set);
213 if (error != ErrorCode::OK) return error;
214
215 // If successful, and if key has a min time between ops, this will be set to the time limit
216 uint32_t min_ops_timeout = UINT32_MAX;
217
218 bool update_access_count = false;
219 bool caller_nonce_authorized_by_key = false;
220 bool authentication_required = false;
221 bool auth_token_matched = false;
222
223 for (auto& param : auth_set) {
224
225 // KM_TAG_PADDING_OLD and KM_TAG_DIGEST_OLD aren't actually members of the enum, so we can't
226 // switch on them. There's nothing to validate for them, though, so just ignore them.
227 if (int32_t(param.tag) == KM_TAG_PADDING_OLD || int32_t(param.tag) == KM_TAG_DIGEST_OLD)
228 continue;
229
230 switch (param.tag) {
231
232 case Tag::ACTIVE_DATETIME: {
233 auto date = authorizationValue(TAG_ACTIVE_DATETIME, param);
234 if (date.isOk() && !activation_date_valid(date.value()))
235 return ErrorCode::KEY_NOT_YET_VALID;
236 break;
237 }
238 case Tag::ORIGINATION_EXPIRE_DATETIME: {
239 auto date = authorizationValue(TAG_ORIGINATION_EXPIRE_DATETIME, param);
240 if (is_origination_purpose(purpose) && date.isOk() &&
241 expiration_date_passed(date.value()))
242 return ErrorCode::KEY_EXPIRED;
243 break;
244 }
245 case Tag::USAGE_EXPIRE_DATETIME: {
246 auto date = authorizationValue(TAG_USAGE_EXPIRE_DATETIME, param);
247 if (is_usage_purpose(purpose) && date.isOk() && expiration_date_passed(date.value()))
248 return ErrorCode::KEY_EXPIRED;
249 break;
250 }
251 case Tag::MIN_SECONDS_BETWEEN_OPS: {
252 auto min_ops_timeout = authorizationValue(TAG_MIN_SECONDS_BETWEEN_OPS, param);
253 if (min_ops_timeout.isOk() && !MinTimeBetweenOpsPassed(min_ops_timeout.value(), keyid))
254 return ErrorCode::KEY_RATE_LIMIT_EXCEEDED;
255 break;
256 }
257 case Tag::MAX_USES_PER_BOOT: {
258 auto max_users = authorizationValue(TAG_MAX_USES_PER_BOOT, param);
259 update_access_count = true;
260 if (max_users.isOk() && !MaxUsesPerBootNotExceeded(keyid, max_users.value()))
261 return ErrorCode::KEY_MAX_OPS_EXCEEDED;
262 break;
263 }
264 case 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 ErrorCode::INVALID_KEY_BLOB;
268 }
269
270 if (auth_timeout_index != -1) {
271 auto secure_id = authorizationValue(TAG_USER_SECURE_ID, param);
272 authentication_required = true;
273 if (secure_id.isOk() &&
274 AuthTokenMatches(auth_set, operation_params, secure_id.value(), auth_type_index,
275 auth_timeout_index, 0 /* op_handle */,
276 true /* is_begin_operation */))
277 auth_token_matched = true;
278 }
279 break;
280
281 case Tag::CALLER_NONCE:
282 caller_nonce_authorized_by_key = true;
283 break;
284
285 /* Tags should never be in key auths. */
286 case Tag::INVALID:
287 case Tag::AUTH_TOKEN:
288 case Tag::ROOT_OF_TRUST:
289 case Tag::APPLICATION_DATA:
290 case Tag::ATTESTATION_CHALLENGE:
291 case Tag::ATTESTATION_APPLICATION_ID:
292 return ErrorCode::INVALID_KEY_BLOB;
293
294 /* Tags used for cryptographic parameters in keygen. Nothing to enforce. */
295 case Tag::PURPOSE:
296 case Tag::ALGORITHM:
297 case Tag::KEY_SIZE:
298 case Tag::BLOCK_MODE:
299 case Tag::DIGEST:
300 case Tag::MAC_LENGTH:
301 case Tag::PADDING:
302 case Tag::NONCE:
303 case Tag::MIN_MAC_LENGTH:
304 case Tag::KDF:
305 case Tag::EC_CURVE:
306
307 /* Tags not used for operations. */
308 case Tag::BLOB_USAGE_REQUIREMENTS:
309 case Tag::EXPORTABLE:
310
311 /* Algorithm specific parameters not used for access control. */
312 case Tag::RSA_PUBLIC_EXPONENT:
313 case Tag::ECIES_SINGLE_HASH_MODE:
314
315 /* Informational tags. */
316 case Tag::CREATION_DATETIME:
317 case Tag::ORIGIN:
318 case Tag::ROLLBACK_RESISTANT:
319
320 /* Tags handled when KM_TAG_USER_SECURE_ID is handled */
321 case Tag::NO_AUTH_REQUIRED:
322 case Tag::USER_AUTH_TYPE:
323 case Tag::AUTH_TIMEOUT:
324
325 /* Tag to provide data to operations. */
326 case Tag::ASSOCIATED_DATA:
327
328 /* Tags that are implicitly verified by secure side */
329 case Tag::ALL_APPLICATIONS:
330 case Tag::APPLICATION_ID:
331 case Tag::OS_VERSION:
332 case Tag::OS_PATCHLEVEL:
333
334 /* Ignored pending removal */
335 case Tag::USER_ID:
336 case Tag::ALL_USERS:
337
338 /* TODO(swillden): Handle these */
339 case Tag::INCLUDE_UNIQUE_ID:
340 case Tag::UNIQUE_ID:
341 case Tag::RESET_SINCE_ID_ROTATION:
342 case Tag::ALLOW_WHILE_ON_BODY:
343 break;
344
345 case Tag::BOOTLOADER_ONLY:
346 return ErrorCode::INVALID_KEY_BLOB;
347 }
348 }
349
350 if (authentication_required && !auth_token_matched) {
351 ALOGE("Auth required but no matching auth token found");
352 return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
353 }
354
355 if (!caller_nonce_authorized_by_key && is_origination_purpose(purpose) &&
356 operation_params.Contains(Tag::NONCE))
357 return ErrorCode::CALLER_NONCE_PROHIBITED;
358
359 if (min_ops_timeout != UINT32_MAX) {
360 if (!access_time_map_) {
361 ALOGE("Rate-limited keys table not allocated. Rate-limited keys disabled");
362 return ErrorCode::MEMORY_ALLOCATION_FAILED;
363 }
364
365 if (!access_time_map_->UpdateKeyAccessTime(keyid, get_current_time(), min_ops_timeout)) {
366 ALOGE("Rate-limited keys table full. Entries will time out.");
367 return ErrorCode::TOO_MANY_OPERATIONS;
368 }
369 }
370
371 if (update_access_count) {
372 if (!access_count_map_) {
373 ALOGE("Usage-count limited keys tabel not allocated. Count-limited keys disabled");
374 return ErrorCode::MEMORY_ALLOCATION_FAILED;
375 }
376
377 if (!access_count_map_->IncrementKeyAccessCount(keyid)) {
378 ALOGE("Usage count-limited keys table full, until reboot.");
379 return ErrorCode::TOO_MANY_OPERATIONS;
380 }
381 }
382
383 return ErrorCode::OK;
384}
385
386class EvpMdCtx {
387 public:
388 EvpMdCtx() { EVP_MD_CTX_init(&ctx_); }
389 ~EvpMdCtx() { EVP_MD_CTX_cleanup(&ctx_); }
390
391 EVP_MD_CTX* get() { return &ctx_; }
392
393 private:
394 EVP_MD_CTX ctx_;
395};
396
397/* static */
398bool KeymasterEnforcement::CreateKeyId(const hidl_vec<uint8_t>& key_blob, km_id_t* keyid) {
399 EvpMdCtx ctx;
400
401 uint8_t hash[EVP_MAX_MD_SIZE];
402 unsigned int hash_len;
403 if (EVP_DigestInit_ex(ctx.get(), EVP_sha256(), nullptr /* ENGINE */) &&
404 EVP_DigestUpdate(ctx.get(), &key_blob[0], key_blob.size()) &&
405 EVP_DigestFinal_ex(ctx.get(), hash, &hash_len)) {
406 assert(hash_len >= sizeof(*keyid));
407 memcpy(keyid, hash, sizeof(*keyid));
408 return true;
409 }
410
411 return false;
412}
413
414bool KeymasterEnforcement::MinTimeBetweenOpsPassed(uint32_t min_time_between, const km_id_t keyid) {
415 if (!access_time_map_) return false;
416
417 uint32_t last_access_time;
418 if (!access_time_map_->LastKeyAccessTime(keyid, &last_access_time)) return true;
419 return min_time_between <= static_cast<int64_t>(get_current_time()) - last_access_time;
420}
421
422bool KeymasterEnforcement::MaxUsesPerBootNotExceeded(const km_id_t keyid, uint32_t max_uses) {
423 if (!access_count_map_) return false;
424
425 uint32_t key_access_count;
426 if (!access_count_map_->KeyAccessCount(keyid, &key_access_count)) return true;
427 return key_access_count < max_uses;
428}
429
430template <typename IntType, uint32_t byteOrder> struct choose_hton;
431
432template <typename IntType> struct choose_hton<IntType, __ORDER_LITTLE_ENDIAN__> {
433 inline static IntType hton(const IntType& value) {
434 IntType result = 0;
435 const unsigned char* inbytes = reinterpret_cast<const unsigned char*>(&value);
436 unsigned char* outbytes = reinterpret_cast<unsigned char*>(&result);
437 for (int i = sizeof(IntType) - 1; i >= 0; --i) {
438 *(outbytes++) = inbytes[i];
439 }
440 return result;
441 }
442};
443
444template <typename IntType> struct choose_hton<IntType, __ORDER_BIG_ENDIAN__> {
445 inline static IntType hton(const IntType& value) { return value; }
446};
447
448template <typename IntType> inline IntType hton(const IntType& value) {
449 return choose_hton<IntType, __BYTE_ORDER__>::hton(value);
450}
451
452template <typename IntType> inline IntType ntoh(const IntType& value) {
453 // same operation and hton
454 return choose_hton<IntType, __BYTE_ORDER__>::hton(value);
455}
456
457bool KeymasterEnforcement::AuthTokenMatches(const AuthorizationSet& auth_set,
458 const AuthorizationSet& operation_params,
459 const uint64_t user_secure_id,
460 const int auth_type_index, const int auth_timeout_index,
461 const uint64_t op_handle,
462 bool is_begin_operation) const {
463 assert(auth_type_index < static_cast<int>(auth_set.size()));
464 assert(auth_timeout_index < static_cast<int>(auth_set.size()));
465
466 auto auth_token_blob = operation_params.GetTagValue(TAG_AUTH_TOKEN);
467 if (!auth_token_blob.isOk()) {
468 ALOGE("Authentication required, but auth token not provided");
469 return false;
470 }
471
472 if (auth_token_blob.value().size() != sizeof(hw_auth_token_t)) {
473 ALOGE("Bug: Auth token is the wrong size (%zu expected, %zu found)",
474 sizeof(hw_auth_token_t), auth_token_blob.value().size());
475 return false;
476 }
477
478 hw_auth_token_t auth_token;
479 memcpy(&auth_token, &auth_token_blob.value()[0], sizeof(hw_auth_token_t));
480 if (auth_token.version != HW_AUTH_TOKEN_VERSION) {
481 ALOGE("Bug: Auth token is the version %hhu (or is not an auth token). Expected %d",
482 auth_token.version, HW_AUTH_TOKEN_VERSION);
483 return false;
484 }
485
486 if (!ValidateTokenSignature(auth_token)) {
487 ALOGE("Auth token signature invalid");
488 return false;
489 }
490
491 if (auth_timeout_index == -1 && op_handle && op_handle != auth_token.challenge) {
492 ALOGE("Auth token has the challenge %" PRIu64 ", need %" PRIu64, auth_token.challenge,
493 op_handle);
494 return false;
495 }
496
497 if (user_secure_id != auth_token.user_id && user_secure_id != auth_token.authenticator_id) {
498 ALOGI("Auth token SIDs %" PRIu64 " and %" PRIu64 " do not match key SID %" PRIu64,
499 auth_token.user_id, auth_token.authenticator_id, user_secure_id);
500 return false;
501 }
502
503 if (auth_type_index < 0 || auth_type_index > static_cast<int>(auth_set.size())) {
504 ALOGE("Auth required but no auth type found");
505 return false;
506 }
507
508 assert(auth_set[auth_type_index].tag == KM_TAG_USER_AUTH_TYPE);
509 auto key_auth_type_mask = authorizationValue(TAG_USER_AUTH_TYPE, auth_set[auth_type_index]);
510 if (!key_auth_type_mask.isOk()) return false;
511
512 uint32_t token_auth_type = ntoh(auth_token.authenticator_type);
513 if ((uint32_t(key_auth_type_mask.value()) & token_auth_type) == 0) {
514 ALOGE("Key requires match of auth type mask 0%uo, but token contained 0%uo",
515 key_auth_type_mask.value(), token_auth_type);
516 return false;
517 }
518
519 if (auth_timeout_index != -1 && is_begin_operation) {
520 assert(auth_set[auth_timeout_index].tag == KM_TAG_AUTH_TIMEOUT);
521 auto auth_token_timeout =
522 authorizationValue(TAG_AUTH_TIMEOUT, auth_set[auth_timeout_index]);
523 if (!auth_token_timeout.isOk()) return false;
524
525 if (auth_token_timed_out(auth_token, auth_token_timeout.value())) {
526 ALOGE("Auth token has timed out");
527 return false;
528 }
529 }
530
531 // Survived the whole gauntlet. We have authentage!
532 return true;
533}
534
535bool AccessTimeMap::LastKeyAccessTime(km_id_t keyid, uint32_t* last_access_time) const {
536 for (auto& entry : last_access_list_)
537 if (entry.keyid == keyid) {
538 *last_access_time = entry.access_time;
539 return true;
540 }
541 return false;
542}
543
544bool AccessTimeMap::UpdateKeyAccessTime(km_id_t keyid, uint32_t current_time, uint32_t timeout) {
545 for (auto iter = last_access_list_.begin(); iter != last_access_list_.end();) {
546 if (iter->keyid == keyid) {
547 iter->access_time = current_time;
548 return true;
549 }
550
551 // Expire entry if possible.
552 assert(current_time >= iter->access_time);
553 if (current_time - iter->access_time >= iter->timeout)
554 iter = last_access_list_.erase(iter);
555 else
556 ++iter;
557 }
558
559 if (last_access_list_.size() >= max_size_) return false;
560
561 AccessTime new_entry;
562 new_entry.keyid = keyid;
563 new_entry.access_time = current_time;
564 new_entry.timeout = timeout;
565 last_access_list_.push_front(new_entry);
566 return true;
567}
568
569bool AccessCountMap::KeyAccessCount(km_id_t keyid, uint32_t* count) const {
570 for (auto& entry : access_count_list_)
571 if (entry.keyid == keyid) {
572 *count = entry.access_count;
573 return true;
574 }
575 return false;
576}
577
578bool AccessCountMap::IncrementKeyAccessCount(km_id_t keyid) {
579 for (auto& entry : access_count_list_)
580 if (entry.keyid == keyid) {
581 // Note that the 'if' below will always be true because KM_TAG_MAX_USES_PER_BOOT is a
582 // uint32_t, and as soon as entry.access_count reaches the specified maximum value
583 // operation requests will be rejected and access_count won't be incremented any more.
584 // And, besides, UINT64_MAX is huge. But we ensure that it doesn't wrap anyway, out of
585 // an abundance of caution.
586 if (entry.access_count < UINT64_MAX) ++entry.access_count;
587 return true;
588 }
589
590 if (access_count_list_.size() >= max_size_) return false;
591
592 AccessCount new_entry;
593 new_entry.keyid = keyid;
594 new_entry.access_count = 1;
595 access_count_list_.push_front(new_entry);
596 return true;
597}
598}; /* namespace keystore */