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 <cutils/log.h>
25 
26 namespace keystore {
27 
28 template <typename IntType, uint32_t byteOrder> struct choose_hton;
29 
30 template <typename IntType> struct choose_hton<IntType, __ORDER_LITTLE_ENDIAN__> {
htonkeystore::choose_hton31     inline static IntType hton(const IntType& value) {
32         IntType result = 0;
33         const unsigned char* inbytes = reinterpret_cast<const unsigned char*>(&value);
34         unsigned char* outbytes = reinterpret_cast<unsigned char*>(&result);
35         for (int i = sizeof(IntType) - 1; i >= 0; --i) {
36             *(outbytes++) = inbytes[i];
37         }
38         return result;
39     }
40 };
41 
42 template <typename IntType> struct choose_hton<IntType, __ORDER_BIG_ENDIAN__> {
htonkeystore::choose_hton43     inline static IntType hton(const IntType& value) { return value; }
44 };
45 
hton(const IntType & value)46 template <typename IntType> inline IntType hton(const IntType& value) {
47     return choose_hton<IntType, __BYTE_ORDER__>::hton(value);
48 }
49 
ntoh(const IntType & value)50 template <typename IntType> inline IntType ntoh(const IntType& value) {
51     // same operation and hton
52     return choose_hton<IntType, __BYTE_ORDER__>::hton(value);
53 }
54 
55 //
56 // Some trivial template wrappers around std algorithms, so they take containers not ranges.
57 //
58 template <typename Container, typename Predicate>
find_if(Container & container,Predicate pred)59 typename Container::iterator find_if(Container& container, Predicate pred) {
60     return std::find_if(container.begin(), container.end(), pred);
61 }
62 
63 template <typename Container, typename Predicate>
remove_if(Container & container,Predicate pred)64 typename Container::iterator remove_if(Container& container, Predicate pred) {
65     return std::remove_if(container.begin(), container.end(), pred);
66 }
67 
min_element(Container & container)68 template <typename Container> typename Container::iterator min_element(Container& container) {
69     return std::min_element(container.begin(), container.end());
70 }
71 
clock_gettime_raw()72 time_t clock_gettime_raw() {
73     struct timespec time;
74     clock_gettime(CLOCK_MONOTONIC_RAW, &time);
75     return time.tv_sec;
76 }
77 
AddAuthenticationToken(const HardwareAuthToken * auth_token)78 void AuthTokenTable::AddAuthenticationToken(const HardwareAuthToken* auth_token) {
79     Entry new_entry(auth_token, clock_function_());
80     RemoveEntriesSupersededBy(new_entry);
81     if (entries_.size() >= max_entries_) {
82         ALOGW("Auth token table filled up; replacing oldest entry");
83         *min_element(entries_) = std::move(new_entry);
84     } else {
85         entries_.push_back(std::move(new_entry));
86     }
87 }
88 
is_secret_key_operation(Algorithm algorithm,KeyPurpose purpose)89 inline bool is_secret_key_operation(Algorithm algorithm, KeyPurpose purpose) {
90     if ((algorithm != Algorithm::RSA && algorithm != Algorithm::EC))
91         return true;
92     if (purpose == KeyPurpose::SIGN || purpose == KeyPurpose::DECRYPT)
93         return true;
94     return false;
95 }
96 
KeyRequiresAuthentication(const AuthorizationSet & key_info,KeyPurpose purpose)97 inline bool KeyRequiresAuthentication(const AuthorizationSet& key_info, KeyPurpose purpose) {
98     auto algorithm = defaultOr(key_info.GetTagValue(TAG_ALGORITHM), Algorithm::AES);
99     return is_secret_key_operation(algorithm, purpose) &&
100            key_info.find(Tag::NO_AUTH_REQUIRED) == -1;
101 }
102 
KeyRequiresAuthPerOperation(const AuthorizationSet & key_info,KeyPurpose purpose)103 inline bool KeyRequiresAuthPerOperation(const AuthorizationSet& key_info, KeyPurpose purpose) {
104     auto algorithm = defaultOr(key_info.GetTagValue(TAG_ALGORITHM), Algorithm::AES);
105     return is_secret_key_operation(algorithm, purpose) && key_info.find(Tag::AUTH_TIMEOUT) == -1;
106 }
107 
FindAuthorization(const AuthorizationSet & key_info,KeyPurpose purpose,uint64_t op_handle,const HardwareAuthToken ** found)108 AuthTokenTable::Error AuthTokenTable::FindAuthorization(const AuthorizationSet& key_info,
109                                                         KeyPurpose purpose, uint64_t op_handle,
110                                                         const HardwareAuthToken** found) {
111     if (!KeyRequiresAuthentication(key_info, purpose)) return AUTH_NOT_REQUIRED;
112 
113     auto auth_type =
114         defaultOr(key_info.GetTagValue(TAG_USER_AUTH_TYPE), HardwareAuthenticatorType::NONE);
115 
116     std::vector<uint64_t> key_sids;
117     ExtractSids(key_info, &key_sids);
118 
119     if (KeyRequiresAuthPerOperation(key_info, purpose))
120         return FindAuthPerOpAuthorization(key_sids, auth_type, op_handle, found);
121     else
122         return FindTimedAuthorization(key_sids, auth_type, key_info, found);
123 }
124 
125 AuthTokenTable::Error
FindAuthPerOpAuthorization(const std::vector<uint64_t> & sids,HardwareAuthenticatorType auth_type,uint64_t op_handle,const HardwareAuthToken ** found)126 AuthTokenTable::FindAuthPerOpAuthorization(const std::vector<uint64_t>& sids,
127                                            HardwareAuthenticatorType auth_type, uint64_t op_handle,
128                                            const HardwareAuthToken** found) {
129     if (op_handle == 0) return OP_HANDLE_REQUIRED;
130 
131     auto matching_op = find_if(
132         entries_, [&](Entry& e) { return e.token()->challenge == op_handle && !e.completed(); });
133 
134     if (matching_op == entries_.end()) return AUTH_TOKEN_NOT_FOUND;
135 
136     if (!matching_op->SatisfiesAuth(sids, auth_type)) return AUTH_TOKEN_WRONG_SID;
137 
138     *found = matching_op->token();
139     return OK;
140 }
141 
FindTimedAuthorization(const std::vector<uint64_t> & sids,HardwareAuthenticatorType auth_type,const AuthorizationSet & key_info,const HardwareAuthToken ** found)142 AuthTokenTable::Error AuthTokenTable::FindTimedAuthorization(const std::vector<uint64_t>& sids,
143                                                              HardwareAuthenticatorType auth_type,
144                                                              const AuthorizationSet& key_info,
145                                                              const HardwareAuthToken** found) {
146     Entry* newest_match = NULL;
147     for (auto& entry : entries_)
148         if (entry.SatisfiesAuth(sids, auth_type) && entry.is_newer_than(newest_match))
149             newest_match = &entry;
150 
151     if (!newest_match) return AUTH_TOKEN_NOT_FOUND;
152 
153     auto timeout = defaultOr(key_info.GetTagValue(TAG_AUTH_TIMEOUT), 0);
154 
155     time_t now = clock_function_();
156     if (static_cast<int64_t>(newest_match->time_received()) + timeout < static_cast<int64_t>(now))
157         return AUTH_TOKEN_EXPIRED;
158 
159     if (key_info.GetTagValue(TAG_ALLOW_WHILE_ON_BODY).isOk()) {
160         if (static_cast<int64_t>(newest_match->time_received()) <
161             static_cast<int64_t>(last_off_body_)) {
162             return AUTH_TOKEN_EXPIRED;
163         }
164     }
165 
166     newest_match->UpdateLastUse(now);
167     *found = newest_match->token();
168     return OK;
169 }
170 
ExtractSids(const AuthorizationSet & key_info,std::vector<uint64_t> * sids)171 void AuthTokenTable::ExtractSids(const AuthorizationSet& key_info, std::vector<uint64_t>* sids) {
172     assert(sids);
173     for (auto& param : key_info)
174         if (param.tag == Tag::USER_SECURE_ID)
175             sids->push_back(authorizationValue(TAG_USER_SECURE_ID, param).value());
176 }
177 
RemoveEntriesSupersededBy(const Entry & entry)178 void AuthTokenTable::RemoveEntriesSupersededBy(const Entry& entry) {
179     entries_.erase(remove_if(entries_, [&](Entry& e) { return entry.Supersedes(e); }),
180                    entries_.end());
181 }
182 
onDeviceOffBody()183 void AuthTokenTable::onDeviceOffBody() {
184     last_off_body_ = clock_function_();
185 }
186 
Clear()187 void AuthTokenTable::Clear() {
188     entries_.clear();
189 }
190 
IsSupersededBySomeEntry(const Entry & entry)191 bool AuthTokenTable::IsSupersededBySomeEntry(const Entry& entry) {
192     return std::any_of(entries_.begin(), entries_.end(),
193                        [&](Entry& e) { return e.Supersedes(entry); });
194 }
195 
MarkCompleted(const uint64_t op_handle)196 void AuthTokenTable::MarkCompleted(const uint64_t op_handle) {
197     auto found = find_if(entries_, [&](Entry& e) { return e.token()->challenge == op_handle; });
198     if (found == entries_.end()) return;
199 
200     assert(!IsSupersededBySomeEntry(*found));
201     found->mark_completed();
202 
203     if (IsSupersededBySomeEntry(*found)) entries_.erase(found);
204 }
205 
Entry(const HardwareAuthToken * token,time_t current_time)206 AuthTokenTable::Entry::Entry(const HardwareAuthToken* token, time_t current_time)
207     : token_(token), time_received_(current_time), last_use_(current_time),
208       operation_completed_(token_->challenge == 0) {}
209 
timestamp_host_order() const210 uint32_t AuthTokenTable::Entry::timestamp_host_order() const {
211     return ntoh(token_->timestamp);
212 }
213 
authenticator_type() const214 HardwareAuthenticatorType AuthTokenTable::Entry::authenticator_type() const {
215     HardwareAuthenticatorType result = static_cast<HardwareAuthenticatorType>(
216         ntoh(static_cast<uint32_t>(token_->authenticatorType)));
217     return result;
218 }
219 
SatisfiesAuth(const std::vector<uint64_t> & sids,HardwareAuthenticatorType auth_type)220 bool AuthTokenTable::Entry::SatisfiesAuth(const std::vector<uint64_t>& sids,
221                                           HardwareAuthenticatorType auth_type) {
222     for (auto sid : sids)
223         if ((sid == token_->authenticatorId) ||
224             (sid == token_->userId && (auth_type & authenticator_type()) != 0))
225             return true;
226     return false;
227 }
228 
UpdateLastUse(time_t time)229 void AuthTokenTable::Entry::UpdateLastUse(time_t time) {
230     this->last_use_ = time;
231 }
232 
Supersedes(const Entry & entry) const233 bool AuthTokenTable::Entry::Supersedes(const Entry& entry) const {
234     if (!entry.completed()) return false;
235 
236     return (token_->userId == entry.token_->userId &&
237             token_->authenticatorType == entry.token_->authenticatorType &&
238             token_->authenticatorType == entry.token_->authenticatorType &&
239             timestamp_host_order() > entry.timestamp_host_order());
240 }
241 
242 }  // namespace keymaster
243