blob: 1a7fa808fd46b73513c92ddfcf8359890ac4de2b [file] [log] [blame]
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001/*
2 * Copyright (C) 2014 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 "keymaster_enforcement.h"
20
21#include <assert.h>
22#include <inttypes.h>
23#include <limits.h>
24#include <string.h>
25
26#include <openssl/evp.h>
27
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010028#include <hardware/hw_auth_token.h>
Logan Chiencdc813f2018-04-23 13:52:28 +080029#include <log/log.h>
30
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010031#include <list>
32
Janis Danisevskis8f737ad2017-11-21 12:30:15 -080033#include <keystore/keystore_hidl_support.h>
34
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010035namespace keystore {
36
37class AccessTimeMap {
38 public:
39 explicit AccessTimeMap(uint32_t max_size) : max_size_(max_size) {}
40
41 /* If the key is found, returns true and fills \p last_access_time. If not found returns
42 * false. */
43 bool LastKeyAccessTime(km_id_t keyid, uint32_t* last_access_time) const;
44
45 /* Updates the last key access time with the currentTime parameter. Adds the key if
46 * needed, returning false if key cannot be added because list is full. */
47 bool UpdateKeyAccessTime(km_id_t keyid, uint32_t current_time, uint32_t timeout);
48
49 private:
50 struct AccessTime {
51 km_id_t keyid;
52 uint32_t access_time;
53 uint32_t timeout;
54 };
55 std::list<AccessTime> last_access_list_;
56 const uint32_t max_size_;
57};
58
59class AccessCountMap {
60 public:
61 explicit AccessCountMap(uint32_t max_size) : max_size_(max_size) {}
62
63 /* If the key is found, returns true and fills \p count. If not found returns
64 * false. */
65 bool KeyAccessCount(km_id_t keyid, uint32_t* count) const;
66
67 /* Increments key access count, adding an entry if the key has never been used. Returns
68 * false if the list has reached maximum size. */
69 bool IncrementKeyAccessCount(km_id_t keyid);
70
71 private:
72 struct AccessCount {
73 km_id_t keyid;
74 uint64_t access_count;
75 };
76 std::list<AccessCount> access_count_list_;
77 const uint32_t max_size_;
78};
79
80bool is_public_key_algorithm(const AuthorizationSet& auth_set) {
81 auto algorithm = auth_set.GetTagValue(TAG_ALGORITHM);
82 return algorithm.isOk() &&
83 (algorithm.value() == Algorithm::RSA || algorithm.value() == Algorithm::EC);
84}
85
86static ErrorCode authorized_purpose(const KeyPurpose purpose, const AuthorizationSet& auth_set) {
87 switch (purpose) {
88 case KeyPurpose::VERIFY:
89 case KeyPurpose::ENCRYPT:
90 case KeyPurpose::SIGN:
91 case KeyPurpose::DECRYPT:
92 if (auth_set.Contains(TAG_PURPOSE, purpose)) return ErrorCode::OK;
93 return ErrorCode::INCOMPATIBLE_PURPOSE;
94
95 default:
96 return ErrorCode::UNSUPPORTED_PURPOSE;
97 }
98}
99
100inline bool is_origination_purpose(KeyPurpose purpose) {
101 return purpose == KeyPurpose::ENCRYPT || purpose == KeyPurpose::SIGN;
102}
103
104inline bool is_usage_purpose(KeyPurpose purpose) {
105 return purpose == KeyPurpose::DECRYPT || purpose == KeyPurpose::VERIFY;
106}
107
108KeymasterEnforcement::KeymasterEnforcement(uint32_t max_access_time_map_size,
109 uint32_t max_access_count_map_size)
110 : access_time_map_(new (std::nothrow) AccessTimeMap(max_access_time_map_size)),
111 access_count_map_(new (std::nothrow) AccessCountMap(max_access_count_map_size)) {}
112
113KeymasterEnforcement::~KeymasterEnforcement() {
114 delete access_time_map_;
115 delete access_count_map_;
116}
117
118ErrorCode KeymasterEnforcement::AuthorizeOperation(const KeyPurpose purpose, const km_id_t keyid,
119 const AuthorizationSet& auth_set,
120 const AuthorizationSet& operation_params,
Shawn Willden0329a822017-12-04 13:55:14 -0700121 const HardwareAuthToken& auth_token,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100122 uint64_t op_handle, bool is_begin_operation) {
123 if (is_public_key_algorithm(auth_set)) {
124 switch (purpose) {
125 case KeyPurpose::ENCRYPT:
126 case KeyPurpose::VERIFY:
127 /* Public key operations are always authorized. */
128 return ErrorCode::OK;
129
130 case KeyPurpose::DECRYPT:
131 case KeyPurpose::SIGN:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100132 break;
Shawn Willden0329a822017-12-04 13:55:14 -0700133
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100134 case KeyPurpose::WRAP_KEY:
135 return ErrorCode::INCOMPATIBLE_PURPOSE;
136 };
137 };
138
139 if (is_begin_operation)
Shawn Willden0329a822017-12-04 13:55:14 -0700140 return AuthorizeBegin(purpose, keyid, auth_set, operation_params, auth_token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100141 else
Shawn Willden0329a822017-12-04 13:55:14 -0700142 return AuthorizeUpdateOrFinish(auth_set, auth_token, op_handle);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100143}
144
145// For update and finish the only thing to check is user authentication, and then only if it's not
146// timeout-based.
147ErrorCode KeymasterEnforcement::AuthorizeUpdateOrFinish(const AuthorizationSet& auth_set,
Shawn Willden0329a822017-12-04 13:55:14 -0700148 const HardwareAuthToken& auth_token,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100149 uint64_t op_handle) {
150 int auth_type_index = -1;
151 for (size_t pos = 0; pos < auth_set.size(); ++pos) {
152 switch (auth_set[pos].tag) {
153 case Tag::NO_AUTH_REQUIRED:
154 case Tag::AUTH_TIMEOUT:
155 // If no auth is required or if auth is timeout-based, we have nothing to check.
156 return ErrorCode::OK;
157
158 case Tag::USER_AUTH_TYPE:
159 auth_type_index = pos;
160 break;
161
162 default:
163 break;
164 }
165 }
166
167 // Note that at this point we should be able to assume that authentication is required, because
168 // authentication is required if KM_TAG_NO_AUTH_REQUIRED is absent. However, there are legacy
169 // keys which have no authentication-related tags, so we assume that absence is equivalent to
170 // presence of KM_TAG_NO_AUTH_REQUIRED.
171 //
172 // So, if we found KM_TAG_USER_AUTH_TYPE or if we find KM_TAG_USER_SECURE_ID then authentication
173 // is required. If we find neither, then we assume authentication is not required and return
174 // success.
175 bool authentication_required = (auth_type_index != -1);
176 for (auto& param : auth_set) {
177 auto user_secure_id = authorizationValue(TAG_USER_SECURE_ID, param);
178 if (user_secure_id.isOk()) {
179 authentication_required = true;
180 int auth_timeout_index = -1;
Shawn Willden0329a822017-12-04 13:55:14 -0700181 if (auth_token.mac.size() &&
182 AuthTokenMatches(auth_set, auth_token, user_secure_id.value(), auth_type_index,
183 auth_timeout_index, op_handle, false /* is_begin_operation */))
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100184 return ErrorCode::OK;
185 }
186 }
187
188 if (authentication_required) return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
189
190 return ErrorCode::OK;
191}
192
193ErrorCode KeymasterEnforcement::AuthorizeBegin(const KeyPurpose purpose, const km_id_t keyid,
194 const AuthorizationSet& auth_set,
Shawn Willden0329a822017-12-04 13:55:14 -0700195 const AuthorizationSet& operation_params,
196 NullOr<const HardwareAuthToken&> auth_token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100197 // Find some entries that may be needed to handle KM_TAG_USER_SECURE_ID
198 int auth_timeout_index = -1;
199 int auth_type_index = -1;
200 int no_auth_required_index = -1;
201 for (size_t pos = 0; pos < auth_set.size(); ++pos) {
202 switch (auth_set[pos].tag) {
203 case Tag::AUTH_TIMEOUT:
204 auth_timeout_index = pos;
205 break;
206 case Tag::USER_AUTH_TYPE:
207 auth_type_index = pos;
208 break;
209 case Tag::NO_AUTH_REQUIRED:
210 no_auth_required_index = pos;
211 break;
212 default:
213 break;
214 }
215 }
216
217 ErrorCode error = authorized_purpose(purpose, auth_set);
218 if (error != ErrorCode::OK) return error;
219
220 // If successful, and if key has a min time between ops, this will be set to the time limit
221 uint32_t min_ops_timeout = UINT32_MAX;
222
223 bool update_access_count = false;
224 bool caller_nonce_authorized_by_key = false;
225 bool authentication_required = false;
226 bool auth_token_matched = false;
Brian Young9a947d52018-02-23 18:03:14 +0000227 bool unlocked_device_required = false;
228 int32_t user_id = -1;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100229
230 for (auto& param : auth_set) {
231
232 // KM_TAG_PADDING_OLD and KM_TAG_DIGEST_OLD aren't actually members of the enum, so we can't
233 // switch on them. There's nothing to validate for them, though, so just ignore them.
234 if (int32_t(param.tag) == KM_TAG_PADDING_OLD || int32_t(param.tag) == KM_TAG_DIGEST_OLD)
235 continue;
236
237 switch (param.tag) {
238
239 case Tag::ACTIVE_DATETIME: {
240 auto date = authorizationValue(TAG_ACTIVE_DATETIME, param);
241 if (date.isOk() && !activation_date_valid(date.value()))
242 return ErrorCode::KEY_NOT_YET_VALID;
243 break;
244 }
245 case Tag::ORIGINATION_EXPIRE_DATETIME: {
246 auto date = authorizationValue(TAG_ORIGINATION_EXPIRE_DATETIME, param);
247 if (is_origination_purpose(purpose) && date.isOk() &&
248 expiration_date_passed(date.value()))
249 return ErrorCode::KEY_EXPIRED;
250 break;
251 }
252 case Tag::USAGE_EXPIRE_DATETIME: {
253 auto date = authorizationValue(TAG_USAGE_EXPIRE_DATETIME, param);
254 if (is_usage_purpose(purpose) && date.isOk() && expiration_date_passed(date.value()))
255 return ErrorCode::KEY_EXPIRED;
256 break;
257 }
258 case Tag::MIN_SECONDS_BETWEEN_OPS: {
259 auto min_ops_timeout = authorizationValue(TAG_MIN_SECONDS_BETWEEN_OPS, param);
260 if (min_ops_timeout.isOk() && !MinTimeBetweenOpsPassed(min_ops_timeout.value(), keyid))
261 return ErrorCode::KEY_RATE_LIMIT_EXCEEDED;
262 break;
263 }
264 case Tag::MAX_USES_PER_BOOT: {
265 auto max_users = authorizationValue(TAG_MAX_USES_PER_BOOT, param);
266 update_access_count = true;
267 if (max_users.isOk() && !MaxUsesPerBootNotExceeded(keyid, max_users.value()))
268 return ErrorCode::KEY_MAX_OPS_EXCEEDED;
269 break;
270 }
271 case Tag::USER_SECURE_ID:
272 if (no_auth_required_index != -1) {
273 // Key has both KM_TAG_USER_SECURE_ID and KM_TAG_NO_AUTH_REQUIRED
274 return ErrorCode::INVALID_KEY_BLOB;
275 }
276
277 if (auth_timeout_index != -1) {
278 auto secure_id = authorizationValue(TAG_USER_SECURE_ID, param);
279 authentication_required = true;
Shawn Willden0329a822017-12-04 13:55:14 -0700280 if (secure_id.isOk() && auth_token.isOk() &&
281 AuthTokenMatches(auth_set, auth_token.value(), secure_id.value(),
282 auth_type_index, auth_timeout_index, 0 /* op_handle */,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100283 true /* is_begin_operation */))
284 auth_token_matched = true;
285 }
286 break;
287
Brian Young9371e952018-02-23 18:03:14 +0000288 case Tag::USER_ID:
Brian Young9a947d52018-02-23 18:03:14 +0000289 user_id = authorizationValue(TAG_USER_ID, param).value();
Brian Young9371e952018-02-23 18:03:14 +0000290 break;
291
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100292 case Tag::CALLER_NONCE:
293 caller_nonce_authorized_by_key = true;
294 break;
295
Brian Young9371e952018-02-23 18:03:14 +0000296 case Tag::UNLOCKED_DEVICE_REQUIRED:
Brian Young9a947d52018-02-23 18:03:14 +0000297 unlocked_device_required = true;
Brian Young9371e952018-02-23 18:03:14 +0000298 break;
299
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100300 /* Tags should never be in key auths. */
301 case Tag::INVALID:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100302 case Tag::ROOT_OF_TRUST:
303 case Tag::APPLICATION_DATA:
304 case Tag::ATTESTATION_CHALLENGE:
305 case Tag::ATTESTATION_APPLICATION_ID:
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +0100306 case Tag::ATTESTATION_ID_BRAND:
307 case Tag::ATTESTATION_ID_DEVICE:
308 case Tag::ATTESTATION_ID_PRODUCT:
309 case Tag::ATTESTATION_ID_SERIAL:
310 case Tag::ATTESTATION_ID_IMEI:
311 case Tag::ATTESTATION_ID_MEID:
Bartosz Fabianowski634a1aa2017-03-20 14:02:32 +0100312 case Tag::ATTESTATION_ID_MANUFACTURER:
313 case Tag::ATTESTATION_ID_MODEL:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100314 return ErrorCode::INVALID_KEY_BLOB;
315
316 /* Tags used for cryptographic parameters in keygen. Nothing to enforce. */
317 case Tag::PURPOSE:
318 case Tag::ALGORITHM:
319 case Tag::KEY_SIZE:
320 case Tag::BLOCK_MODE:
321 case Tag::DIGEST:
322 case Tag::MAC_LENGTH:
323 case Tag::PADDING:
324 case Tag::NONCE:
325 case Tag::MIN_MAC_LENGTH:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100326 case Tag::EC_CURVE:
327
328 /* Tags not used for operations. */
329 case Tag::BLOB_USAGE_REQUIREMENTS:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100330
331 /* Algorithm specific parameters not used for access control. */
332 case Tag::RSA_PUBLIC_EXPONENT:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100333
334 /* Informational tags. */
335 case Tag::CREATION_DATETIME:
336 case Tag::ORIGIN:
Shawn Willden0329a822017-12-04 13:55:14 -0700337 case Tag::ROLLBACK_RESISTANCE:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100338
339 /* Tags handled when KM_TAG_USER_SECURE_ID is handled */
340 case Tag::NO_AUTH_REQUIRED:
341 case Tag::USER_AUTH_TYPE:
342 case Tag::AUTH_TIMEOUT:
343
344 /* Tag to provide data to operations. */
345 case Tag::ASSOCIATED_DATA:
346
347 /* Tags that are implicitly verified by secure side */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100348 case Tag::APPLICATION_ID:
Shawn Willden30adb492018-01-18 18:48:29 -0700349 case Tag::BOOT_PATCHLEVEL:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100350 case Tag::OS_PATCHLEVEL:
Shawn Willden30adb492018-01-18 18:48:29 -0700351 case Tag::OS_VERSION:
Shawn Willden35b6e6c2018-01-10 09:30:12 -0700352 case Tag::TRUSTED_USER_PRESENCE_REQUIRED:
Shawn Willden30adb492018-01-18 18:48:29 -0700353 case Tag::VENDOR_PATCHLEVEL:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100354
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100355 /* TODO(swillden): Handle these */
356 case Tag::INCLUDE_UNIQUE_ID:
357 case Tag::UNIQUE_ID:
358 case Tag::RESET_SINCE_ID_ROTATION:
359 case Tag::ALLOW_WHILE_ON_BODY:
Shawn Willden0329a822017-12-04 13:55:14 -0700360 case Tag::HARDWARE_TYPE:
David Zeuthenc6eb7cd2017-11-27 11:33:55 -0500361 case Tag::TRUSTED_CONFIRMATION_REQUIRED:
362 case Tag::CONFIRMATION_TOKEN:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100363 break;
364
365 case Tag::BOOTLOADER_ONLY:
366 return ErrorCode::INVALID_KEY_BLOB;
367 }
368 }
369
Brian Young9a947d52018-02-23 18:03:14 +0000370 if (unlocked_device_required && is_device_locked(user_id)) {
371 switch (purpose) {
372 case KeyPurpose::ENCRYPT:
373 case KeyPurpose::VERIFY:
374 /* These are okay */
375 break;
376 case KeyPurpose::DECRYPT:
377 case KeyPurpose::SIGN:
378 case KeyPurpose::WRAP_KEY:
379 return ErrorCode::DEVICE_LOCKED;
380 };
381 }
382
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100383 if (authentication_required && !auth_token_matched) {
384 ALOGE("Auth required but no matching auth token found");
385 return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
386 }
387
388 if (!caller_nonce_authorized_by_key && is_origination_purpose(purpose) &&
389 operation_params.Contains(Tag::NONCE))
390 return ErrorCode::CALLER_NONCE_PROHIBITED;
391
392 if (min_ops_timeout != UINT32_MAX) {
393 if (!access_time_map_) {
394 ALOGE("Rate-limited keys table not allocated. Rate-limited keys disabled");
395 return ErrorCode::MEMORY_ALLOCATION_FAILED;
396 }
397
398 if (!access_time_map_->UpdateKeyAccessTime(keyid, get_current_time(), min_ops_timeout)) {
399 ALOGE("Rate-limited keys table full. Entries will time out.");
400 return ErrorCode::TOO_MANY_OPERATIONS;
401 }
402 }
403
404 if (update_access_count) {
405 if (!access_count_map_) {
406 ALOGE("Usage-count limited keys tabel not allocated. Count-limited keys disabled");
407 return ErrorCode::MEMORY_ALLOCATION_FAILED;
408 }
409
410 if (!access_count_map_->IncrementKeyAccessCount(keyid)) {
411 ALOGE("Usage count-limited keys table full, until reboot.");
412 return ErrorCode::TOO_MANY_OPERATIONS;
413 }
414 }
415
416 return ErrorCode::OK;
417}
418
419class EvpMdCtx {
420 public:
421 EvpMdCtx() { EVP_MD_CTX_init(&ctx_); }
422 ~EvpMdCtx() { EVP_MD_CTX_cleanup(&ctx_); }
423
424 EVP_MD_CTX* get() { return &ctx_; }
425
426 private:
427 EVP_MD_CTX ctx_;
428};
429
430/* static */
431bool KeymasterEnforcement::CreateKeyId(const hidl_vec<uint8_t>& key_blob, km_id_t* keyid) {
432 EvpMdCtx ctx;
433
434 uint8_t hash[EVP_MAX_MD_SIZE];
435 unsigned int hash_len;
436 if (EVP_DigestInit_ex(ctx.get(), EVP_sha256(), nullptr /* ENGINE */) &&
437 EVP_DigestUpdate(ctx.get(), &key_blob[0], key_blob.size()) &&
438 EVP_DigestFinal_ex(ctx.get(), hash, &hash_len)) {
439 assert(hash_len >= sizeof(*keyid));
440 memcpy(keyid, hash, sizeof(*keyid));
441 return true;
442 }
443
444 return false;
445}
446
447bool KeymasterEnforcement::MinTimeBetweenOpsPassed(uint32_t min_time_between, const km_id_t keyid) {
448 if (!access_time_map_) return false;
449
450 uint32_t last_access_time;
451 if (!access_time_map_->LastKeyAccessTime(keyid, &last_access_time)) return true;
452 return min_time_between <= static_cast<int64_t>(get_current_time()) - last_access_time;
453}
454
455bool KeymasterEnforcement::MaxUsesPerBootNotExceeded(const km_id_t keyid, uint32_t max_uses) {
456 if (!access_count_map_) return false;
457
458 uint32_t key_access_count;
459 if (!access_count_map_->KeyAccessCount(keyid, &key_access_count)) return true;
460 return key_access_count < max_uses;
461}
462
463template <typename IntType, uint32_t byteOrder> struct choose_hton;
464
465template <typename IntType> struct choose_hton<IntType, __ORDER_LITTLE_ENDIAN__> {
466 inline static IntType hton(const IntType& value) {
467 IntType result = 0;
468 const unsigned char* inbytes = reinterpret_cast<const unsigned char*>(&value);
469 unsigned char* outbytes = reinterpret_cast<unsigned char*>(&result);
470 for (int i = sizeof(IntType) - 1; i >= 0; --i) {
471 *(outbytes++) = inbytes[i];
472 }
473 return result;
474 }
475};
476
477template <typename IntType> struct choose_hton<IntType, __ORDER_BIG_ENDIAN__> {
478 inline static IntType hton(const IntType& value) { return value; }
479};
480
481template <typename IntType> inline IntType hton(const IntType& value) {
482 return choose_hton<IntType, __BYTE_ORDER__>::hton(value);
483}
484
485template <typename IntType> inline IntType ntoh(const IntType& value) {
486 // same operation and hton
487 return choose_hton<IntType, __BYTE_ORDER__>::hton(value);
488}
489
490bool KeymasterEnforcement::AuthTokenMatches(const AuthorizationSet& auth_set,
Shawn Willden0329a822017-12-04 13:55:14 -0700491 const HardwareAuthToken& auth_token,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100492 const uint64_t user_secure_id,
493 const int auth_type_index, const int auth_timeout_index,
494 const uint64_t op_handle,
495 bool is_begin_operation) const {
496 assert(auth_type_index < static_cast<int>(auth_set.size()));
497 assert(auth_timeout_index < static_cast<int>(auth_set.size()));
498
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100499 if (!ValidateTokenSignature(auth_token)) {
500 ALOGE("Auth token signature invalid");
501 return false;
502 }
503
504 if (auth_timeout_index == -1 && op_handle && op_handle != auth_token.challenge) {
505 ALOGE("Auth token has the challenge %" PRIu64 ", need %" PRIu64, auth_token.challenge,
506 op_handle);
507 return false;
508 }
509
Janis Danisevskis8f737ad2017-11-21 12:30:15 -0800510 if (user_secure_id != auth_token.userId && user_secure_id != auth_token.authenticatorId) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100511 ALOGI("Auth token SIDs %" PRIu64 " and %" PRIu64 " do not match key SID %" PRIu64,
Janis Danisevskis8f737ad2017-11-21 12:30:15 -0800512 auth_token.userId, auth_token.authenticatorId, user_secure_id);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100513 return false;
514 }
515
516 if (auth_type_index < 0 || auth_type_index > static_cast<int>(auth_set.size())) {
517 ALOGE("Auth required but no auth type found");
518 return false;
519 }
520
Janis Danisevskis8f737ad2017-11-21 12:30:15 -0800521 assert(auth_set[auth_type_index].tag == TAG_USER_AUTH_TYPE);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100522 auto key_auth_type_mask = authorizationValue(TAG_USER_AUTH_TYPE, auth_set[auth_type_index]);
523 if (!key_auth_type_mask.isOk()) return false;
524
Shawn Willden0329a822017-12-04 13:55:14 -0700525 if ((uint32_t(key_auth_type_mask.value()) & auth_token.authenticatorType) == 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100526 ALOGE("Key requires match of auth type mask 0%uo, but token contained 0%uo",
Shawn Willden0329a822017-12-04 13:55:14 -0700527 key_auth_type_mask.value(), auth_token.authenticatorType);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100528 return false;
529 }
530
531 if (auth_timeout_index != -1 && is_begin_operation) {
Janis Danisevskis8f737ad2017-11-21 12:30:15 -0800532 assert(auth_set[auth_timeout_index].tag == TAG_AUTH_TIMEOUT);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100533 auto auth_token_timeout =
534 authorizationValue(TAG_AUTH_TIMEOUT, auth_set[auth_timeout_index]);
535 if (!auth_token_timeout.isOk()) return false;
536
537 if (auth_token_timed_out(auth_token, auth_token_timeout.value())) {
538 ALOGE("Auth token has timed out");
539 return false;
540 }
541 }
542
543 // Survived the whole gauntlet. We have authentage!
544 return true;
545}
546
547bool AccessTimeMap::LastKeyAccessTime(km_id_t keyid, uint32_t* last_access_time) const {
548 for (auto& entry : last_access_list_)
549 if (entry.keyid == keyid) {
550 *last_access_time = entry.access_time;
551 return true;
552 }
553 return false;
554}
555
556bool AccessTimeMap::UpdateKeyAccessTime(km_id_t keyid, uint32_t current_time, uint32_t timeout) {
557 for (auto iter = last_access_list_.begin(); iter != last_access_list_.end();) {
558 if (iter->keyid == keyid) {
559 iter->access_time = current_time;
560 return true;
561 }
562
563 // Expire entry if possible.
564 assert(current_time >= iter->access_time);
565 if (current_time - iter->access_time >= iter->timeout)
566 iter = last_access_list_.erase(iter);
567 else
568 ++iter;
569 }
570
571 if (last_access_list_.size() >= max_size_) return false;
572
573 AccessTime new_entry;
574 new_entry.keyid = keyid;
575 new_entry.access_time = current_time;
576 new_entry.timeout = timeout;
577 last_access_list_.push_front(new_entry);
578 return true;
579}
580
581bool AccessCountMap::KeyAccessCount(km_id_t keyid, uint32_t* count) const {
582 for (auto& entry : access_count_list_)
583 if (entry.keyid == keyid) {
584 *count = entry.access_count;
585 return true;
586 }
587 return false;
588}
589
590bool AccessCountMap::IncrementKeyAccessCount(km_id_t keyid) {
591 for (auto& entry : access_count_list_)
592 if (entry.keyid == keyid) {
593 // Note that the 'if' below will always be true because KM_TAG_MAX_USES_PER_BOOT is a
594 // uint32_t, and as soon as entry.access_count reaches the specified maximum value
595 // operation requests will be rejected and access_count won't be incremented any more.
596 // And, besides, UINT64_MAX is huge. But we ensure that it doesn't wrap anyway, out of
597 // an abundance of caution.
598 if (entry.access_count < UINT64_MAX) ++entry.access_count;
599 return true;
600 }
601
602 if (access_count_list_.size() >= max_size_) return false;
603
604 AccessCount new_entry;
605 new_entry.keyid = keyid;
606 new_entry.access_count = 1;
607 access_count_list_.push_front(new_entry);
608 return true;
609}
610}; /* namespace keystore */