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