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