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