1 /*
2  * Copyright (C) 2015 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 "auth_token_table.h"
18 
19 #include <assert.h>
20 #include <time.h>
21 
22 #include <algorithm>
23 
24 #include <keymaster/android_keymaster_utils.h>
25 #include <keymaster/logger.h>
26 
27 namespace keymaster {
28 
29 //
30 // Some trivial template wrappers around std algorithms, so they take containers not ranges.
31 //
32 template <typename Container, typename Predicate>
find_if(Container & container,Predicate pred)33 typename Container::iterator find_if(Container& container, Predicate pred) {
34     return std::find_if(container.begin(), container.end(), pred);
35 }
36 
37 template <typename Container, typename Predicate>
remove_if(Container & container,Predicate pred)38 typename Container::iterator remove_if(Container& container, Predicate pred) {
39     return std::remove_if(container.begin(), container.end(), pred);
40 }
41 
min_element(Container & container)42 template <typename Container> typename Container::iterator min_element(Container& container) {
43     return std::min_element(container.begin(), container.end());
44 }
45 
clock_gettime_raw()46 time_t clock_gettime_raw() {
47     struct timespec time;
48     clock_gettime(CLOCK_MONOTONIC_RAW, &time);
49     return time.tv_sec;
50 }
51 
AddAuthenticationToken(const hw_auth_token_t * auth_token)52 void AuthTokenTable::AddAuthenticationToken(const hw_auth_token_t* auth_token) {
53     Entry new_entry(auth_token, clock_function_());
54     RemoveEntriesSupersededBy(new_entry);
55     if (entries_.size() >= max_entries_) {
56         LOG_W("Auth token table filled up; replacing oldest entry", 0);
57         *min_element(entries_) = std::move(new_entry);
58     } else {
59         entries_.push_back(std::move(new_entry));
60     }
61 }
62 
is_secret_key_operation(keymaster_algorithm_t algorithm,keymaster_purpose_t purpose)63 inline bool is_secret_key_operation(keymaster_algorithm_t algorithm, keymaster_purpose_t purpose) {
64     if ((algorithm != KM_ALGORITHM_RSA || algorithm != KM_ALGORITHM_EC))
65         return true;
66     if (purpose == KM_PURPOSE_SIGN || purpose == KM_PURPOSE_DECRYPT)
67         return true;
68     return false;
69 }
70 
KeyRequiresAuthentication(const AuthorizationSet & key_info,keymaster_purpose_t purpose)71 inline bool KeyRequiresAuthentication(const AuthorizationSet& key_info,
72                                       keymaster_purpose_t purpose) {
73     keymaster_algorithm_t algorithm = KM_ALGORITHM_AES;
74     key_info.GetTagValue(TAG_ALGORITHM, &algorithm);
75     return is_secret_key_operation(algorithm, purpose) && key_info.find(TAG_NO_AUTH_REQUIRED) == -1;
76 }
77 
KeyRequiresAuthPerOperation(const AuthorizationSet & key_info,keymaster_purpose_t purpose)78 inline bool KeyRequiresAuthPerOperation(const AuthorizationSet& key_info,
79                                         keymaster_purpose_t purpose) {
80     keymaster_algorithm_t algorithm = KM_ALGORITHM_AES;
81     key_info.GetTagValue(TAG_ALGORITHM, &algorithm);
82     return is_secret_key_operation(algorithm, purpose) && key_info.find(TAG_AUTH_TIMEOUT) == -1;
83 }
84 
FindAuthorization(const AuthorizationSet & key_info,keymaster_purpose_t purpose,keymaster_operation_handle_t op_handle,const hw_auth_token_t ** found)85 AuthTokenTable::Error AuthTokenTable::FindAuthorization(const AuthorizationSet& key_info,
86                                                         keymaster_purpose_t purpose,
87                                                         keymaster_operation_handle_t op_handle,
88                                                         const hw_auth_token_t** found) {
89     if (!KeyRequiresAuthentication(key_info, purpose))
90         return AUTH_NOT_REQUIRED;
91 
92     hw_authenticator_type_t auth_type = HW_AUTH_NONE;
93     key_info.GetTagValue(TAG_USER_AUTH_TYPE, &auth_type);
94 
95     std::vector<uint64_t> key_sids;
96     ExtractSids(key_info, &key_sids);
97 
98     if (KeyRequiresAuthPerOperation(key_info, purpose))
99         return FindAuthPerOpAuthorization(key_sids, auth_type, op_handle, found);
100     else
101         return FindTimedAuthorization(key_sids, auth_type, key_info, found);
102 }
103 
FindAuthPerOpAuthorization(const std::vector<uint64_t> & sids,hw_authenticator_type_t auth_type,keymaster_operation_handle_t op_handle,const hw_auth_token_t ** found)104 AuthTokenTable::Error AuthTokenTable::FindAuthPerOpAuthorization(
105     const std::vector<uint64_t>& sids, hw_authenticator_type_t auth_type,
106     keymaster_operation_handle_t op_handle, const hw_auth_token_t** found) {
107     if (op_handle == 0)
108         return OP_HANDLE_REQUIRED;
109 
110     auto matching_op = find_if(
111         entries_, [&](Entry& e) { return e.token()->challenge == op_handle && !e.completed(); });
112 
113     if (matching_op == entries_.end())
114         return AUTH_TOKEN_NOT_FOUND;
115 
116     if (!matching_op->SatisfiesAuth(sids, auth_type))
117         return AUTH_TOKEN_WRONG_SID;
118 
119     *found = matching_op->token();
120     return OK;
121 }
122 
FindTimedAuthorization(const std::vector<uint64_t> & sids,hw_authenticator_type_t auth_type,const AuthorizationSet & key_info,const hw_auth_token_t ** found)123 AuthTokenTable::Error AuthTokenTable::FindTimedAuthorization(const std::vector<uint64_t>& sids,
124                                                              hw_authenticator_type_t auth_type,
125                                                              const AuthorizationSet& key_info,
126                                                              const hw_auth_token_t** found) {
127     Entry* newest_match = NULL;
128     for (auto& entry : entries_)
129         if (entry.SatisfiesAuth(sids, auth_type) && entry.is_newer_than(newest_match))
130             newest_match = &entry;
131 
132     if (!newest_match)
133         return AUTH_TOKEN_NOT_FOUND;
134 
135     uint32_t timeout;
136     key_info.GetTagValue(TAG_AUTH_TIMEOUT, &timeout);
137     time_t now = clock_function_();
138     if (static_cast<int64_t>(newest_match->time_received()) + timeout < static_cast<int64_t>(now))
139         return AUTH_TOKEN_EXPIRED;
140 
141     newest_match->UpdateLastUse(now);
142     *found = newest_match->token();
143     return OK;
144 }
145 
ExtractSids(const AuthorizationSet & key_info,std::vector<uint64_t> * sids)146 void AuthTokenTable::ExtractSids(const AuthorizationSet& key_info, std::vector<uint64_t>* sids) {
147     assert(sids);
148     for (auto& param : key_info)
149         if (param.tag == TAG_USER_SECURE_ID)
150             sids->push_back(param.long_integer);
151 }
152 
RemoveEntriesSupersededBy(const Entry & entry)153 void AuthTokenTable::RemoveEntriesSupersededBy(const Entry& entry) {
154     entries_.erase(remove_if(entries_, [&](Entry& e) { return entry.Supersedes(e); }),
155                    entries_.end());
156 }
157 
Clear()158 void AuthTokenTable::Clear() {
159     entries_.clear();
160 }
161 
IsSupersededBySomeEntry(const Entry & entry)162 bool AuthTokenTable::IsSupersededBySomeEntry(const Entry& entry) {
163     return std::any_of(entries_.begin(), entries_.end(),
164                        [&](Entry& e) { return e.Supersedes(entry); });
165 }
166 
MarkCompleted(const keymaster_operation_handle_t op_handle)167 void AuthTokenTable::MarkCompleted(const keymaster_operation_handle_t op_handle) {
168     auto found = find_if(entries_, [&](Entry& e) { return e.token()->challenge == op_handle; });
169     if (found == entries_.end())
170         return;
171 
172     assert(!IsSupersededBySomeEntry(*found));
173     found->mark_completed();
174 
175     if (IsSupersededBySomeEntry(*found))
176         entries_.erase(found);
177 }
178 
Entry(const hw_auth_token_t * token,time_t current_time)179 AuthTokenTable::Entry::Entry(const hw_auth_token_t* token, time_t current_time)
180     : token_(token), time_received_(current_time), last_use_(current_time),
181       operation_completed_(token_->challenge == 0) {
182 }
183 
timestamp_host_order() const184 uint32_t AuthTokenTable::Entry::timestamp_host_order() const {
185     return ntoh(token_->timestamp);
186 }
187 
authenticator_type() const188 hw_authenticator_type_t AuthTokenTable::Entry::authenticator_type() const {
189     hw_authenticator_type_t result = static_cast<hw_authenticator_type_t>(
190         ntoh(static_cast<uint32_t>(token_->authenticator_type)));
191     return result;
192 }
193 
SatisfiesAuth(const std::vector<uint64_t> & sids,hw_authenticator_type_t auth_type)194 bool AuthTokenTable::Entry::SatisfiesAuth(const std::vector<uint64_t>& sids,
195                                           hw_authenticator_type_t auth_type) {
196     for (auto sid : sids)
197         if ((sid == token_->authenticator_id) ||
198             (sid == token_->user_id && (auth_type & authenticator_type()) != 0))
199             return true;
200     return false;
201 }
202 
UpdateLastUse(time_t time)203 void AuthTokenTable::Entry::UpdateLastUse(time_t time) {
204     this->last_use_ = time;
205 }
206 
Supersedes(const Entry & entry) const207 bool AuthTokenTable::Entry::Supersedes(const Entry& entry) const {
208     if (!entry.completed())
209         return false;
210 
211     return (token_->user_id == entry.token_->user_id &&
212             token_->authenticator_type == entry.token_->authenticator_type &&
213             token_->authenticator_type == entry.token_->authenticator_type &&
214             timestamp_host_order() > entry.timestamp_host_order());
215 }
216 
217 }  // namespace keymaster
218