auth_token_table.cpp 8.7 KB

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