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 if (key_info.GetTagValue(TAG_ALLOW_WHILE_ON_BODY)) {
142 if (static_cast<int64_t>(newest_match->time_received()) <
143 static_cast<int64_t>(last_off_body_)) {
144 return AUTH_TOKEN_EXPIRED;
145 }
146 }
147
148 newest_match->UpdateLastUse(now);
149 *found = newest_match->token();
150 return OK;
151 }
152
ExtractSids(const AuthorizationSet & key_info,std::vector<uint64_t> * sids)153 void AuthTokenTable::ExtractSids(const AuthorizationSet& key_info, std::vector<uint64_t>* sids) {
154 assert(sids);
155 for (auto& param : key_info)
156 if (param.tag == TAG_USER_SECURE_ID)
157 sids->push_back(param.long_integer);
158 }
159
RemoveEntriesSupersededBy(const Entry & entry)160 void AuthTokenTable::RemoveEntriesSupersededBy(const Entry& entry) {
161 entries_.erase(remove_if(entries_, [&](Entry& e) { return entry.Supersedes(e); }),
162 entries_.end());
163 }
164
onDeviceOffBody()165 void AuthTokenTable::onDeviceOffBody() {
166 last_off_body_ = clock_function_();
167 }
168
Clear()169 void AuthTokenTable::Clear() {
170 entries_.clear();
171 }
172
IsSupersededBySomeEntry(const Entry & entry)173 bool AuthTokenTable::IsSupersededBySomeEntry(const Entry& entry) {
174 return std::any_of(entries_.begin(), entries_.end(),
175 [&](Entry& e) { return e.Supersedes(entry); });
176 }
177
MarkCompleted(const keymaster_operation_handle_t op_handle)178 void AuthTokenTable::MarkCompleted(const keymaster_operation_handle_t op_handle) {
179 auto found = find_if(entries_, [&](Entry& e) { return e.token()->challenge == op_handle; });
180 if (found == entries_.end())
181 return;
182
183 assert(!IsSupersededBySomeEntry(*found));
184 found->mark_completed();
185
186 if (IsSupersededBySomeEntry(*found))
187 entries_.erase(found);
188 }
189
Entry(const hw_auth_token_t * token,time_t current_time)190 AuthTokenTable::Entry::Entry(const hw_auth_token_t* token, time_t current_time)
191 : token_(token), time_received_(current_time), last_use_(current_time),
192 operation_completed_(token_->challenge == 0) {
193 }
194
timestamp_host_order() const195 uint32_t AuthTokenTable::Entry::timestamp_host_order() const {
196 return ntoh(token_->timestamp);
197 }
198
authenticator_type() const199 hw_authenticator_type_t AuthTokenTable::Entry::authenticator_type() const {
200 hw_authenticator_type_t result = static_cast<hw_authenticator_type_t>(
201 ntoh(static_cast<uint32_t>(token_->authenticator_type)));
202 return result;
203 }
204
SatisfiesAuth(const std::vector<uint64_t> & sids,hw_authenticator_type_t auth_type)205 bool AuthTokenTable::Entry::SatisfiesAuth(const std::vector<uint64_t>& sids,
206 hw_authenticator_type_t auth_type) {
207 for (auto sid : sids)
208 if ((sid == token_->authenticator_id) ||
209 (sid == token_->user_id && (auth_type & authenticator_type()) != 0))
210 return true;
211 return false;
212 }
213
UpdateLastUse(time_t time)214 void AuthTokenTable::Entry::UpdateLastUse(time_t time) {
215 this->last_use_ = time;
216 }
217
Supersedes(const Entry & entry) const218 bool AuthTokenTable::Entry::Supersedes(const Entry& entry) const {
219 if (!entry.completed())
220 return false;
221
222 return (token_->user_id == entry.token_->user_id &&
223 token_->authenticator_type == entry.token_->authenticator_type &&
224 token_->authenticator_type == entry.token_->authenticator_type &&
225 timestamp_host_order() > entry.timestamp_host_order());
226 }
227
228 } // namespace keymaster
229