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