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/android_keymaster_utils.h>
27 #include <keymaster/logger.h>
28 #include <keymaster/List.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         if (auth_set.Contains(TAG_PURPOSE, purpose))
90             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             break;
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.
145 keymaster_error_t
AuthorizeUpdateOrFinish(const AuthProxy & auth_set,const AuthorizationSet & operation_params,keymaster_operation_handle_t op_handle)146 KeymasterEnforcement::AuthorizeUpdateOrFinish(const AuthProxy& auth_set,
147                                               const AuthorizationSet& operation_params,
148                                               keymaster_operation_handle_t op_handle) {
149     int auth_type_index = -1;
150     int trusted_confirmation_index = -1;
151     bool no_auth_required = false;
152     for (size_t pos = 0; pos < auth_set.size(); ++pos) {
153         switch (auth_set[pos].tag) {
154         case KM_TAG_USER_AUTH_TYPE:
155             auth_type_index = pos;
156             break;
157 
158         case KM_TAG_TRUSTED_CONFIRMATION_REQUIRED:
159             trusted_confirmation_index = pos;
160             break;
161         case KM_TAG_NO_AUTH_REQUIRED:
162         case KM_TAG_AUTH_TIMEOUT:
163             // If no auth is required or if auth is timeout-based, we have nothing to check.
164             no_auth_required = true;
165             break;
166         default:
167             break;
168         }
169     }
170 
171     // TODO verify trusted confirmation mac once we have a shared secret established
172     // For now, since we do not have such a service, any token offered here must be invalid.
173     if (trusted_confirmation_index != -1) {
174         return KM_ERROR_NO_USER_CONFIRMATION;
175     }
176 
177     // If NO_AUTH_REQUIRED or AUTH_TIMEOUT was set, we need not check an auth token.
178     if (no_auth_required) {
179         return KM_ERROR_OK;
180     }
181 
182     // Note that at this point we should be able to assume that authentication is required, because
183     // authentication is required if KM_TAG_NO_AUTH_REQUIRED is absent.  However, there are legacy
184     // keys which have no authentication-related tags, so we assume that absence is equivalent to
185     // presence of KM_TAG_NO_AUTH_REQUIRED.
186     //
187     // So, if we found KM_TAG_USER_AUTH_TYPE or if we find KM_TAG_USER_SECURE_ID then authentication
188     // is required.  If we find neither, then we assume authentication is not required and return
189     // success.
190     bool authentication_required = (auth_type_index != -1);
191     for (auto& param : auth_set) {
192         if (param.tag == KM_TAG_USER_SECURE_ID) {
193             authentication_required = true;
194             int auth_timeout_index = -1;
195             if (AuthTokenMatches(auth_set, operation_params, param.long_integer, auth_type_index,
196                                  auth_timeout_index, op_handle, false /* is_begin_operation */))
197                 return KM_ERROR_OK;
198         }
199     }
200 
201     if (authentication_required) {
202         return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
203     }
204 
205     return KM_ERROR_OK;
206 }
207 
AuthorizeBegin(const keymaster_purpose_t purpose,const km_id_t keyid,const AuthProxy & auth_set,const AuthorizationSet & operation_params)208 keymaster_error_t KeymasterEnforcement::AuthorizeBegin(const keymaster_purpose_t purpose,
209                                                        const km_id_t keyid,
210                                                        const AuthProxy& auth_set,
211                                                        const AuthorizationSet& operation_params) {
212     // Find some entries that may be needed to handle KM_TAG_USER_SECURE_ID
213     int auth_timeout_index = -1;
214     int auth_type_index = -1;
215     int no_auth_required_index = -1;
216     for (size_t pos = 0; pos < auth_set.size(); ++pos) {
217         switch (auth_set[pos].tag) {
218         case KM_TAG_AUTH_TIMEOUT:
219             auth_timeout_index = pos;
220             break;
221         case KM_TAG_USER_AUTH_TYPE:
222             auth_type_index = pos;
223             break;
224         case KM_TAG_NO_AUTH_REQUIRED:
225             no_auth_required_index = pos;
226             break;
227         default:
228             break;
229         }
230     }
231 
232     keymaster_error_t error = authorized_purpose(purpose, auth_set);
233     if (error != KM_ERROR_OK)
234         return error;
235 
236     // If successful, and if key has a min time between ops, this will be set to the time limit
237     uint32_t min_ops_timeout = UINT32_MAX;
238 
239     bool update_access_count = false;
240     bool caller_nonce_authorized_by_key = false;
241     bool authentication_required = false;
242     bool auth_token_matched = false;
243 
244     for (auto& param : auth_set) {
245 
246         // KM_TAG_PADDING_OLD and KM_TAG_DIGEST_OLD aren't actually members of the enum, so we can't
247         // switch on them.  There's nothing to validate for them, though, so just ignore them.
248         if (param.tag == KM_TAG_PADDING_OLD || param.tag == KM_TAG_DIGEST_OLD)
249             continue;
250 
251         switch (param.tag) {
252 
253         case KM_TAG_ACTIVE_DATETIME:
254             if (!activation_date_valid(param.date_time))
255                 return KM_ERROR_KEY_NOT_YET_VALID;
256             break;
257 
258         case KM_TAG_ORIGINATION_EXPIRE_DATETIME:
259             if (is_origination_purpose(purpose) && expiration_date_passed(param.date_time))
260                 return KM_ERROR_KEY_EXPIRED;
261             break;
262 
263         case KM_TAG_USAGE_EXPIRE_DATETIME:
264             if (is_usage_purpose(purpose) && expiration_date_passed(param.date_time))
265                 return KM_ERROR_KEY_EXPIRED;
266             break;
267 
268         case KM_TAG_MIN_SECONDS_BETWEEN_OPS:
269             min_ops_timeout = param.integer;
270             if (!MinTimeBetweenOpsPassed(min_ops_timeout, keyid))
271                 return KM_ERROR_KEY_RATE_LIMIT_EXCEEDED;
272             break;
273 
274         case KM_TAG_MAX_USES_PER_BOOT:
275             update_access_count = true;
276             if (!MaxUsesPerBootNotExceeded(keyid, param.integer))
277                 return KM_ERROR_KEY_MAX_OPS_EXCEEDED;
278             break;
279 
280         case KM_TAG_USER_SECURE_ID:
281             if (no_auth_required_index != -1) {
282                 // Key has both KM_TAG_USER_SECURE_ID and KM_TAG_NO_AUTH_REQUIRED
283                 return KM_ERROR_INVALID_KEY_BLOB;
284             }
285 
286             if (auth_timeout_index != -1) {
287                 authentication_required = true;
288                 if (AuthTokenMatches(auth_set, operation_params, param.long_integer,
289                                      auth_type_index, auth_timeout_index, 0 /* op_handle */,
290                                      true /* is_begin_operation */))
291                     auth_token_matched = true;
292             }
293             break;
294 
295         case KM_TAG_UNLOCKED_DEVICE_REQUIRED:
296             if (device_locked_at_ > 0) {
297                 const hw_auth_token_t* auth_token;
298                 uint32_t token_auth_type;
299                 if (!GetAndValidateAuthToken(operation_params, &auth_token, &token_auth_type)) {
300                     return KM_ERROR_DEVICE_LOCKED;
301                 }
302 
303                 uint64_t token_timestamp_millis = ntoh(auth_token->timestamp);
304                 if (token_timestamp_millis <= device_locked_at_ ||
305                     (password_unlock_only_ && !(token_auth_type & HW_AUTH_PASSWORD))) {
306                     return KM_ERROR_DEVICE_LOCKED;
307                 }
308             }
309             break;
310 
311         case KM_TAG_CALLER_NONCE:
312             caller_nonce_authorized_by_key = true;
313             break;
314 
315         /* Tags should never be in key auths. */
316         case KM_TAG_INVALID:
317         case KM_TAG_AUTH_TOKEN:
318         case KM_TAG_ROOT_OF_TRUST:
319         case KM_TAG_APPLICATION_DATA:
320         case KM_TAG_ATTESTATION_CHALLENGE:
321         case KM_TAG_ATTESTATION_APPLICATION_ID:
322         case KM_TAG_ATTESTATION_ID_BRAND:
323         case KM_TAG_ATTESTATION_ID_DEVICE:
324         case KM_TAG_ATTESTATION_ID_PRODUCT:
325         case KM_TAG_ATTESTATION_ID_SERIAL:
326         case KM_TAG_ATTESTATION_ID_IMEI:
327         case KM_TAG_ATTESTATION_ID_MEID:
328         case KM_TAG_ATTESTATION_ID_MANUFACTURER:
329         case KM_TAG_ATTESTATION_ID_MODEL:
330         case KM_TAG_DEVICE_UNIQUE_ATTESTATION:
331             return KM_ERROR_INVALID_KEY_BLOB;
332 
333         /* Tags used for cryptographic parameters in keygen.  Nothing to enforce. */
334         case KM_TAG_PURPOSE:
335         case KM_TAG_ALGORITHM:
336         case KM_TAG_KEY_SIZE:
337         case KM_TAG_BLOCK_MODE:
338         case KM_TAG_DIGEST:
339         case KM_TAG_MAC_LENGTH:
340         case KM_TAG_PADDING:
341         case KM_TAG_NONCE:
342         case KM_TAG_MIN_MAC_LENGTH:
343         case KM_TAG_KDF:
344         case KM_TAG_EC_CURVE:
345 
346         /* Tags not used for operations. */
347         case KM_TAG_BLOB_USAGE_REQUIREMENTS:
348         case KM_TAG_EXPORTABLE:
349 
350         /* Algorithm specific parameters not used for access control. */
351         case KM_TAG_RSA_PUBLIC_EXPONENT:
352         case KM_TAG_ECIES_SINGLE_HASH_MODE:
353 
354         /* Informational tags. */
355         case KM_TAG_CREATION_DATETIME:
356         case KM_TAG_ORIGIN:
357         case KM_TAG_ROLLBACK_RESISTANCE:
358         case KM_TAG_ROLLBACK_RESISTANT:
359         case KM_TAG_USER_ID:
360 
361         /* Tags handled when KM_TAG_USER_SECURE_ID is handled */
362         case KM_TAG_NO_AUTH_REQUIRED:
363         case KM_TAG_USER_AUTH_TYPE:
364         case KM_TAG_AUTH_TIMEOUT:
365 
366         /* Tag to provide data to operations. */
367         case KM_TAG_ASSOCIATED_DATA:
368 
369         /* Tags that are implicitly verified by secure side */
370         case KM_TAG_ALL_APPLICATIONS:
371         case KM_TAG_APPLICATION_ID:
372         case KM_TAG_OS_VERSION:
373         case KM_TAG_OS_PATCHLEVEL:
374 
375         /* Ignored pending removal */
376         case KM_TAG_ALL_USERS:
377 
378         /* TODO(swillden): Handle these */
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             break;
385 
386         case KM_TAG_IDENTITY_CREDENTIAL_KEY:
387         case KM_TAG_BOOTLOADER_ONLY:
388             return KM_ERROR_INVALID_KEY_BLOB;
389 
390         case KM_TAG_EARLY_BOOT_ONLY:
391             if (!in_early_boot()) return KM_ERROR_EARLY_BOOT_ENDED;
392             break;
393         }
394     }
395 
396     if (authentication_required && !auth_token_matched) {
397         LOG_E("Auth required but no matching auth token found", 0);
398         return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
399     }
400 
401     if (!caller_nonce_authorized_by_key && is_origination_purpose(purpose) &&
402         operation_params.find(KM_TAG_NONCE) != -1)
403         return KM_ERROR_CALLER_NONCE_PROHIBITED;
404 
405     if (min_ops_timeout != UINT32_MAX) {
406         if (!access_time_map_) {
407             LOG_S("Rate-limited keys table not allocated.  Rate-limited keys disabled", 0);
408             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
409         }
410 
411         if (!access_time_map_->UpdateKeyAccessTime(keyid, get_current_time(), min_ops_timeout)) {
412             LOG_E("Rate-limited keys table full.  Entries will time out.", 0);
413             return KM_ERROR_TOO_MANY_OPERATIONS;
414         }
415     }
416 
417     if (update_access_count) {
418         if (!access_count_map_) {
419             LOG_S("Usage-count limited keys table not allocated.  Count-limited keys disabled", 0);
420             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
421         }
422 
423         if (!access_count_map_->IncrementKeyAccessCount(keyid)) {
424             LOG_E("Usage count-limited keys table full, until reboot.", 0);
425             return KM_ERROR_TOO_MANY_OPERATIONS;
426         }
427     }
428 
429     return KM_ERROR_OK;
430 }
431 
MinTimeBetweenOpsPassed(uint32_t min_time_between,const km_id_t keyid)432 bool KeymasterEnforcement::MinTimeBetweenOpsPassed(uint32_t min_time_between, const km_id_t keyid) {
433     if (!access_time_map_)
434         return false;
435 
436     uint32_t last_access_time;
437     if (!access_time_map_->LastKeyAccessTime(keyid, &last_access_time))
438         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_)
444         return false;
445 
446     uint32_t key_access_count;
447     if (!access_count_map_->KeyAccessCount(keyid, &key_access_count))
448         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", 0);
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 (%d expected, %d found)", sizeof(hw_auth_token_t),
463               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", 0);
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 %llu, need %llu", auth_token->challenge, op_handle);
499         return false;
500     }
501 
502     if (user_secure_id != auth_token->user_id && user_secure_id != auth_token->authenticator_id) {
503         LOG_I("Auth token SIDs %llu and %llu do not match key SID %llu", auth_token->user_id,
504               auth_token->authenticator_id, user_secure_id);
505         return false;
506     }
507 
508     if (auth_type_index < 0 || auth_type_index > static_cast<int>(auth_set.size())) {
509         LOG_E("Auth required but no auth type found", 0);
510         return false;
511     }
512 
513     assert(auth_set[auth_type_index].tag == KM_TAG_USER_AUTH_TYPE);
514     if (auth_set[auth_type_index].tag != KM_TAG_USER_AUTH_TYPE)
515         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 0%uo, but token contained 0%uo",
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)
527             return false;
528 
529         if (auth_token_timed_out(*auth_token, auth_set[auth_timeout_index].integer)) {
530             LOG_E("Auth token has timed out", 0);
531             return false;
532         }
533     }
534 
535     // Survived the whole gauntlet.  We have authentage!
536     return true;
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_)
565         return false;
566 
567     AccessTime new_entry;
568     new_entry.keyid = keyid;
569     new_entry.access_time = current_time;
570     new_entry.timeout = timeout;
571     last_access_list_.push_front(new_entry);
572     return true;
573 }
574 
KeyAccessCount(km_id_t keyid,uint32_t * count) const575 bool AccessCountMap::KeyAccessCount(km_id_t keyid, uint32_t* count) const {
576     for (auto& entry : access_count_list_)
577         if (entry.keyid == keyid) {
578             *count = entry.access_count;
579             return true;
580         }
581     return false;
582 }
583 
IncrementKeyAccessCount(km_id_t keyid)584 bool AccessCountMap::IncrementKeyAccessCount(km_id_t keyid) {
585     for (auto& entry : access_count_list_)
586         if (entry.keyid == keyid) {
587             // Note that the 'if' below will always be true because KM_TAG_MAX_USES_PER_BOOT is a
588             // uint32_t, and as soon as entry.access_count reaches the specified maximum value
589             // operation requests will be rejected and access_count won't be incremented any more.
590             // And, besides, UINT64_MAX is huge.  But we ensure that it doesn't wrap anyway, out of
591             // an abundance of caution.
592             if (entry.access_count < UINT64_MAX)
593                 ++entry.access_count;
594             return true;
595         }
596 
597     if (access_count_list_.size() >= max_size_)
598         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