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_SECOND_IMEI:
317 case KM_TAG_ATTESTATION_ID_MEID:
318 case KM_TAG_ATTESTATION_ID_MANUFACTURER:
319 case KM_TAG_ATTESTATION_ID_MODEL:
320 case KM_TAG_DEVICE_UNIQUE_ATTESTATION:
321 case KM_TAG_CERTIFICATE_SUBJECT:
322 case KM_TAG_CERTIFICATE_SERIAL:
323 case KM_TAG_CERTIFICATE_NOT_AFTER:
324 case KM_TAG_CERTIFICATE_NOT_BEFORE:
325 return KM_ERROR_INVALID_KEY_BLOB;
326
327 /* Tags used for cryptographic parameters in keygen. Nothing to enforce. */
328 case KM_TAG_PURPOSE:
329 case KM_TAG_ALGORITHM:
330 case KM_TAG_KEY_SIZE:
331 case KM_TAG_BLOCK_MODE:
332 case KM_TAG_DIGEST:
333 case KM_TAG_MAC_LENGTH:
334 case KM_TAG_PADDING:
335 case KM_TAG_NONCE:
336 case KM_TAG_MIN_MAC_LENGTH:
337 case KM_TAG_KDF:
338 case KM_TAG_EC_CURVE:
339
340 /* Tags not used for operations. */
341 case KM_TAG_BLOB_USAGE_REQUIREMENTS:
342 case KM_TAG_EXPORTABLE:
343
344 /* Algorithm specific parameters not used for access control. */
345 case KM_TAG_RSA_PUBLIC_EXPONENT:
346 case KM_TAG_ECIES_SINGLE_HASH_MODE:
347 case KM_TAG_RSA_OAEP_MGF_DIGEST:
348
349 /* Informational tags. */
350 case KM_TAG_CREATION_DATETIME:
351 case KM_TAG_ORIGIN:
352 case KM_TAG_ROLLBACK_RESISTANCE:
353 case KM_TAG_ROLLBACK_RESISTANT:
354 case KM_TAG_USER_ID:
355
356 /* Tags handled when KM_TAG_USER_SECURE_ID is handled */
357 case KM_TAG_NO_AUTH_REQUIRED:
358 case KM_TAG_USER_AUTH_TYPE:
359 case KM_TAG_AUTH_TIMEOUT:
360
361 /* Tag to provide data to operations. */
362 case KM_TAG_ASSOCIATED_DATA:
363
364 /* Tags that are implicitly verified by secure side */
365 case KM_TAG_ALL_APPLICATIONS:
366 case KM_TAG_APPLICATION_ID:
367 case KM_TAG_OS_VERSION:
368 case KM_TAG_OS_PATCHLEVEL:
369 case KM_TAG_BOOT_PATCHLEVEL:
370 case KM_TAG_VENDOR_PATCHLEVEL:
371 case KM_TAG_STORAGE_KEY:
372
373 /* Ignored pending removal */
374 case KM_TAG_ALL_USERS:
375
376 /* Tags that are not enforced by begin */
377 case KM_TAG_INCLUDE_UNIQUE_ID:
378 case KM_TAG_UNIQUE_ID:
379 case KM_TAG_RESET_SINCE_ID_ROTATION:
380 case KM_TAG_ALLOW_WHILE_ON_BODY:
381 case KM_TAG_TRUSTED_CONFIRMATION_REQUIRED:
382 case KM_TAG_TRUSTED_USER_PRESENCE_REQUIRED:
383 case KM_TAG_CONFIRMATION_TOKEN:
384 case KM_TAG_USAGE_COUNT_LIMIT:
385 case KM_TAG_MAX_BOOT_LEVEL:
386 break;
387
388 case KM_TAG_IDENTITY_CREDENTIAL_KEY:
389 case KM_TAG_BOOTLOADER_ONLY:
390 return KM_ERROR_INVALID_KEY_BLOB;
391
392 case KM_TAG_EARLY_BOOT_ONLY:
393 if (!in_early_boot()) return KM_ERROR_EARLY_BOOT_ENDED;
394 break;
395 }
396 }
397
398 if (authentication_required && !auth_token_matched) {
399 LOG_E("Auth required but no matching auth token found", 0);
400 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
401 }
402
403 if (!caller_nonce_authorized_by_key && is_origination_purpose(purpose) &&
404 operation_params.find(KM_TAG_NONCE) != -1)
405 return KM_ERROR_CALLER_NONCE_PROHIBITED;
406
407 if (min_ops_timeout != UINT32_MAX) {
408 if (!access_time_map_) {
409 LOG_S("Rate-limited keys table not allocated. Rate-limited keys disabled", 0);
410 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
411 }
412
413 if (!access_time_map_->UpdateKeyAccessTime(keyid, get_current_time(), min_ops_timeout)) {
414 LOG_E("Rate-limited keys table full. Entries will time out.", 0);
415 return KM_ERROR_TOO_MANY_OPERATIONS;
416 }
417 }
418
419 if (update_access_count) {
420 if (!access_count_map_) {
421 LOG_S("Usage-count limited keys table not allocated. Count-limited keys disabled", 0);
422 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
423 }
424
425 if (!access_count_map_->IncrementKeyAccessCount(keyid)) {
426 LOG_E("Usage count-limited keys table full, until reboot.", 0);
427 return KM_ERROR_TOO_MANY_OPERATIONS;
428 }
429 }
430
431 return KM_ERROR_OK;
432 }
433
MinTimeBetweenOpsPassed(uint32_t min_time_between,const km_id_t keyid)434 bool KeymasterEnforcement::MinTimeBetweenOpsPassed(uint32_t min_time_between, const km_id_t keyid) {
435 if (!access_time_map_) return false;
436
437 uint32_t last_access_time;
438 if (!access_time_map_->LastKeyAccessTime(keyid, &last_access_time)) return true;
439 return min_time_between <= static_cast<int64_t>(get_current_time()) - last_access_time;
440 }
441
MaxUsesPerBootNotExceeded(const km_id_t keyid,uint32_t max_uses)442 bool KeymasterEnforcement::MaxUsesPerBootNotExceeded(const km_id_t keyid, uint32_t max_uses) {
443 if (!access_count_map_) return false;
444
445 uint32_t key_access_count;
446 if (!access_count_map_->KeyAccessCount(keyid, &key_access_count)) return true;
447 return key_access_count < max_uses;
448 }
449
GetAndValidateAuthToken(const AuthorizationSet & operation_params,const hw_auth_token_t ** auth_token,uint32_t * token_auth_type) const450 bool KeymasterEnforcement::GetAndValidateAuthToken(const AuthorizationSet& operation_params,
451 const hw_auth_token_t** auth_token,
452 uint32_t* token_auth_type) const {
453 keymaster_blob_t auth_token_blob;
454 if (!operation_params.GetTagValue(TAG_AUTH_TOKEN, &auth_token_blob)) {
455 LOG_E("Authentication required, but auth token not provided", 0);
456 return false;
457 }
458
459 if (auth_token_blob.data_length != sizeof(**auth_token)) {
460 LOG_E("Bug: Auth token is the wrong size (%d expected, %d found)", sizeof(hw_auth_token_t),
461 auth_token_blob.data_length);
462 return false;
463 }
464
465 *auth_token = reinterpret_cast<const hw_auth_token_t*>(auth_token_blob.data);
466 if ((*auth_token)->version != HW_AUTH_TOKEN_VERSION) {
467 LOG_E("Bug: Auth token is the version %d (or is not an auth token). Expected %d",
468 (*auth_token)->version, HW_AUTH_TOKEN_VERSION);
469 return false;
470 }
471
472 if (!ValidateTokenSignature(**auth_token)) {
473 LOG_E("Auth token signature invalid", 0);
474 return false;
475 }
476
477 *token_auth_type = ntoh((*auth_token)->authenticator_type);
478
479 return true;
480 }
481
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) const482 bool KeymasterEnforcement::AuthTokenMatches(const AuthProxy& auth_set,
483 const AuthorizationSet& operation_params,
484 const uint64_t user_secure_id,
485 const int auth_type_index, const int auth_timeout_index,
486 const keymaster_operation_handle_t op_handle,
487 bool is_begin_operation) const {
488 assert(auth_type_index < static_cast<int>(auth_set.size()));
489 assert(auth_timeout_index < static_cast<int>(auth_set.size()));
490
491 const hw_auth_token_t* auth_token;
492 uint32_t token_auth_type;
493 if (!GetAndValidateAuthToken(operation_params, &auth_token, &token_auth_type)) return false;
494
495 if (auth_timeout_index == -1 && op_handle && op_handle != auth_token->challenge) {
496 LOG_E("Auth token has the challenge %llu, need %llu", auth_token->challenge, op_handle);
497 return false;
498 }
499
500 if (user_secure_id != auth_token->user_id && user_secure_id != auth_token->authenticator_id) {
501 LOG_I("Auth token SIDs %llu and %llu do not match key SID %llu", auth_token->user_id,
502 auth_token->authenticator_id, user_secure_id);
503 return false;
504 }
505
506 if (auth_type_index < 0 || auth_type_index > static_cast<int>(auth_set.size())) {
507 LOG_E("Auth required but no auth type found", 0);
508 return false;
509 }
510
511 assert(auth_set[auth_type_index].tag == KM_TAG_USER_AUTH_TYPE);
512 if (auth_set[auth_type_index].tag != KM_TAG_USER_AUTH_TYPE) return false;
513
514 uint32_t key_auth_type_mask = auth_set[auth_type_index].integer;
515 if ((key_auth_type_mask & token_auth_type) == 0) {
516 LOG_E("Key requires match of auth type mask 0%uo, but token contained 0%uo",
517 key_auth_type_mask, token_auth_type);
518 return false;
519 }
520
521 if (auth_timeout_index != -1 && is_begin_operation) {
522 assert(auth_set[auth_timeout_index].tag == KM_TAG_AUTH_TIMEOUT);
523 if (auth_set[auth_timeout_index].tag != KM_TAG_AUTH_TIMEOUT) return false;
524
525 if (auth_token_timed_out(*auth_token, auth_set[auth_timeout_index].integer)) {
526 LOG_E("Auth token has timed out", 0);
527 return false;
528 }
529 }
530
531 // Survived the whole gauntlet. We have authentage!
532 return true;
533 }
534
GenerateTimestampToken(TimestampToken *)535 keymaster_error_t KeymasterEnforcement::GenerateTimestampToken(TimestampToken* /*token*/) {
536 return KM_ERROR_UNIMPLEMENTED;
537 }
538
LastKeyAccessTime(km_id_t keyid,uint32_t * last_access_time) const539 bool AccessTimeMap::LastKeyAccessTime(km_id_t keyid, uint32_t* last_access_time) const {
540 for (auto& entry : last_access_list_)
541 if (entry.keyid == keyid) {
542 *last_access_time = entry.access_time;
543 return true;
544 }
545 return false;
546 }
547
UpdateKeyAccessTime(km_id_t keyid,uint32_t current_time,uint32_t timeout)548 bool AccessTimeMap::UpdateKeyAccessTime(km_id_t keyid, uint32_t current_time, uint32_t timeout) {
549 List<AccessTime>::iterator iter;
550 for (iter = last_access_list_.begin(); iter != last_access_list_.end();) {
551 if (iter->keyid == keyid) {
552 iter->access_time = current_time;
553 return true;
554 }
555
556 // Expire entry if possible.
557 assert(current_time >= iter->access_time);
558 if (current_time - iter->access_time >= iter->timeout)
559 iter = last_access_list_.erase(iter);
560 else
561 ++iter;
562 }
563
564 if (last_access_list_.size() >= max_size_) return false;
565
566 AccessTime new_entry;
567 new_entry.keyid = keyid;
568 new_entry.access_time = current_time;
569 new_entry.timeout = timeout;
570 last_access_list_.push_front(new_entry);
571 return true;
572 }
573
KeyAccessCount(km_id_t keyid,uint32_t * count) const574 bool AccessCountMap::KeyAccessCount(km_id_t keyid, uint32_t* count) const {
575 for (auto& entry : access_count_list_)
576 if (entry.keyid == keyid) {
577 *count = entry.access_count;
578 return true;
579 }
580 return false;
581 }
582
IncrementKeyAccessCount(km_id_t keyid)583 bool AccessCountMap::IncrementKeyAccessCount(km_id_t keyid) {
584 for (auto& entry : access_count_list_)
585 if (entry.keyid == keyid) {
586 // Note that the 'if' below will always be true because KM_TAG_MAX_USES_PER_BOOT is a
587 // uint32_t, and as soon as entry.access_count reaches the specified maximum value
588 // operation requests will be rejected and access_count won't be incremented any more.
589 // And, besides, UINT64_MAX is huge. But we ensure that it doesn't wrap anyway, out of
590 // an abundance of caution.
591 if (entry.access_count < UINT64_MAX) ++entry.access_count;
592 return true;
593 }
594
595 if (access_count_list_.size() >= max_size_) return false;
596
597 AccessCount new_entry;
598 new_entry.keyid = keyid;
599 new_entry.access_count = 1;
600 access_count_list_.push_front(new_entry);
601 return true;
602 }
603 }; /* namespace keymaster */
604