blob: 971f9eff1350cdee8e8aaff5466e81056460f4b5 [file] [log] [blame]
Shawn Willden489dfe12015-03-17 10:13:27 -06001/*
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
Rubin Xuce99f582017-10-12 10:50:11 +010017#define LOG_TAG "keystore"
18
Shawn Willden489dfe12015-03-17 10:13:27 -060019#include "auth_token_table.h"
20
21#include <assert.h>
22#include <time.h>
23
24#include <algorithm>
25
Logan Chiencdc813f2018-04-23 13:52:28 +080026#include <log/log.h>
Shawn Willden489dfe12015-03-17 10:13:27 -060027
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010028namespace keystore {
29
Shawn Willdend3ed3a22017-03-28 00:39:16 +000030template <typename IntType, uint32_t byteOrder> struct choose_hton;
31
32template <typename IntType> struct choose_hton<IntType, __ORDER_LITTLE_ENDIAN__> {
33 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
44template <typename IntType> struct choose_hton<IntType, __ORDER_BIG_ENDIAN__> {
45 inline static IntType hton(const IntType& value) { return value; }
46};
47
48template <typename IntType> inline IntType hton(const IntType& value) {
49 return choose_hton<IntType, __BYTE_ORDER__>::hton(value);
50}
51
52template <typename IntType> inline IntType ntoh(const IntType& value) {
53 // same operation and hton
54 return choose_hton<IntType, __BYTE_ORDER__>::hton(value);
55}
56
Shawn Willden489dfe12015-03-17 10:13:27 -060057//
58// Some trivial template wrappers around std algorithms, so they take containers not ranges.
59//
60template <typename Container, typename Predicate>
61typename Container::iterator find_if(Container& container, Predicate pred) {
62 return std::find_if(container.begin(), container.end(), pred);
63}
64
65template <typename Container, typename Predicate>
66typename Container::iterator remove_if(Container& container, Predicate pred) {
67 return std::remove_if(container.begin(), container.end(), pred);
68}
69
70template <typename Container> typename Container::iterator min_element(Container& container) {
71 return std::min_element(container.begin(), container.end());
72}
73
74time_t clock_gettime_raw() {
75 struct timespec time;
76 clock_gettime(CLOCK_MONOTONIC_RAW, &time);
77 return time.tv_sec;
78}
79
Shawn Willden0329a822017-12-04 13:55:14 -070080void AuthTokenTable::AddAuthenticationToken(HardwareAuthToken&& auth_token) {
Janis Danisevskis8f737ad2017-11-21 12:30:15 -080081 Entry new_entry(std::move(auth_token), clock_function_());
Shawn Willden0329a822017-12-04 13:55:14 -070082 // 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()));
Rubin Xuce99f582017-10-12 10:50:11 +010086
Janis Danisevskisff3d7f42018-10-08 07:15:09 -070087 std::lock_guard<std::mutex> lock(entries_mutex_);
Shawn Willden489dfe12015-03-17 10:13:27 -060088 RemoveEntriesSupersededBy(new_entry);
89 if (entries_.size() >= max_entries_) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010090 ALOGW("Auth token table filled up; replacing oldest entry");
Shawn Willden489dfe12015-03-17 10:13:27 -060091 *min_element(entries_) = std::move(new_entry);
92 } else {
93 entries_.push_back(std::move(new_entry));
94 }
95}
96
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010097inline bool is_secret_key_operation(Algorithm algorithm, KeyPurpose purpose) {
Shawn Willden0329a822017-12-04 13:55:14 -070098 if ((algorithm != Algorithm::RSA && algorithm != Algorithm::EC)) return true;
99 if (purpose == KeyPurpose::SIGN || purpose == KeyPurpose::DECRYPT) return true;
Shawn Willdenb2ffa422015-06-17 12:18:55 -0600100 return false;
Shawn Willden489dfe12015-03-17 10:13:27 -0600101}
102
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100103inline 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;
Shawn Willdenb2ffa422015-06-17 12:18:55 -0600107}
108
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100109inline 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;
Shawn Willden489dfe12015-03-17 10:13:27 -0600112}
113
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700114std::tuple<AuthTokenTable::Error, HardwareAuthToken>
115AuthTokenTable::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, {}};
Shawn Willden489dfe12015-03-17 10:13:27 -0600121
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100122 auto auth_type =
123 defaultOr(key_info.GetTagValue(TAG_USER_AUTH_TYPE), HardwareAuthenticatorType::NONE);
Shawn Willden489dfe12015-03-17 10:13:27 -0600124
125 std::vector<uint64_t> key_sids;
126 ExtractSids(key_info, &key_sids);
127
Shawn Willdenb2ffa422015-06-17 12:18:55 -0600128 if (KeyRequiresAuthPerOperation(key_info, purpose))
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700129 return FindAuthPerOpAuthorization(key_sids, auth_type, op_handle);
Shawn Willden489dfe12015-03-17 10:13:27 -0600130 else
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700131 return FindTimedAuthorization(key_sids, auth_type, key_info);
Shawn Willden489dfe12015-03-17 10:13:27 -0600132}
133
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700134std::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, {}};
Shawn Willden489dfe12015-03-17 10:13:27 -0600137
138 auto matching_op = find_if(
Janis Danisevskis8f737ad2017-11-21 12:30:15 -0800139 entries_, [&](Entry& e) { return e.token().challenge == op_handle && !e.completed(); });
Shawn Willden489dfe12015-03-17 10:13:27 -0600140
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700141 if (matching_op == entries_.end()) return {AUTH_TOKEN_NOT_FOUND, {}};
Shawn Willden489dfe12015-03-17 10:13:27 -0600142
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700143 if (!matching_op->SatisfiesAuth(sids, auth_type)) return {AUTH_TOKEN_WRONG_SID, {}};
Shawn Willden489dfe12015-03-17 10:13:27 -0600144
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700145 return {OK, matching_op->token()};
Shawn Willden489dfe12015-03-17 10:13:27 -0600146}
147
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700148std::tuple<AuthTokenTable::Error, HardwareAuthToken>
149AuthTokenTable::FindTimedAuthorization(const std::vector<uint64_t>& sids,
150 HardwareAuthenticatorType auth_type,
151 const AuthorizationSet& key_info) {
Yi Konge353f252018-07-30 01:38:39 -0700152 Entry* newest_match = nullptr;
Shawn Willden489dfe12015-03-17 10:13:27 -0600153 for (auto& entry : entries_)
154 if (entry.SatisfiesAuth(sids, auth_type) && entry.is_newer_than(newest_match))
155 newest_match = &entry;
156
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700157 if (!newest_match) return {AUTH_TOKEN_NOT_FOUND, {}};
Shawn Willden489dfe12015-03-17 10:13:27 -0600158
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100159 auto timeout = defaultOr(key_info.GetTagValue(TAG_AUTH_TIMEOUT), 0);
160
Shawn Willden489dfe12015-03-17 10:13:27 -0600161 time_t now = clock_function_();
162 if (static_cast<int64_t>(newest_match->time_received()) + timeout < static_cast<int64_t>(now))
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700163 return {AUTH_TOKEN_EXPIRED, {}};
Shawn Willden489dfe12015-03-17 10:13:27 -0600164
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100165 if (key_info.GetTagValue(TAG_ALLOW_WHILE_ON_BODY).isOk()) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400166 if (static_cast<int64_t>(newest_match->time_received()) <
167 static_cast<int64_t>(last_off_body_)) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700168 return {AUTH_TOKEN_EXPIRED, {}};
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400169 }
170 }
171
Shawn Willden489dfe12015-03-17 10:13:27 -0600172 newest_match->UpdateLastUse(now);
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700173 return {OK, newest_match->token()};
Shawn Willden489dfe12015-03-17 10:13:27 -0600174}
175
David Zeuthenab3e5652019-10-28 13:32:48 -0400176std::tuple<AuthTokenTable::Error, HardwareAuthToken>
177AuthTokenTable::FindAuthorizationForCredstore(uint64_t challenge, uint64_t secureUserId,
178 int64_t authTokenMaxAgeMillis) {
179 std::vector<uint64_t> sids = {secureUserId};
180 HardwareAuthenticatorType auth_type = HardwareAuthenticatorType::ANY;
David Zeuthenab3e5652019-10-28 13:32:48 -0400181 time_t now = clock_function_();
David Zeuthen27407a52021-03-04 16:32:43 -0500182 int64_t nowMillis = now * 1000;
David Zeuthenab3e5652019-10-28 13:32:48 -0400183
David Zeuthen27407a52021-03-04 16:32:43 -0500184 // It's an error to call this without a non-zero challenge.
185 if (challenge == 0) {
186 return {OP_HANDLE_REQUIRED, {}};
David Zeuthenab3e5652019-10-28 13:32:48 -0400187 }
188
David Zeuthen27407a52021-03-04 16:32:43 -0500189 // First see if we can find a token which matches the given challenge. If we
190 // can, return the newest one. We specifically don't care about its age.
191 //
192 Entry* newest_match_for_challenge = nullptr;
193 for (auto& entry : entries_) {
194 if (entry.token().challenge == challenge && !entry.completed() &&
195 entry.SatisfiesAuth(sids, auth_type)) {
196 if (newest_match_for_challenge == nullptr ||
197 entry.is_newer_than(newest_match_for_challenge)) {
198 newest_match_for_challenge = &entry;
199 }
200 }
201 }
202 if (newest_match_for_challenge != nullptr) {
203 newest_match_for_challenge->UpdateLastUse(now);
204 return {OK, newest_match_for_challenge->token()};
205 }
206
207 // If that didn't work, we'll take the most recent token within the specified
208 // deadline, if any. Of course if the deadline is zero it doesn't make sense
209 // to look at all.
210 if (authTokenMaxAgeMillis == 0) {
211 return {AUTH_TOKEN_NOT_FOUND, {}};
212 }
213
David Zeuthenab3e5652019-10-28 13:32:48 -0400214 Entry* newest_match = nullptr;
215 for (auto& entry : entries_) {
216 if (entry.SatisfiesAuth(sids, auth_type) && entry.is_newer_than(newest_match)) {
217 newest_match = &entry;
218 }
219 }
220
221 if (newest_match == nullptr) {
222 return {AUTH_TOKEN_NOT_FOUND, {}};
223 }
224
David Zeuthen27407a52021-03-04 16:32:43 -0500225 int64_t tokenAgeMillis = nowMillis - newest_match->time_received() * 1000;
226 if (tokenAgeMillis >= authTokenMaxAgeMillis) {
227 return {AUTH_TOKEN_EXPIRED, {}};
David Zeuthenab3e5652019-10-28 13:32:48 -0400228 }
229
230 newest_match->UpdateLastUse(now);
231 return {OK, newest_match->token()};
232}
233
Shawn Willden489dfe12015-03-17 10:13:27 -0600234void AuthTokenTable::ExtractSids(const AuthorizationSet& key_info, std::vector<uint64_t>* sids) {
235 assert(sids);
236 for (auto& param : key_info)
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100237 if (param.tag == Tag::USER_SECURE_ID)
238 sids->push_back(authorizationValue(TAG_USER_SECURE_ID, param).value());
Shawn Willden489dfe12015-03-17 10:13:27 -0600239}
240
241void AuthTokenTable::RemoveEntriesSupersededBy(const Entry& entry) {
242 entries_.erase(remove_if(entries_, [&](Entry& e) { return entry.Supersedes(e); }),
243 entries_.end());
244}
245
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400246void AuthTokenTable::onDeviceOffBody() {
247 last_off_body_ = clock_function_();
248}
249
Chad Brubakerbbc76482015-04-16 15:16:44 -0700250void AuthTokenTable::Clear() {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700251 std::lock_guard<std::mutex> lock(entries_mutex_);
252
Chad Brubakerbbc76482015-04-16 15:16:44 -0700253 entries_.clear();
254}
255
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700256size_t AuthTokenTable::size() const {
257 std::lock_guard<std::mutex> lock(entries_mutex_);
258 return entries_.size();
259}
260
Shawn Willden489dfe12015-03-17 10:13:27 -0600261bool AuthTokenTable::IsSupersededBySomeEntry(const Entry& entry) {
262 return std::any_of(entries_.begin(), entries_.end(),
263 [&](Entry& e) { return e.Supersedes(entry); });
264}
265
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100266void AuthTokenTable::MarkCompleted(const uint64_t op_handle) {
Janis Danisevskisff3d7f42018-10-08 07:15:09 -0700267 std::lock_guard<std::mutex> lock(entries_mutex_);
268
Janis Danisevskis8f737ad2017-11-21 12:30:15 -0800269 auto found = find_if(entries_, [&](Entry& e) { return e.token().challenge == op_handle; });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100270 if (found == entries_.end()) return;
Shawn Willden489dfe12015-03-17 10:13:27 -0600271
272 assert(!IsSupersededBySomeEntry(*found));
273 found->mark_completed();
274
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100275 if (IsSupersededBySomeEntry(*found)) entries_.erase(found);
Shawn Willden489dfe12015-03-17 10:13:27 -0600276}
277
Shawn Willden0329a822017-12-04 13:55:14 -0700278AuthTokenTable::Entry::Entry(HardwareAuthToken&& token, time_t current_time)
Janis Danisevskis8f737ad2017-11-21 12:30:15 -0800279 : token_(std::move(token)), time_received_(current_time), last_use_(current_time),
Shawn Willden0329a822017-12-04 13:55:14 -0700280 operation_completed_(token_.challenge == 0) {}
Shawn Willden489dfe12015-03-17 10:13:27 -0600281
282bool AuthTokenTable::Entry::SatisfiesAuth(const std::vector<uint64_t>& sids,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100283 HardwareAuthenticatorType auth_type) {
Shawn Willden0329a822017-12-04 13:55:14 -0700284 for (auto sid : sids) {
285 if (SatisfiesAuth(sid, auth_type)) return true;
286 }
Shawn Willden489dfe12015-03-17 10:13:27 -0600287 return false;
288}
289
290void AuthTokenTable::Entry::UpdateLastUse(time_t time) {
291 this->last_use_ = time;
292}
293
294bool AuthTokenTable::Entry::Supersedes(const Entry& entry) const {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100295 if (!entry.completed()) return false;
Shawn Willden489dfe12015-03-17 10:13:27 -0600296
Shawn Willden0329a822017-12-04 13:55:14 -0700297 return (token_.userId == entry.token_.userId &&
298 token_.authenticatorType == entry.token_.authenticatorType &&
299 token_.authenticatorId == entry.token_.authenticatorId && is_newer_than(&entry));
Shawn Willden489dfe12015-03-17 10:13:27 -0600300}
301
Shawn Willden0329a822017-12-04 13:55:14 -0700302} // namespace keystore