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