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 
29 #include "List.h"
30 
31 using android::List;
32 
33 namespace keymaster {
34 
35 class AccessTimeMap {
36   public:
AccessTimeMap(uint32_t max_size)37     AccessTimeMap(uint32_t max_size) : max_size_(max_size) {}
38 
39     /* If the key is found, returns true and fills \p last_access_time.  If not found returns
40      * false. */
41     bool LastKeyAccessTime(km_id_t keyid, uint32_t* last_access_time) const;
42 
43     /* Updates the last key access time with the currentTime parameter.  Adds the key if
44      * needed, returning false if key cannot be added because list is full. */
45     bool UpdateKeyAccessTime(km_id_t keyid, uint32_t current_time, uint32_t timeout);
46 
47   private:
48     struct AccessTime {
49         km_id_t keyid;
50         uint32_t access_time;
51         uint32_t timeout;
52     };
53     android::List<AccessTime> last_access_list_;
54     const uint32_t max_size_;
55 };
56 
57 class AccessCountMap {
58   public:
AccessCountMap(uint32_t max_size)59     AccessCountMap(uint32_t max_size) : max_size_(max_size) {}
60 
61     /* If the key is found, returns true and fills \p count.  If not found returns
62      * false. */
63     bool KeyAccessCount(km_id_t keyid, uint32_t* count) const;
64 
65     /* Increments key access count, adding an entry if the key has never been used.  Returns
66      * false if the list has reached maximum size. */
67     bool IncrementKeyAccessCount(km_id_t keyid);
68 
69   private:
70     struct AccessCount {
71         km_id_t keyid;
72         uint64_t access_count;
73     };
74     android::List<AccessCount> access_count_list_;
75     const uint32_t max_size_;
76 };
77 
is_public_key_algorithm(const AuthorizationSet & auth_set)78 bool is_public_key_algorithm(const AuthorizationSet& auth_set) {
79     keymaster_algorithm_t algorithm;
80     return auth_set.GetTagValue(TAG_ALGORITHM, &algorithm) &&
81            (algorithm == KM_ALGORITHM_RSA || algorithm == KM_ALGORITHM_EC);
82 }
83 
authorized_purpose(const keymaster_purpose_t purpose,const AuthorizationSet & auth_set)84 static keymaster_error_t authorized_purpose(const keymaster_purpose_t purpose,
85                                             const AuthorizationSet& auth_set) {
86     switch (purpose) {
87     case KM_PURPOSE_VERIFY:
88     case KM_PURPOSE_ENCRYPT:
89     case KM_PURPOSE_SIGN:
90     case KM_PURPOSE_DECRYPT:
91         if (auth_set.Contains(TAG_PURPOSE, purpose))
92             return KM_ERROR_OK;
93         return KM_ERROR_INCOMPATIBLE_PURPOSE;
94 
95     default:
96         return KM_ERROR_UNSUPPORTED_PURPOSE;
97     }
98 }
99 
is_origination_purpose(keymaster_purpose_t purpose)100 inline bool is_origination_purpose(keymaster_purpose_t purpose) {
101     return purpose == KM_PURPOSE_ENCRYPT || purpose == KM_PURPOSE_SIGN;
102 }
103 
is_usage_purpose(keymaster_purpose_t purpose)104 inline bool is_usage_purpose(keymaster_purpose_t purpose) {
105     return purpose == KM_PURPOSE_DECRYPT || purpose == KM_PURPOSE_VERIFY;
106 }
107 
KeymasterEnforcement(uint32_t max_access_time_map_size,uint32_t max_access_count_map_size)108 KeymasterEnforcement::KeymasterEnforcement(uint32_t max_access_time_map_size,
109                                            uint32_t max_access_count_map_size)
110     : access_time_map_(new (std::nothrow) AccessTimeMap(max_access_time_map_size)),
111       access_count_map_(new (std::nothrow) AccessCountMap(max_access_count_map_size)) {}
112 
~KeymasterEnforcement()113 KeymasterEnforcement::~KeymasterEnforcement() {
114     delete access_time_map_;
115     delete access_count_map_;
116 }
117 
AuthorizeOperation(const keymaster_purpose_t purpose,const km_id_t keyid,const AuthorizationSet & auth_set,const AuthorizationSet & operation_params,keymaster_operation_handle_t op_handle,bool is_begin_operation)118 keymaster_error_t KeymasterEnforcement::AuthorizeOperation(const keymaster_purpose_t purpose,
119                                                            const km_id_t keyid,
120                                                            const AuthorizationSet& auth_set,
121                                                            const AuthorizationSet& operation_params,
122                                                            keymaster_operation_handle_t op_handle,
123                                                            bool is_begin_operation) {
124     if (is_public_key_algorithm(auth_set)) {
125         switch (purpose) {
126         case KM_PURPOSE_ENCRYPT:
127         case KM_PURPOSE_VERIFY:
128             /* Public key operations are always authorized. */
129             return KM_ERROR_OK;
130 
131         case KM_PURPOSE_DECRYPT:
132         case KM_PURPOSE_SIGN:
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 AuthorizationSet & auth_set,const AuthorizationSet & operation_params,keymaster_operation_handle_t op_handle)146 KeymasterEnforcement::AuthorizeUpdateOrFinish(const AuthorizationSet& auth_set,
147                                               const AuthorizationSet& operation_params,
148                                               keymaster_operation_handle_t op_handle) {
149     int auth_type_index = -1;
150     for (size_t pos = 0; pos < auth_set.size(); ++pos) {
151         switch (auth_set[pos].tag) {
152         case KM_TAG_NO_AUTH_REQUIRED:
153         case KM_TAG_AUTH_TIMEOUT:
154             // If no auth is required or if auth is timeout-based, we have nothing to check.
155             return KM_ERROR_OK;
156 
157         case KM_TAG_USER_AUTH_TYPE:
158             auth_type_index = pos;
159             break;
160 
161         default:
162             break;
163         }
164     }
165 
166     // Note that at this point we should be able to assume that authentication is required, because
167     // authentication is required if KM_TAG_NO_AUTH_REQUIRED is absent.  However, there are legacy
168     // keys which have no authentication-related tags, so we assume that absence is equivalent to
169     // presence of KM_TAG_NO_AUTH_REQUIRED.
170     //
171     // So, if we found KM_TAG_USER_AUTH_TYPE or if we find KM_TAG_USER_SECURE_ID then authentication
172     // is required.  If we find neither, then we assume authentication is not required and return
173     // success.
174     bool authentication_required = (auth_type_index != -1);
175     for (auto& param : auth_set) {
176         if (param.tag == KM_TAG_USER_SECURE_ID) {
177             authentication_required = true;
178             int auth_timeout_index = -1;
179             if (AuthTokenMatches(auth_set, operation_params, param.long_integer, auth_type_index,
180                                  auth_timeout_index, op_handle, false /* is_begin_operation */))
181                 return KM_ERROR_OK;
182         }
183     }
184 
185     if (authentication_required)
186         return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
187 
188     return KM_ERROR_OK;
189 }
190 
AuthorizeBegin(const keymaster_purpose_t purpose,const km_id_t keyid,const AuthorizationSet & auth_set,const AuthorizationSet & operation_params)191 keymaster_error_t KeymasterEnforcement::AuthorizeBegin(const keymaster_purpose_t purpose,
192                                                        const km_id_t keyid,
193                                                        const AuthorizationSet& auth_set,
194                                                        const AuthorizationSet& operation_params) {
195     // Find some entries that may be needed to handle KM_TAG_USER_SECURE_ID
196     int auth_timeout_index = -1;
197     int auth_type_index = -1;
198     int no_auth_required_index = -1;
199     for (size_t pos = 0; pos < auth_set.size(); ++pos) {
200         switch (auth_set[pos].tag) {
201         case KM_TAG_AUTH_TIMEOUT:
202             auth_timeout_index = pos;
203             break;
204         case KM_TAG_USER_AUTH_TYPE:
205             auth_type_index = pos;
206             break;
207         case KM_TAG_NO_AUTH_REQUIRED:
208             no_auth_required_index = pos;
209             break;
210         default:
211             break;
212         }
213     }
214 
215     keymaster_error_t error = authorized_purpose(purpose, auth_set);
216     if (error != KM_ERROR_OK)
217         return error;
218 
219     // If successful, and if key has a min time between ops, this will be set to the time limit
220     uint32_t min_ops_timeout = UINT32_MAX;
221 
222     bool update_access_count = false;
223     bool caller_nonce_authorized_by_key = false;
224     bool authentication_required = false;
225     bool auth_token_matched = false;
226 
227     for (auto& param : auth_set) {
228 
229         // KM_TAG_PADDING_OLD and KM_TAG_DIGEST_OLD aren't actually members of the enum, so we can't
230         // switch on them.  There's nothing to validate for them, though, so just ignore them.
231         if (param.tag == KM_TAG_PADDING_OLD || param.tag == KM_TAG_DIGEST_OLD)
232             continue;
233 
234         switch (param.tag) {
235 
236         case KM_TAG_ACTIVE_DATETIME:
237             if (!activation_date_valid(param.date_time))
238                 return KM_ERROR_KEY_NOT_YET_VALID;
239             break;
240 
241         case KM_TAG_ORIGINATION_EXPIRE_DATETIME:
242             if (is_origination_purpose(purpose) && expiration_date_passed(param.date_time))
243                 return KM_ERROR_KEY_EXPIRED;
244             break;
245 
246         case KM_TAG_USAGE_EXPIRE_DATETIME:
247             if (is_usage_purpose(purpose) && expiration_date_passed(param.date_time))
248                 return KM_ERROR_KEY_EXPIRED;
249             break;
250 
251         case KM_TAG_MIN_SECONDS_BETWEEN_OPS:
252             min_ops_timeout = param.integer;
253             if (!MinTimeBetweenOpsPassed(min_ops_timeout, keyid))
254                 return KM_ERROR_KEY_RATE_LIMIT_EXCEEDED;
255             break;
256 
257         case KM_TAG_MAX_USES_PER_BOOT:
258             update_access_count = true;
259             if (!MaxUsesPerBootNotExceeded(keyid, param.integer))
260                 return KM_ERROR_KEY_MAX_OPS_EXCEEDED;
261             break;
262 
263         case KM_TAG_USER_SECURE_ID:
264             if (no_auth_required_index != -1) {
265                 // Key has both KM_TAG_USER_SECURE_ID and KM_TAG_NO_AUTH_REQUIRED
266                 return KM_ERROR_INVALID_KEY_BLOB;
267             }
268 
269             if (auth_timeout_index != -1) {
270                 authentication_required = true;
271                 if (AuthTokenMatches(auth_set, operation_params, param.long_integer,
272                                      auth_type_index, auth_timeout_index, 0 /* op_handle */,
273                                      true /* is_begin_operation */))
274                     auth_token_matched = true;
275             }
276             break;
277 
278         case KM_TAG_CALLER_NONCE:
279             caller_nonce_authorized_by_key = true;
280             break;
281 
282         /* Tags should never be in key auths. */
283         case KM_TAG_INVALID:
284         case KM_TAG_AUTH_TOKEN:
285         case KM_TAG_ROOT_OF_TRUST:
286         case KM_TAG_APPLICATION_DATA:
287             return KM_ERROR_INVALID_KEY_BLOB;
288 
289         /* Tags used for cryptographic parameters in keygen.  Nothing to enforce. */
290         case KM_TAG_PURPOSE:
291         case KM_TAG_ALGORITHM:
292         case KM_TAG_KEY_SIZE:
293         case KM_TAG_BLOCK_MODE:
294         case KM_TAG_DIGEST:
295         case KM_TAG_MAC_LENGTH:
296         case KM_TAG_PADDING:
297         case KM_TAG_NONCE:
298         case KM_TAG_MIN_MAC_LENGTH:
299 
300         /* Tags not used for operations. */
301         case KM_TAG_BLOB_USAGE_REQUIREMENTS:
302 
303         /* Algorithm specific parameters not used for access control. */
304         case KM_TAG_RSA_PUBLIC_EXPONENT:
305 
306         /* Informational tags. */
307         case KM_TAG_CREATION_DATETIME:
308         case KM_TAG_ORIGIN:
309         case KM_TAG_ROLLBACK_RESISTANT:
310 
311         /* Tags handled when KM_TAG_USER_SECURE_ID is handled */
312         case KM_TAG_NO_AUTH_REQUIRED:
313         case KM_TAG_USER_AUTH_TYPE:
314         case KM_TAG_AUTH_TIMEOUT:
315 
316         /* Tag to provide data to operations. */
317         case KM_TAG_ASSOCIATED_DATA:
318 
319         /* Ignored pending removal */
320         case KM_TAG_ALL_APPLICATIONS:
321         case KM_TAG_APPLICATION_ID:
322         case KM_TAG_USER_ID:
323         case KM_TAG_ALL_USERS:
324             break;
325 
326         case KM_TAG_BOOTLOADER_ONLY:
327             return KM_ERROR_INVALID_KEY_BLOB;
328         }
329     }
330 
331     if (authentication_required && !auth_token_matched) {
332         LOG_E("Auth required but no matching auth token found", 0);
333         return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
334     }
335 
336     if (!caller_nonce_authorized_by_key && is_origination_purpose(purpose) &&
337         operation_params.find(KM_TAG_NONCE) != -1)
338         return KM_ERROR_CALLER_NONCE_PROHIBITED;
339 
340     if (min_ops_timeout != UINT32_MAX) {
341         if (!access_time_map_) {
342             LOG_S("Rate-limited keys table not allocated.  Rate-limited keys disabled", 0);
343             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
344         }
345 
346         if (!access_time_map_->UpdateKeyAccessTime(keyid, get_current_time(), min_ops_timeout)) {
347             LOG_E("Rate-limited keys table full.  Entries will time out.", 0);
348             return KM_ERROR_TOO_MANY_OPERATIONS;
349         }
350     }
351 
352     if (update_access_count) {
353         if (!access_count_map_) {
354             LOG_S("Usage-count limited keys tabel not allocated.  Count-limited keys disabled", 0);
355             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
356         }
357 
358         if (!access_count_map_->IncrementKeyAccessCount(keyid)) {
359             LOG_E("Usage count-limited keys table full, until reboot.", 0);
360             return KM_ERROR_TOO_MANY_OPERATIONS;
361         }
362     }
363 
364     return KM_ERROR_OK;
365 }
366 
367 class EvpMdCtx {
368   public:
EvpMdCtx()369     EvpMdCtx() { EVP_MD_CTX_init(&ctx_); }
~EvpMdCtx()370     ~EvpMdCtx() { EVP_MD_CTX_cleanup(&ctx_); }
371 
get()372     EVP_MD_CTX* get() { return &ctx_; }
373 
374   private:
375     EVP_MD_CTX ctx_;
376 };
377 
378 /* static */
CreateKeyId(const keymaster_key_blob_t & key_blob,km_id_t * keyid)379 bool KeymasterEnforcement::CreateKeyId(const keymaster_key_blob_t& key_blob, km_id_t* keyid) {
380     EvpMdCtx ctx;
381 
382     uint8_t hash[EVP_MAX_MD_SIZE];
383     unsigned int hash_len;
384     if (EVP_DigestInit_ex(ctx.get(), EVP_sha256(), nullptr /* ENGINE */) &&
385         EVP_DigestUpdate(ctx.get(), key_blob.key_material, key_blob.key_material_size) &&
386         EVP_DigestFinal_ex(ctx.get(), hash, &hash_len)) {
387         assert(hash_len >= sizeof(*keyid));
388         memcpy(keyid, hash, sizeof(*keyid));
389         return true;
390     }
391 
392     return false;
393 }
394 
MinTimeBetweenOpsPassed(uint32_t min_time_between,const km_id_t keyid)395 bool KeymasterEnforcement::MinTimeBetweenOpsPassed(uint32_t min_time_between, const km_id_t keyid) {
396     if (!access_time_map_)
397         return false;
398 
399     uint32_t last_access_time;
400     if (!access_time_map_->LastKeyAccessTime(keyid, &last_access_time))
401         return true;
402     return min_time_between <= static_cast<int64_t>(get_current_time()) - last_access_time;
403 }
404 
MaxUsesPerBootNotExceeded(const km_id_t keyid,uint32_t max_uses)405 bool KeymasterEnforcement::MaxUsesPerBootNotExceeded(const km_id_t keyid, uint32_t max_uses) {
406     if (!access_count_map_)
407         return false;
408 
409     uint32_t key_access_count;
410     if (!access_count_map_->KeyAccessCount(keyid, &key_access_count))
411         return true;
412     return key_access_count < max_uses;
413 }
414 
AuthTokenMatches(const AuthorizationSet & 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) const415 bool KeymasterEnforcement::AuthTokenMatches(const AuthorizationSet& auth_set,
416                                             const AuthorizationSet& operation_params,
417                                             const uint64_t user_secure_id,
418                                             const int auth_type_index, const int auth_timeout_index,
419                                             const keymaster_operation_handle_t op_handle,
420                                             bool is_begin_operation) const {
421     assert(auth_type_index < static_cast<int>(auth_set.size()));
422     assert(auth_timeout_index < static_cast<int>(auth_set.size()));
423 
424     keymaster_blob_t auth_token_blob;
425     if (!operation_params.GetTagValue(TAG_AUTH_TOKEN, &auth_token_blob)) {
426         LOG_E("Authentication required, but auth token not provided", 0);
427         return false;
428     }
429 
430     if (auth_token_blob.data_length != sizeof(hw_auth_token_t)) {
431         LOG_E("Bug: Auth token is the wrong size (%d expected, %d found)", sizeof(hw_auth_token_t),
432               auth_token_blob.data_length);
433         return false;
434     }
435 
436     hw_auth_token_t auth_token;
437     memcpy(&auth_token, auth_token_blob.data, sizeof(hw_auth_token_t));
438     if (auth_token.version != HW_AUTH_TOKEN_VERSION) {
439         LOG_E("Bug: Auth token is the version %d (or is not an auth token). Expected %d",
440               auth_token.version, HW_AUTH_TOKEN_VERSION);
441         return false;
442     }
443 
444     if (!ValidateTokenSignature(auth_token)) {
445         LOG_E("Auth token signature invalid", 0);
446         return false;
447     }
448 
449     if (auth_timeout_index == -1 && op_handle && op_handle != auth_token.challenge) {
450         LOG_E("Auth token has the challenge %llu, need %llu", auth_token.challenge, op_handle);
451         return false;
452     }
453 
454     if (user_secure_id != auth_token.user_id && user_secure_id != auth_token.authenticator_id) {
455         LOG_I("Auth token SIDs %llu and %llu do not match key SID %llu", auth_token.user_id,
456               auth_token.authenticator_id, user_secure_id);
457         return false;
458     }
459 
460     if (auth_type_index < 0 || auth_type_index > static_cast<int>(auth_set.size())) {
461         LOG_E("Auth required but no auth type found", 0);
462         return false;
463     }
464 
465     assert(auth_set[auth_type_index].tag == KM_TAG_USER_AUTH_TYPE);
466     if (auth_set[auth_type_index].tag != KM_TAG_USER_AUTH_TYPE)
467         return false;
468 
469     uint32_t key_auth_type_mask = auth_set[auth_type_index].integer;
470     uint32_t token_auth_type = ntoh(auth_token.authenticator_type);
471     if ((key_auth_type_mask & token_auth_type) == 0) {
472         LOG_E("Key requires match of auth type mask 0%uo, but token contained 0%uo",
473               key_auth_type_mask, token_auth_type);
474         return false;
475     }
476 
477     if (auth_timeout_index != -1 && is_begin_operation) {
478         assert(auth_set[auth_timeout_index].tag == KM_TAG_AUTH_TIMEOUT);
479         if (auth_set[auth_timeout_index].tag != KM_TAG_AUTH_TIMEOUT)
480             return false;
481 
482         if (auth_token_timed_out(auth_token, auth_set[auth_timeout_index].integer)) {
483             LOG_E("Auth token has timed out", 0);
484             return false;
485         }
486     }
487 
488     // Survived the whole gauntlet.  We have authentage!
489     return true;
490 }
491 
LastKeyAccessTime(km_id_t keyid,uint32_t * last_access_time) const492 bool AccessTimeMap::LastKeyAccessTime(km_id_t keyid, uint32_t* last_access_time) const {
493     for (auto& entry : last_access_list_)
494         if (entry.keyid == keyid) {
495             *last_access_time = entry.access_time;
496             return true;
497         }
498     return false;
499 }
500 
UpdateKeyAccessTime(km_id_t keyid,uint32_t current_time,uint32_t timeout)501 bool AccessTimeMap::UpdateKeyAccessTime(km_id_t keyid, uint32_t current_time, uint32_t timeout) {
502     List<AccessTime>::iterator iter;
503     for (iter = last_access_list_.begin(); iter != last_access_list_.end();) {
504         if (iter->keyid == keyid) {
505             iter->access_time = current_time;
506             return true;
507         }
508 
509         // Expire entry if possible.
510         assert(current_time >= iter->access_time);
511         if (current_time - iter->access_time >= iter->timeout)
512             iter = last_access_list_.erase(iter);
513         else
514             ++iter;
515     }
516 
517     if (last_access_list_.size() >= max_size_)
518         return false;
519 
520     AccessTime new_entry;
521     new_entry.keyid = keyid;
522     new_entry.access_time = current_time;
523     new_entry.timeout = timeout;
524     last_access_list_.push_front(new_entry);
525     return true;
526 }
527 
KeyAccessCount(km_id_t keyid,uint32_t * count) const528 bool AccessCountMap::KeyAccessCount(km_id_t keyid, uint32_t* count) const {
529     for (auto& entry : access_count_list_)
530         if (entry.keyid == keyid) {
531             *count = entry.access_count;
532             return true;
533         }
534     return false;
535 }
536 
IncrementKeyAccessCount(km_id_t keyid)537 bool AccessCountMap::IncrementKeyAccessCount(km_id_t keyid) {
538     for (auto& entry : access_count_list_)
539         if (entry.keyid == keyid) {
540             // Note that the 'if' below will always be true because KM_TAG_MAX_USES_PER_BOOT is a
541             // uint32_t, and as soon as entry.access_count reaches the specified maximum value
542             // operation requests will be rejected and access_count won't be incremented any more.
543             // And, besides, UINT64_MAX is huge.  But we ensure that it doesn't wrap anyway, out of
544             // an abundance of caution.
545             if (entry.access_count < UINT64_MAX)
546                 ++entry.access_count;
547             return true;
548         }
549 
550     if (access_count_list_.size() >= max_size_)
551         return false;
552 
553     AccessCount new_entry;
554     new_entry.keyid = keyid;
555     new_entry.access_count = 1;
556     access_count_list_.push_front(new_entry);
557     return true;
558 }
559 }; /* namespace keymaster */
560