1 /*
2 * Copyright (C) 2016 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 "key_store_service.h"
20
21 #include <fcntl.h>
22 #include <sys/stat.h>
23
24 #include <algorithm>
25 #include <atomic>
26 #include <sstream>
27
28 #include <android-base/scopeguard.h>
29 #include <binder/IInterface.h>
30 #include <binder/IPCThreadState.h>
31 #include <binder/IPermissionController.h>
32 #include <binder/IServiceManager.h>
33 #include <cutils/multiuser.h>
34 #include <log/log_event_list.h>
35
36 #include <private/android_filesystem_config.h>
37 #include <private/android_logger.h>
38
39 #include <android/hardware/confirmationui/1.0/IConfirmationUI.h>
40 #include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
41 #include <keymasterV4_0/keymaster_utils.h>
42
43 #include "defaults.h"
44 #include "key_proto_handler.h"
45 #include "keystore_keymaster_enforcement.h"
46 #include "keystore_utils.h"
47 #include <keystore/keystore_attestation_id.h>
48 #include <keystore/keystore_hidl_support.h>
49 #include <keystore/keystore_return_types.h>
50
51 #include <hardware/hw_auth_token.h>
52
53 namespace keystore {
54
55 using namespace android;
56
57 namespace {
58
59 using ::android::binder::Status;
60 using android::hardware::keymaster::V4_0::support::authToken2HidlVec;
61 using android::hardware::keymaster::V4_0::support::serializeVerificationToken;
62 using android::security::keymaster::ExportResult;
63 using android::security::keymaster::KeymasterArguments;
64 using android::security::keymaster::KeymasterBlob;
65 using android::security::keymaster::KeymasterCertificateChain;
66 using android::security::keymaster::operationFailed;
67 using android::security::keymaster::OperationResult;
68 using ConfirmationResponseCode = android::hardware::confirmationui::V1_0::ResponseCode;
69 using ::android::security::keystore::ICredstoreTokenCallback;
70 using ::android::security::keystore::IKeystoreOperationResultCallback;
71 using ::android::security::keystore::IKeystoreResponseCallback;
72 using ::android::security::keystore::KeystoreResponse;
73
74 constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
75 const char* kTimestampFilePath = "timestamp";
76
containsTag(const hidl_vec<KeyParameter> & params,Tag tag)77 bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
78 return params.end() !=
79 std::find_if(params.begin(), params.end(),
80 [&](const KeyParameter& param) { return param.tag == tag; });
81 }
82
83 #define AIDL_RETURN(rc) (*_aidl_return = KeyStoreServiceReturnCode(rc).getErrorCode(), Status::ok())
84
hadFactoryResetSinceIdRotation()85 std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
86 struct stat sbuf;
87 if (stat(kTimestampFilePath, &sbuf) == 0) {
88 double diff_secs = difftime(time(nullptr), sbuf.st_ctime);
89 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
90 }
91
92 if (errno != ENOENT) {
93 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
94 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
95 }
96
97 int fd = creat(kTimestampFilePath, 0600);
98 if (fd < 0) {
99 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
100 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
101 }
102
103 if (close(fd)) {
104 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
105 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
106 }
107
108 return {ResponseCode::NO_ERROR, true};
109 }
110
111 using ::android::security::KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE;
112
updateParamsForAttestation(uid_t callingUid,AuthorizationSet * params)113 KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
114 KeyStoreServiceReturnCode responseCode;
115 bool factoryResetSinceIdRotation;
116 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
117
118 if (!responseCode.isOk()) return responseCode;
119 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
120
121 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
122 if (!asn1_attestation_id_result.isOk()) {
123 ALOGE("failed to gather attestation_id");
124 // Couldn't get attestation ID; just use an empty one rather than failing.
125 asn1_attestation_id_result = std::vector<uint8_t>();
126 }
127 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
128
129 /*
130 * The attestation application ID must not be longer than
131 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, error out if gather_attestation_application_id
132 * returned such an invalid vector.
133 */
134 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
135 ALOGE("BUG: Gathered Attestation Application ID is too big (%d)",
136 static_cast<int32_t>(asn1_attestation_id.size()));
137 return ErrorCode::CANNOT_ATTEST_IDS;
138 }
139
140 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
141
142 return ResponseCode::NO_ERROR;
143 }
144
145 } // anonymous namespace
146
getState(int32_t userId,int32_t * aidl_return)147 Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
148 if (!checkBinderPermission(P_GET_STATE)) {
149 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
150 return Status::ok();
151 }
152 *aidl_return = mKeyStore->getState(userId);
153 return Status::ok();
154 }
155
get(const String16 & name,int32_t uid,::std::vector<uint8_t> * item)156 Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
157 uid_t targetUid = getEffectiveUid(uid);
158 if (!checkBinderPermission(P_GET, targetUid)) {
159 // see keystore/keystore.h
160 return Status::fromServiceSpecificError(
161 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
162 }
163
164 String8 name8(name);
165 ResponseCode rc;
166 Blob keyBlob;
167 Blob charBlob;
168 LockedKeyBlobEntry lockedEntry;
169
170 std::tie(rc, keyBlob, charBlob, lockedEntry) =
171 mKeyStore->getKeyForName(name8, targetUid, TYPE_GENERIC);
172 if (rc != ResponseCode::NO_ERROR) {
173 *item = ::std::vector<uint8_t>();
174 // Return empty array if key is not found
175 // TODO: consider having returned value nullable or parse exception on the client.
176 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
177 }
178 auto resultBlob = blob2hidlVec(keyBlob);
179 // The static_cast here is needed to prevent a move, forcing a deep copy.
180 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
181 return Status::ok();
182 }
183
insert(const String16 & name,const::std::vector<uint8_t> & item,int targetUid,int32_t flags,int32_t * aidl_return)184 Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
185 int targetUid, int32_t flags, int32_t* aidl_return) {
186 targetUid = getEffectiveUid(targetUid);
187 KeyStoreServiceReturnCode result =
188 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
189 if (!result.isOk()) {
190 *aidl_return = result.getErrorCode();
191 return Status::ok();
192 }
193
194 String8 name8(name);
195 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), targetUid);
196
197 if (!lockedEntry) {
198 ALOGE("failed to grab lock on blob entry %u_%s", targetUid, name8.string());
199 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_ALREADY_EXISTS);
200 return Status::ok();
201 }
202
203 Blob keyBlob(&item[0], item.size(), nullptr, 0, ::TYPE_GENERIC);
204 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
205
206 *aidl_return = static_cast<int32_t>(mKeyStore->put(lockedEntry, keyBlob, {}));
207 return Status::ok();
208 }
209
del(const String16 & name,int targetUid,int32_t * aidl_return)210 Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
211 targetUid = getEffectiveUid(targetUid);
212 if (!checkBinderPermission(P_DELETE, targetUid)) {
213 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
214 return Status::ok();
215 }
216 String8 name8(name);
217 ALOGI("del %s %d", name8.string(), targetUid);
218 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
219 if (!lockedEntry) {
220 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
221 return Status::ok();
222 }
223
224 ResponseCode result = mKeyStore->del(lockedEntry);
225
226 *aidl_return = static_cast<int32_t>(result);
227 return Status::ok();
228 }
229
exist(const String16 & name,int targetUid,int32_t * aidl_return)230 Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
231 targetUid = getEffectiveUid(targetUid);
232 if (!checkBinderPermission(P_EXIST, targetUid)) {
233 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
234 return Status::ok();
235 }
236
237 LockedKeyBlobEntry lockedEntry =
238 mKeyStore->getLockedBlobEntryIfExists(String8(name).string(), targetUid);
239 *aidl_return =
240 static_cast<int32_t>(lockedEntry ? ResponseCode::NO_ERROR : ResponseCode::KEY_NOT_FOUND);
241 return Status::ok();
242 }
243
list(const String16 & prefix,int32_t targetUid,::std::vector<::android::String16> * matches)244 Status KeyStoreService::list(const String16& prefix, int32_t targetUid,
245 ::std::vector<::android::String16>* matches) {
246 targetUid = getEffectiveUid(targetUid);
247 if (!checkBinderPermission(P_LIST, targetUid)) {
248 return Status::fromServiceSpecificError(
249 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
250 }
251 const String8 prefix8(prefix);
252 const std::string stdPrefix(prefix8.string());
253
254 ResponseCode rc;
255 std::list<LockedKeyBlobEntry> internal_matches;
256 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
257
258 std::tie(rc, internal_matches) =
259 LockedKeyBlobEntry::list(userDirName, [&](uid_t uid, const std::string& alias) {
260 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end());
261 return uid == static_cast<uid_t>(targetUid) &&
262 std::mismatch(stdPrefix.begin(), stdPrefix.end(), alias.begin(), alias.end())
263 .first == stdPrefix.end();
264 });
265
266 if (rc != ResponseCode::NO_ERROR) {
267 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
268 }
269
270 for (LockedKeyBlobEntry& entry : internal_matches) {
271 matches->push_back(String16(entry->alias().substr(prefix8.size()).c_str()));
272 }
273 return Status::ok();
274 }
275
276 /*
277 * This method will return the uids of all auth bound keys for the calling user.
278 * This is intended to be used for alerting the user about which apps will be affected
279 * if the password/pin is removed. Only allowed to be called by system.
280 * The output is bound by the initial size of uidsOut to be compatible with Java.
281 */
listUidsOfAuthBoundKeys(std::vector<std::string> * uidsOut,int32_t * aidl_return)282 Status KeyStoreService::listUidsOfAuthBoundKeys(std::vector<std::string>* uidsOut,
283 int32_t* aidl_return) {
284 const int32_t callingUid = IPCThreadState::self()->getCallingUid();
285 const int32_t userId = get_user_id(callingUid);
286 const int32_t appId = get_app_id(callingUid);
287 if (appId != AID_SYSTEM) {
288 ALOGE("Permission listUidsOfAuthBoundKeys denied for aid %d", appId);
289 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
290 return Status::ok();
291 }
292
293 const String8 prefix8("");
294 auto userState = mKeyStore->getUserStateDB().getUserState(userId);
295 const std::string userDirName = userState->getUserDirName();
296 auto encryptionKey = userState->getEncryptionKey();
297 auto state = userState->getState();
298 // unlock the user state
299 userState = {};
300
301 ResponseCode rc;
302 std::list<LockedKeyBlobEntry> internal_matches;
303 std::tie(rc, internal_matches) =
304 LockedKeyBlobEntry::list(userDirName, [&](uid_t, const std::string&) {
305 // Need to filter on auth bound state, so just return true.
306 return true;
307 });
308 if (rc != ResponseCode::NO_ERROR) {
309 ALOGE("Error listing blob entries for user %d", userId);
310 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
311 }
312
313 for (LockedKeyBlobEntry& entry : internal_matches) {
314 // Need to store uids as a list of strings because integer list output
315 // parameters is not supported in aidl-cpp.
316 std::string entryUid = std::to_string(entry->uid());
317 if (std::find(uidsOut->begin(), uidsOut->end(), entryUid) != uidsOut->end()) {
318 // uid already in list, skip
319 continue;
320 }
321
322 auto [rc, blob, charBlob] = entry.readBlobs(encryptionKey, state);
323 if (rc != ResponseCode::NO_ERROR && rc != ResponseCode::LOCKED) {
324 ALOGE("Error reading blob for key %s", entry->alias().c_str());
325 continue;
326 }
327
328 if (blob && blob.isEncrypted()) {
329 uidsOut->push_back(entryUid);
330 } else if (charBlob) {
331 auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
332 if (!success) {
333 ALOGE("Error reading blob characteristics for key %s", entry->alias().c_str());
334 continue;
335 }
336 if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
337 swEnforced.Contains(TAG_USER_SECURE_ID)) {
338 uidsOut->push_back(entryUid);
339 }
340 }
341 }
342 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
343 return Status::ok();
344 }
345
onUserPasswordChanged(int32_t userId,const String16 & password,int32_t * aidl_return)346 Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
347 int32_t* aidl_return) {
348 if (!checkBinderPermission(P_PASSWORD)) {
349 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
350 return Status::ok();
351 }
352
353 if (password.size() == 0) {
354 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
355 mKeyStore->resetUser(userId, true);
356 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
357 return Status::ok();
358 } else {
359 const String8 password8(password);
360 switch (mKeyStore->getState(userId)) {
361 case ::STATE_UNINITIALIZED: {
362 // generate master key, encrypt with password, write to file,
363 // initialize mMasterKey*.
364 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
365 return Status::ok();
366 }
367 case ::STATE_NO_ERROR: {
368 // rewrite master key with new password.
369 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
370 return Status::ok();
371 }
372 case ::STATE_LOCKED: {
373 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
374 mKeyStore->resetUser(userId, true);
375 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
376 return Status::ok();
377 }
378 }
379 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
380 return Status::ok();
381 }
382 }
383
onUserAdded(int32_t userId,int32_t parentId,int32_t * aidl_return)384 Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
385 if (!checkBinderPermission(P_USER_CHANGED)) {
386 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
387 return Status::ok();
388 }
389
390 // Sanity check that the new user has an empty keystore.
391 if (!mKeyStore->isEmpty(userId)) {
392 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
393 }
394 // Unconditionally clear the keystore, just to be safe.
395 mKeyStore->resetUser(userId, false);
396 if (parentId != -1) {
397 // This profile must share the same master key password as the parent profile. Because the
398 // password of the parent profile is not known here, the best we can do is copy the parent's
399 // master key and master key file. This makes this profile use the same master key as the
400 // parent profile, forever.
401 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
402 return Status::ok();
403 } else {
404 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
405 return Status::ok();
406 }
407 }
408
onUserRemoved(int32_t userId,int32_t * aidl_return)409 Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
410 if (!checkBinderPermission(P_USER_CHANGED)) {
411 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
412 return Status::ok();
413 }
414
415 mKeyStore->resetUser(userId, false);
416 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
417 return Status::ok();
418 }
419
lock(int32_t userId,int32_t * aidl_return)420 Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
421 if (!checkBinderPermission(P_LOCK)) {
422 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
423 return Status::ok();
424 }
425
426 State state = mKeyStore->getState(userId);
427 if (state != ::STATE_NO_ERROR) {
428 ALOGD("calling lock in state: %d", state);
429 *aidl_return = static_cast<int32_t>(ResponseCode(state));
430 return Status::ok();
431 }
432
433 mKeyStore->getEnforcementPolicy().set_device_locked(true, userId);
434 mKeyStore->lock(userId);
435 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
436 return Status::ok();
437 }
438
unlock(int32_t userId,const String16 & pw,int32_t * aidl_return)439 Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
440 if (!checkBinderPermission(P_UNLOCK)) {
441 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
442 return Status::ok();
443 }
444
445 State state = mKeyStore->getState(userId);
446 if (state != ::STATE_LOCKED) {
447 switch (state) {
448 case ::STATE_NO_ERROR:
449 ALOGI("calling unlock when already unlocked, ignoring.");
450 break;
451 case ::STATE_UNINITIALIZED:
452 ALOGE("unlock called on uninitialized keystore.");
453 break;
454 default:
455 ALOGE("unlock called on keystore in unknown state: %d", state);
456 break;
457 }
458 *aidl_return = static_cast<int32_t>(ResponseCode(state));
459 return Status::ok();
460 }
461
462 mKeyStore->getEnforcementPolicy().set_device_locked(false, userId);
463 const String8 password8(pw);
464 // read master key, decrypt with password, initialize mMasterKey*.
465 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
466 return Status::ok();
467 }
468
isEmpty(int32_t userId,int32_t * aidl_return)469 Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
470 if (!checkBinderPermission(P_IS_EMPTY)) {
471 *aidl_return = static_cast<int32_t>(false);
472 return Status::ok();
473 }
474
475 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
476 return Status::ok();
477 }
478
grant(const String16 & name,int32_t granteeUid,::android::String16 * aidl_return)479 Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
480 ::android::String16* aidl_return) {
481 uid_t callingUid = IPCThreadState::self()->getCallingUid();
482 auto result =
483 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
484 if (!result.isOk()) {
485 *aidl_return = String16();
486 return Status::ok();
487 }
488
489 String8 name8(name);
490 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
491 if (!lockedEntry) {
492 *aidl_return = String16();
493 return Status::ok();
494 }
495
496 *aidl_return = String16(mKeyStore->addGrant(lockedEntry, granteeUid).c_str());
497 return Status::ok();
498 }
499
ungrant(const String16 & name,int32_t granteeUid,int32_t * aidl_return)500 Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
501 uid_t callingUid = IPCThreadState::self()->getCallingUid();
502 KeyStoreServiceReturnCode result =
503 checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
504 if (!result.isOk()) {
505 *aidl_return = result.getErrorCode();
506 return Status::ok();
507 }
508
509 String8 name8(name);
510
511 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), callingUid);
512 if (!lockedEntry) {
513 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
514 }
515
516 *aidl_return = mKeyStore->removeGrant(lockedEntry, granteeUid);
517 return Status::ok();
518 }
519
getmtime(const String16 & name,int32_t uid,int64_t * time)520 Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
521 uid_t targetUid = getEffectiveUid(uid);
522 if (!checkBinderPermission(P_GET, targetUid)) {
523 ALOGW("permission denied for %d: getmtime", targetUid);
524 *time = -1L;
525 return Status::ok();
526 }
527 String8 name8(name);
528
529 auto lockedEntry = mKeyStore->getLockedBlobEntryIfExists(name8.string(), targetUid);
530 if (!lockedEntry) {
531 ALOGW("could not access key with alias %s for getmtime", name8.string());
532 *time = -1L;
533 return Status::ok();
534 }
535
536 std::string filename = lockedEntry->getKeyBlobPath();
537
538 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_NOFOLLOW, O_RDONLY));
539 if (fd < 0) {
540 ALOGW("could not open %s for getmtime", filename.c_str());
541 *time = -1L;
542 return Status::ok();
543 }
544
545 struct stat s;
546 int ret = fstat(fd, &s);
547 close(fd);
548 if (ret == -1) {
549 ALOGW("could not stat %s for getmtime", filename.c_str());
550 *time = -1L;
551 return Status::ok();
552 }
553
554 *time = static_cast<int64_t>(s.st_mtime);
555 return Status::ok();
556 }
557
is_hardware_backed(const String16 & keyType,int32_t * aidl_return)558 Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
559 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
560 return Status::ok();
561 }
562
clear_uid(int64_t targetUid64,int32_t * _aidl_return)563 Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* _aidl_return) {
564 uid_t targetUid = getEffectiveUid(targetUid64);
565 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
566 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
567 }
568 ALOGI("clear_uid %" PRId64, targetUid64);
569
570 mKeyStore->removeAllGrantsToUid(targetUid);
571
572 ResponseCode rc;
573 std::list<LockedKeyBlobEntry> entries;
574 auto userDirName = mKeyStore->getUserStateDB().getUserStateByUid(targetUid)->getUserDirName();
575
576 // list has a fence making sure no workers are modifying blob files before iterating the
577 // data base. All returned entries are locked.
578 std::tie(rc, entries) = LockedKeyBlobEntry::list(
579 userDirName, [&](uid_t uid, const std::string&) -> bool { return uid == targetUid; });
580
581 if (rc != ResponseCode::NO_ERROR) {
582 return AIDL_RETURN(rc);
583 }
584
585 for (LockedKeyBlobEntry& lockedEntry : entries) {
586 if (get_app_id(targetUid) == AID_SYSTEM) {
587 Blob keyBlob;
588 Blob charBlob;
589 std::tie(rc, keyBlob, charBlob) = mKeyStore->get(lockedEntry);
590 if (rc == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
591 // Do not clear keys critical to device encryption under system uid.
592 continue;
593 }
594 }
595 mKeyStore->del(lockedEntry);
596 }
597 return AIDL_RETURN(ResponseCode::NO_ERROR);
598 }
599
addRngEntropy(const::android::sp<::android::security::keystore::IKeystoreResponseCallback> & cb,const::std::vector<uint8_t> & entropy,int32_t flags,int32_t * _aidl_return)600 Status KeyStoreService::addRngEntropy(
601 const ::android::sp<::android::security::keystore::IKeystoreResponseCallback>& cb,
602 const ::std::vector<uint8_t>& entropy, int32_t flags, int32_t* _aidl_return) {
603 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
604 if (!device) {
605 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
606 }
607
608 device->addRngEntropy(entropy, [device, cb](Return<ErrorCode> rc) {
609 cb->onFinished(KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device, rc)));
610 });
611
612 return AIDL_RETURN(ResponseCode::NO_ERROR);
613 }
614
generateKey(const::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback> & cb,const String16 & name,const KeymasterArguments & params,const::std::vector<uint8_t> & entropy,int uid,int flags,int32_t * _aidl_return)615 Status KeyStoreService::generateKey(
616 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
617 const String16& name, const KeymasterArguments& params, const ::std::vector<uint8_t>& entropy,
618 int uid, int flags, int32_t* _aidl_return) {
619 uid = getEffectiveUid(uid);
620 auto logOnScopeExit = android::base::make_scope_guard([&] {
621 if (__android_log_security()) {
622 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
623 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
624 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
625 }
626 });
627 KeyStoreServiceReturnCode rc =
628 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
629 if (!rc.isOk()) {
630 return AIDL_RETURN(rc);
631 }
632 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
633 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
634 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
635 }
636
637 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
638 if (!checkBinderPermission(P_GEN_UNIQUE_ID)) {
639 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
640 }
641 }
642
643 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
644 auto dev = mKeyStore->getDevice(securityLevel);
645 if (!dev) {
646 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
647 }
648
649 String8 name8(name);
650 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
651 if (!lockedEntry) {
652 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
653 }
654
655 logOnScopeExit.Disable();
656
657 dev->generateKey(
658 std::move(lockedEntry), params.getParameters(), entropy, flags,
659 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
660 if (__android_log_security()) {
661 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
662 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
663 }
664 cb->onFinished(rc,
665 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
666 });
667
668 return AIDL_RETURN(ResponseCode::NO_ERROR);
669 }
670
getKeyCharacteristics(const::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback> & cb,const String16 & name,const::android::security::keymaster::KeymasterBlob & clientId,const::android::security::keymaster::KeymasterBlob & appData,int32_t uid,int32_t * _aidl_return)671 Status KeyStoreService::getKeyCharacteristics(
672 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
673 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
674 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
675 int32_t* _aidl_return) {
676
677 uid_t targetUid = getEffectiveUid(uid);
678 uid_t callingUid = IPCThreadState::self()->getCallingUid();
679 if (!is_granted_to(callingUid, targetUid)) {
680 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
681 targetUid);
682 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
683 }
684
685 String8 name8(name);
686
687 ResponseCode rc;
688 Blob keyBlob;
689 Blob charBlob;
690 LockedKeyBlobEntry lockedEntry;
691
692 std::tie(rc, keyBlob, charBlob, lockedEntry) =
693 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
694
695 if (rc != ResponseCode::NO_ERROR) {
696 return AIDL_RETURN(rc);
697 }
698
699 auto dev = mKeyStore->getDevice(keyBlob);
700 if (!dev) {
701 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
702 }
703
704 // If the charBlob is up to date, it simply moves the argument blobs to the returned blobs
705 // and extracts the characteristics on the way. Otherwise it updates the cache file with data
706 // from keymaster. It may also upgrade the key blob.
707 dev->getKeyCharacteristics(
708 std::move(lockedEntry), clientId.getData(), appData.getData(), std::move(keyBlob),
709 std::move(charBlob),
710 [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
711 cb->onFinished(rc,
712 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
713 });
714
715 return AIDL_RETURN(ResponseCode::NO_ERROR);
716 }
717
importKey(const::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback> & cb,const String16 & name,const KeymasterArguments & params,int32_t format,const::std::vector<uint8_t> & keyData,int uid,int flags,int32_t * _aidl_return)718 Status KeyStoreService::importKey(
719 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
720 const String16& name, const KeymasterArguments& params, int32_t format,
721 const ::std::vector<uint8_t>& keyData, int uid, int flags, int32_t* _aidl_return) {
722 uid = getEffectiveUid(uid);
723 auto logOnScopeExit = android::base::make_scope_guard([&] {
724 if (__android_log_security()) {
725 android_log_event_list(SEC_TAG_KEY_IMPORTED)
726 << int32_t(*_aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
727 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
728 }
729 });
730 KeyStoreServiceReturnCode rc =
731 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
732 if (!rc.isOk()) {
733 LOG(ERROR) << "permissission denied";
734 return AIDL_RETURN(rc);
735 }
736 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
737 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
738 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
739 }
740
741 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
742 auto dev = mKeyStore->getDevice(securityLevel);
743 if (!dev) {
744 LOG(ERROR) << "importKey - cound not get keymaster device";
745 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
746 }
747
748 String8 name8(name);
749 auto lockedEntry = mKeyStore->getLockedBlobEntryIfNotExists(name8.string(), uid);
750 if (!lockedEntry) {
751 LOG(ERROR) << "importKey - key: " << name8.string() << " " << int(uid)
752 << " already exists.";
753 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
754 }
755
756 logOnScopeExit.Disable();
757
758 dev->importKey(
759 std::move(lockedEntry), params.getParameters(), KeyFormat(format), keyData, flags,
760 [cb, uid, name](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
761 if (__android_log_security()) {
762 android_log_event_list(SEC_TAG_KEY_IMPORTED)
763 << rc.isOk() << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
764 }
765 cb->onFinished(rc,
766 android::security::keymaster::KeyCharacteristics(keyCharacteristics));
767 });
768
769 return AIDL_RETURN(ResponseCode::NO_ERROR);
770 }
771
exportKey(const::android::sp<::android::security::keystore::IKeystoreExportKeyCallback> & cb,const String16 & name,int32_t format,const::android::security::keymaster::KeymasterBlob & clientId,const::android::security::keymaster::KeymasterBlob & appData,int32_t uid,int32_t * _aidl_return)772 Status KeyStoreService::exportKey(
773 const ::android::sp<::android::security::keystore::IKeystoreExportKeyCallback>& cb,
774 const String16& name, int32_t format,
775 const ::android::security::keymaster::KeymasterBlob& clientId,
776 const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
777 int32_t* _aidl_return) {
778
779 uid_t targetUid = getEffectiveUid(uid);
780 uid_t callingUid = IPCThreadState::self()->getCallingUid();
781 if (!is_granted_to(callingUid, targetUid)) {
782 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
783 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
784 }
785
786 String8 name8(name);
787
788 KeyStoreServiceReturnCode rc;
789 Blob keyBlob;
790 Blob charBlob;
791 LockedKeyBlobEntry lockedEntry;
792
793 std::tie(rc, keyBlob, charBlob, lockedEntry) =
794 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
795 if (!rc.isOk()) {
796 return AIDL_RETURN(rc);
797 }
798
799 auto dev = mKeyStore->getDevice(keyBlob);
800
801 dev->exportKey(std::move(lockedEntry), KeyFormat(format), clientId.getData(), appData.getData(),
802 std::move(keyBlob), std::move(charBlob),
803 [cb](ExportResult exportResult) { cb->onFinished(exportResult); });
804
805 return AIDL_RETURN(ResponseCode::NO_ERROR);
806 }
807
begin(const sp<IKeystoreOperationResultCallback> & cb,const sp<IBinder> & appToken,const String16 & name,int32_t purpose,bool pruneable,const KeymasterArguments & params,const::std::vector<uint8_t> & entropy,int32_t uid,int32_t * _aidl_return)808 Status KeyStoreService::begin(const sp<IKeystoreOperationResultCallback>& cb,
809 const sp<IBinder>& appToken, const String16& name, int32_t purpose,
810 bool pruneable, const KeymasterArguments& params,
811 const ::std::vector<uint8_t>& entropy, int32_t uid,
812 int32_t* _aidl_return) {
813 uid_t callingUid = IPCThreadState::self()->getCallingUid();
814 uid_t targetUid = getEffectiveUid(uid);
815 if (!is_granted_to(callingUid, targetUid)) {
816 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
817 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
818 }
819 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
820 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
821 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
822 }
823 if (!checkAllowedOperationParams(params.getParameters())) {
824 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
825 }
826
827 String8 name8(name);
828 Blob keyBlob;
829 Blob charBlob;
830 LockedKeyBlobEntry lockedEntry;
831 ResponseCode rc;
832
833 std::tie(rc, keyBlob, charBlob, lockedEntry) =
834 mKeyStore->getKeyForName(name8, targetUid, TYPE_KEYMASTER_10);
835
836 if (rc == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
837 return AIDL_RETURN(ErrorCode::KEY_USER_NOT_AUTHENTICATED);
838 }
839 if (rc != ResponseCode::NO_ERROR) return AIDL_RETURN(rc);
840
841 auto dev = mKeyStore->getDevice(keyBlob);
842 AuthorizationSet opParams = params.getParameters();
843
844 dev->begin(std::move(lockedEntry), appToken, std::move(keyBlob), std::move(charBlob), pruneable,
845 static_cast<KeyPurpose>(purpose), std::move(opParams), entropy,
846 [this, cb, dev](OperationResult result_) {
847 if (result_.resultCode.isOk() ||
848 result_.resultCode == ResponseCode::OP_AUTH_NEEDED) {
849 mKeyStore->addOperationDevice(result_.token, dev);
850 }
851 cb->onFinished(result_);
852 });
853
854 return AIDL_RETURN(ResponseCode::NO_ERROR);
855 }
856
update(const::android::sp<IKeystoreOperationResultCallback> & cb,const::android::sp<::android::IBinder> & token,const::android::security::keymaster::KeymasterArguments & params,const::std::vector<uint8_t> & input,int32_t * _aidl_return)857 Status KeyStoreService::update(const ::android::sp<IKeystoreOperationResultCallback>& cb,
858 const ::android::sp<::android::IBinder>& token,
859 const ::android::security::keymaster::KeymasterArguments& params,
860 const ::std::vector<uint8_t>& input, int32_t* _aidl_return) {
861 if (!checkAllowedOperationParams(params.getParameters())) {
862 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
863 }
864
865 auto dev = mKeyStore->getOperationDevice(token);
866 if (!dev) {
867 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
868 }
869
870 dev->update(token, params.getParameters(), input, [this, cb, token](OperationResult result_) {
871 if (!result_.resultCode.isOk()) {
872 mKeyStore->removeOperationDevice(token);
873 }
874 cb->onFinished(result_);
875 });
876
877 return AIDL_RETURN(ResponseCode::NO_ERROR);
878 }
879
finish(const::android::sp<IKeystoreOperationResultCallback> & cb,const::android::sp<::android::IBinder> & token,const::android::security::keymaster::KeymasterArguments & params,const::std::vector<uint8_t> & input,const::std::vector<uint8_t> & signature,const::std::vector<uint8_t> & entropy,int32_t * _aidl_return)880 Status KeyStoreService::finish(const ::android::sp<IKeystoreOperationResultCallback>& cb,
881 const ::android::sp<::android::IBinder>& token,
882 const ::android::security::keymaster::KeymasterArguments& params,
883 const ::std::vector<uint8_t>& input,
884 const ::std::vector<uint8_t>& signature,
885 const ::std::vector<uint8_t>& entropy, int32_t* _aidl_return) {
886 if (!checkAllowedOperationParams(params.getParameters())) {
887 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
888 }
889
890 auto dev = mKeyStore->getOperationDevice(token);
891 if (!dev) {
892 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
893 }
894
895 dev->finish(token, params.getParameters(), input, signature, entropy,
896 [this, cb, token](OperationResult result_) {
897 mKeyStore->removeOperationDevice(token);
898 cb->onFinished(result_);
899 });
900
901 return AIDL_RETURN(ResponseCode::NO_ERROR);
902 }
903
abort(const::android::sp<IKeystoreResponseCallback> & cb,const::android::sp<::android::IBinder> & token,int32_t * _aidl_return)904 Status KeyStoreService::abort(const ::android::sp<IKeystoreResponseCallback>& cb,
905 const ::android::sp<::android::IBinder>& token,
906 int32_t* _aidl_return) {
907 auto dev = mKeyStore->getOperationDevice(token);
908 if (!dev) {
909 return AIDL_RETURN(ErrorCode::INVALID_OPERATION_HANDLE);
910 }
911
912 dev->abort(token, [this, cb, token](KeyStoreServiceReturnCode rc) {
913 mKeyStore->removeOperationDevice(token);
914 cb->onFinished(rc);
915 });
916
917 return AIDL_RETURN(ResponseCode::NO_ERROR);
918 }
919
addAuthToken(const::std::vector<uint8_t> & authTokenAsVector,int32_t * aidl_return)920 Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
921 int32_t* aidl_return) {
922
923 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
924 // receive a HardwareAuthToken, rather than an opaque byte array.
925
926 if (!checkBinderPermission(P_ADD_AUTH)) {
927 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
928 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
929 return Status::ok();
930 }
931 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
932 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
933 return Status::ok();
934 }
935
936 hw_auth_token_t authToken;
937 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
938 if (authToken.version != 0) {
939 *aidl_return = KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT).getErrorCode();
940 return Status::ok();
941 }
942
943 mKeyStore->getAuthTokenTable().AddAuthenticationToken(
944 hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
945 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
946 return Status::ok();
947 }
948
getTokensForCredstore(int64_t challenge,int64_t secureUserId,int32_t authTokenMaxAgeMillis,const::android::sp<ICredstoreTokenCallback> & cb)949 Status KeyStoreService::getTokensForCredstore(int64_t challenge, int64_t secureUserId,
950 int32_t authTokenMaxAgeMillis,
951 const ::android::sp<ICredstoreTokenCallback>& cb) {
952 uid_t callingUid = IPCThreadState::self()->getCallingUid();
953 if (callingUid != AID_CREDSTORE) {
954 return Status::fromServiceSpecificError(static_cast<int32_t>(0));
955 }
956
957 auto [err, authToken] = mKeyStore->getAuthTokenTable().FindAuthorizationForCredstore(
958 challenge, secureUserId, authTokenMaxAgeMillis);
959 // It's entirely possible we couldn't find an authToken (e.g. no user auth
960 // happened within the requested deadline) and in that case, we just
961 // callback immediately signaling success but just not returning any tokens.
962 if (err != AuthTokenTable::OK) {
963 cb->onFinished(true, {} /* serializedAuthToken */, {} /* serializedVerificationToken */);
964 return Status::ok();
965 }
966
967 // If we did find an authToken, get a verificationToken as well...
968 //
969 std::vector<uint8_t> serializedAuthToken = authToken2HidlVec(authToken);
970 std::vector<uint8_t> serializedVerificationToken;
971 std::shared_ptr<KeymasterWorker> dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
972 if (!dev) {
973 LOG(ERROR) << "Unable to get KM device for SecurityLevel::TRUSTED_ENVIRONMENT";
974 dev = mKeyStore->getDevice(SecurityLevel::SOFTWARE);
975 if (!dev) {
976 LOG(ERROR) << "Unable to get KM device for SecurityLevel::SOFTWARE";
977 cb->onFinished(false, {}, {});
978 return Status::fromServiceSpecificError(static_cast<int32_t>(0));
979 }
980 }
981
982 dev->verifyAuthorization(
983 challenge, {} /* params */, authToken,
984 [serializedAuthToken, cb](KeyStoreServiceReturnCode rc, HardwareAuthToken,
985 VerificationToken verificationToken) {
986 if (rc != ErrorCode::OK) {
987 LOG(ERROR) << "verifyAuthorization failed, rc=" << rc;
988 cb->onFinished(false, {}, {});
989 return;
990 }
991 std::optional<std::vector<uint8_t>> serializedVerificationToken =
992 serializeVerificationToken(verificationToken);
993 if (!serializedVerificationToken) {
994 LOG(ERROR) << "Error serializing verificationToken";
995 cb->onFinished(false, {}, {});
996 return;
997 }
998 cb->onFinished(true, serializedAuthToken, serializedVerificationToken.value());
999 });
1000
1001 return Status::ok();
1002 }
1003
isDeviceIdAttestationTag(Tag tag)1004 bool isDeviceIdAttestationTag(Tag tag) {
1005 switch (tag) {
1006 case Tag::ATTESTATION_ID_BRAND:
1007 case Tag::ATTESTATION_ID_DEVICE:
1008 case Tag::ATTESTATION_ID_MANUFACTURER:
1009 case Tag::ATTESTATION_ID_MODEL:
1010 case Tag::ATTESTATION_ID_PRODUCT:
1011 case Tag::ATTESTATION_ID_IMEI:
1012 case Tag::ATTESTATION_ID_MEID:
1013 case Tag::ATTESTATION_ID_SERIAL:
1014 return true;
1015 case Tag::INVALID:
1016 case Tag::PURPOSE:
1017 case Tag::ALGORITHM:
1018 case Tag::KEY_SIZE:
1019 case Tag::BLOCK_MODE:
1020 case Tag::DIGEST:
1021 case Tag::PADDING:
1022 case Tag::CALLER_NONCE:
1023 case Tag::MIN_MAC_LENGTH:
1024 case Tag::EC_CURVE:
1025 case Tag::RSA_PUBLIC_EXPONENT:
1026 case Tag::INCLUDE_UNIQUE_ID:
1027 case Tag::BLOB_USAGE_REQUIREMENTS:
1028 case Tag::BOOTLOADER_ONLY:
1029 case Tag::ROLLBACK_RESISTANCE:
1030 case Tag::HARDWARE_TYPE:
1031 case Tag::ACTIVE_DATETIME:
1032 case Tag::ORIGINATION_EXPIRE_DATETIME:
1033 case Tag::USAGE_EXPIRE_DATETIME:
1034 case Tag::MIN_SECONDS_BETWEEN_OPS:
1035 case Tag::MAX_USES_PER_BOOT:
1036 case Tag::USER_ID:
1037 case Tag::USER_SECURE_ID:
1038 case Tag::NO_AUTH_REQUIRED:
1039 case Tag::USER_AUTH_TYPE:
1040 case Tag::AUTH_TIMEOUT:
1041 case Tag::ALLOW_WHILE_ON_BODY:
1042 case Tag::TRUSTED_USER_PRESENCE_REQUIRED:
1043 case Tag::TRUSTED_CONFIRMATION_REQUIRED:
1044 case Tag::UNLOCKED_DEVICE_REQUIRED:
1045 case Tag::APPLICATION_ID:
1046 case Tag::APPLICATION_DATA:
1047 case Tag::CREATION_DATETIME:
1048 case Tag::ORIGIN:
1049 case Tag::ROOT_OF_TRUST:
1050 case Tag::OS_VERSION:
1051 case Tag::OS_PATCHLEVEL:
1052 case Tag::UNIQUE_ID:
1053 case Tag::ATTESTATION_CHALLENGE:
1054 case Tag::ATTESTATION_APPLICATION_ID:
1055 case Tag::VENDOR_PATCHLEVEL:
1056 case Tag::BOOT_PATCHLEVEL:
1057 case Tag::ASSOCIATED_DATA:
1058 case Tag::NONCE:
1059 case Tag::MAC_LENGTH:
1060 case Tag::RESET_SINCE_ID_ROTATION:
1061 case Tag::CONFIRMATION_TOKEN:
1062 return false;
1063 // no default, all values must be present in the switch, in this way the compiler ensures
1064 // that new values added in the Tag enum are also added here.
1065 }
1066 }
1067
1068 // These are attestation id tags that are not unique per device and don't require special permission
1069 // to be attested. Any addition to this list needs privacy review and approval (PWG).
isDevicePropertyAttestationTag(Tag tag)1070 bool isDevicePropertyAttestationTag(Tag tag) {
1071 switch (tag) {
1072 case Tag::ATTESTATION_ID_BRAND:
1073 case Tag::ATTESTATION_ID_DEVICE:
1074 case Tag::ATTESTATION_ID_MANUFACTURER:
1075 case Tag::ATTESTATION_ID_MODEL:
1076 case Tag::ATTESTATION_ID_PRODUCT:
1077 return true;
1078 default:
1079 return false;
1080 }
1081 }
1082
isDeviceIdAttestationRequested(const KeymasterArguments & params)1083 bool isDeviceIdAttestationRequested(const KeymasterArguments& params) {
1084 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
1085 for (size_t i = 0; i < paramsVec.size(); ++i) {
1086 if (isDeviceIdAttestationTag(paramsVec[i].tag)) {
1087 return true;
1088 }
1089 }
1090 return false;
1091 }
1092
1093 // Device properties can be attested safely without special permission
needsPermissionToAttestDeviceIds(const KeymasterArguments & params)1094 bool needsPermissionToAttestDeviceIds(const KeymasterArguments& params) {
1095 const hardware::hidl_vec<KeyParameter>& paramsVec = params.getParameters();
1096 for (size_t i = 0; i < paramsVec.size(); ++i) {
1097 if (isDeviceIdAttestationTag(paramsVec[i].tag) &&
1098 !isDevicePropertyAttestationTag(paramsVec[i].tag)) {
1099 return true;
1100 }
1101 }
1102 return false;
1103 }
1104
attestKey(const::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback> & cb,const String16 & name,const KeymasterArguments & params,int32_t * _aidl_return)1105 Status KeyStoreService::attestKey(
1106 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1107 const String16& name, const KeymasterArguments& params, int32_t* _aidl_return) {
1108 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1109 if (!checkAllowedOperationParams(params.getParameters())) {
1110 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
1111 }
1112
1113 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1114
1115 if (needsPermissionToAttestDeviceIds(params) && (get_app_id(callingUid) != AID_SYSTEM)) {
1116 return AIDL_RETURN(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1117 }
1118
1119 AuthorizationSet mutableParams = params.getParameters();
1120 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1121 if (!rc.isOk()) {
1122 return AIDL_RETURN(rc);
1123 }
1124
1125 String8 name8(name);
1126 Blob keyBlob;
1127 Blob charBlob;
1128 LockedKeyBlobEntry lockedEntry;
1129
1130 std::tie(rc, keyBlob, charBlob, lockedEntry) =
1131 mKeyStore->getKeyForName(name8, callingUid, TYPE_KEYMASTER_10);
1132
1133 if (!rc.isOk()) {
1134 return AIDL_RETURN(rc);
1135 }
1136
1137 auto dev = mKeyStore->getDevice(keyBlob);
1138 auto hidlKey = blob2hidlVec(keyBlob);
1139 dev->attestKey(
1140 std::move(hidlKey), mutableParams.hidl_data(),
1141 [dev, cb](Return<void> rc,
1142 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1143 auto& [ret, certChain] = hidlResult;
1144 if (!rc.isOk()) {
1145 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1146 } else if (ret != ErrorCode::OK) {
1147 dev->logIfKeymasterVendorError(ret);
1148 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1149 } else {
1150 cb->onFinished(KeyStoreServiceReturnCode(ret),
1151 KeymasterCertificateChain(std::move(certChain)));
1152 }
1153 });
1154
1155 return AIDL_RETURN(ResponseCode::NO_ERROR);
1156 }
1157
1158 // My IDE defines "CAPTURE_MOVE(x) x" because it does not understand generalized lambda captures.
1159 // It should never be redefined by a build system though.
1160 #ifndef CAPTURE_MOVE
1161 #define CAPTURE_MOVE(x) x = std::move(x)
1162 #endif
1163
attestDeviceIds(const::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback> & cb,const KeymasterArguments & params,int32_t * _aidl_return)1164 Status KeyStoreService::attestDeviceIds(
1165 const ::android::sp<::android::security::keystore::IKeystoreCertificateChainCallback>& cb,
1166 const KeymasterArguments& params, int32_t* _aidl_return) {
1167 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1168
1169 if (!checkAllowedOperationParams(params.getParameters())) {
1170 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
1171 }
1172
1173 if (!isDeviceIdAttestationRequested(params)) {
1174 // There is an attestKey() method for attesting keys without device ID attestation.
1175 return AIDL_RETURN(ErrorCode::INVALID_ARGUMENT);
1176 }
1177
1178 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1179
1180 // Request special permission only for unique ids
1181 if (needsPermissionToAttestDeviceIds(params)) {
1182 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1183 if (binder == nullptr) {
1184 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
1185 }
1186
1187 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1188 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1189 IPCThreadState::self()->getCallingPid(), callingUid)) {
1190 return AIDL_RETURN(ErrorCode::CANNOT_ATTEST_IDS);
1191 }
1192 }
1193
1194 AuthorizationSet mutableParams = params.getParameters();
1195 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1196 if (!rc.isOk()) {
1197 return AIDL_RETURN(rc);
1198 }
1199
1200 // Generate temporary key.
1201 auto dev = mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT);
1202
1203 if (!dev) {
1204 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
1205 }
1206
1207
1208 AuthorizationSet keyCharacteristics;
1209 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1210 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1211 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1212 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1213 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
1214
1215 std::promise<KeyStoreServiceReturnCode> resultPromise;
1216 auto resultFuture = resultPromise.get_future();
1217
1218 dev->generateKey(
1219 keyCharacteristics.hidl_data(),
1220 [cb, dev, CAPTURE_MOVE(mutableParams)](
1221 Return<void> rc,
1222 std::tuple<ErrorCode, ::std::vector<uint8_t>, KeyCharacteristics>&& hidlResult) {
1223 auto& [ret, hidlKeyBlob_, dummyCharacteristics] = hidlResult;
1224 auto hidlKeyBlob = std::move(hidlKeyBlob_);
1225 if (!rc.isOk()) {
1226 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1227 return;
1228 }
1229 if (ret != ErrorCode::OK) {
1230 dev->logIfKeymasterVendorError(ret);
1231 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1232 return;
1233 }
1234 dev->attestKey(
1235 hidlKeyBlob, mutableParams.hidl_data(),
1236 [cb, dev,
1237 hidlKeyBlob](Return<void> rc,
1238 std::tuple<ErrorCode, hidl_vec<hidl_vec<uint8_t>>>&& hidlResult) {
1239 auto& [ret, certChain] = hidlResult;
1240 // schedule temp key for deletion
1241 dev->deleteKey(std::move(hidlKeyBlob), [dev](Return<ErrorCode> rc) {
1242 // log error but don't return an error
1243 KS_HANDLE_HIDL_ERROR(dev, rc);
1244 });
1245 if (!rc.isOk()) {
1246 cb->onFinished(KeyStoreServiceReturnCode(ResponseCode::SYSTEM_ERROR), {});
1247 return;
1248 }
1249 if (ret == ErrorCode::OK) {
1250 cb->onFinished(
1251 KeyStoreServiceReturnCode(ret),
1252 ::android::security::keymaster::KeymasterCertificateChain(certChain));
1253 } else {
1254 dev->logIfKeymasterVendorError(ret);
1255 cb->onFinished(KeyStoreServiceReturnCode(ret), {});
1256 }
1257 });
1258 });
1259
1260 return AIDL_RETURN(ResponseCode::NO_ERROR);
1261 }
1262
onDeviceOffBody(int32_t * aidl_return)1263 Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
1264 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1265 mKeyStore->getAuthTokenTable().onDeviceOffBody();
1266 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1267 return Status::ok();
1268 }
1269
importWrappedKey(const::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback> & cb,const::android::String16 & wrappedKeyAlias,const::std::vector<uint8_t> & wrappedKey,const::android::String16 & wrappingKeyAlias,const::std::vector<uint8_t> & maskingKey,const KeymasterArguments & params,int64_t rootSid,int64_t fingerprintSid,int32_t * _aidl_return)1270 Status KeyStoreService::importWrappedKey(
1271 const ::android::sp<::android::security::keystore::IKeystoreKeyCharacteristicsCallback>& cb,
1272 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1273 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1274 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
1275 int32_t* _aidl_return) {
1276
1277 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1278
1279 if (!checkBinderPermission(P_INSERT, callingUid)) {
1280 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1281 }
1282
1283 String8 wrappingKeyName8(wrappingKeyAlias);
1284
1285 KeyStoreServiceReturnCode rc;
1286 Blob wrappingKeyBlob;
1287 Blob wrappingCharBlob;
1288 LockedKeyBlobEntry wrappingLockedEntry;
1289
1290 std::tie(rc, wrappingKeyBlob, wrappingCharBlob, wrappingLockedEntry) =
1291 mKeyStore->getKeyForName(wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
1292 if (!rc.isOk()) {
1293 return AIDL_RETURN(rc);
1294 }
1295
1296 String8 wrappedKeyName8(wrappedKeyAlias);
1297 auto wrappedLockedEntry =
1298 mKeyStore->getLockedBlobEntryIfNotExists(wrappedKeyName8.string(), callingUid);
1299 if (!wrappedLockedEntry) {
1300 return AIDL_RETURN(ResponseCode::KEY_ALREADY_EXISTS);
1301 }
1302
1303 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1304 auto dev = mKeyStore->getDevice(securityLevel);
1305 if (!dev) {
1306 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1307 }
1308
1309 dev->importWrappedKey(
1310 std::move(wrappingLockedEntry), std::move(wrappedLockedEntry), wrappedKey, maskingKey,
1311 params.getParameters(), std::move(wrappingKeyBlob), std::move(wrappingCharBlob), rootSid,
1312 fingerprintSid, [cb](KeyStoreServiceReturnCode rc, KeyCharacteristics keyCharacteristics) {
1313 cb->onFinished(rc,
1314 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics));
1315 });
1316
1317 return AIDL_RETURN(ResponseCode::NO_ERROR);
1318 }
1319
presentConfirmationPrompt(const sp<IBinder> & listener,const String16 & promptText,const::std::vector<uint8_t> & extraData,const String16 & locale,int32_t uiOptionsAsFlags,int32_t * aidl_return)1320 Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1321 const String16& promptText,
1322 const ::std::vector<uint8_t>& extraData,
1323 const String16& locale, int32_t uiOptionsAsFlags,
1324 int32_t* aidl_return) {
1325 return mKeyStore->getConfirmationManager().presentConfirmationPrompt(
1326 listener, promptText, extraData, locale, uiOptionsAsFlags, aidl_return);
1327 }
1328
cancelConfirmationPrompt(const sp<IBinder> & listener,int32_t * aidl_return)1329 Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1330 int32_t* aidl_return) {
1331 return mKeyStore->getConfirmationManager().cancelConfirmationPrompt(listener, aidl_return);
1332 }
1333
isConfirmationPromptSupported(bool * aidl_return)1334 Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
1335 return mKeyStore->getConfirmationManager().isConfirmationPromptSupported(aidl_return);
1336 }
1337
1338 /**
1339 * Get the effective target uid for a binder operation that takes an
1340 * optional uid as the target.
1341 */
getEffectiveUid(int32_t targetUid)1342 uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1343 if (targetUid == UID_SELF) {
1344 return IPCThreadState::self()->getCallingUid();
1345 }
1346 return static_cast<uid_t>(targetUid);
1347 }
1348
1349 /**
1350 * Check if the caller of the current binder method has the required
1351 * permission and if acting on other uids the grants to do so.
1352 */
checkBinderPermission(perm_t permission,int32_t targetUid)1353 bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1354 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1355 pid_t spid = IPCThreadState::self()->getCallingPid();
1356 const char* ssid = IPCThreadState::self()->getCallingSid();
1357 if (!has_permission(callingUid, permission, spid, ssid)) {
1358 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1359 return false;
1360 }
1361 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1362 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1363 return false;
1364 }
1365 return true;
1366 }
1367
1368 /**
1369 * Check if the caller of the current binder method has the required
1370 * permission and the target uid is the caller or the caller is system.
1371 */
checkBinderPermissionSelfOrSystem(perm_t permission,int32_t targetUid)1372 bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1373 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1374 pid_t spid = IPCThreadState::self()->getCallingPid();
1375 const char* ssid = IPCThreadState::self()->getCallingSid();
1376 if (!has_permission(callingUid, permission, spid, ssid)) {
1377 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1378 return false;
1379 }
1380 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1381 }
1382
1383 /**
1384 * Check if the caller of the current binder method has the required
1385 * permission or the target of the operation is the caller's uid. This is
1386 * for operation where the permission is only for cross-uid activity and all
1387 * uids are allowed to act on their own (ie: clearing all entries for a
1388 * given uid).
1389 */
checkBinderPermissionOrSelfTarget(perm_t permission,int32_t targetUid)1390 bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1391 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1392 if (getEffectiveUid(targetUid) == callingUid) {
1393 return true;
1394 } else {
1395 return checkBinderPermission(permission, targetUid);
1396 }
1397 }
1398
1399 /**
1400 * Helper method to check that the caller has the required permission as
1401 * well as the keystore is in the unlocked state if checkUnlocked is true.
1402 *
1403 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1404 * otherwise the state of keystore when not unlocked and checkUnlocked is
1405 * true.
1406 */
1407 KeyStoreServiceReturnCode
checkBinderPermissionAndKeystoreState(perm_t permission,int32_t targetUid,bool checkUnlocked)1408 KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1409 bool checkUnlocked) {
1410 if (!checkBinderPermission(permission, targetUid)) {
1411 return ResponseCode::PERMISSION_DENIED;
1412 }
1413 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1414 if (checkUnlocked && !isKeystoreUnlocked(state)) {
1415 // All State values coincide with ResponseCodes
1416 return static_cast<ResponseCode>(state);
1417 }
1418
1419 return ResponseCode::NO_ERROR;
1420 }
1421
isKeystoreUnlocked(State state)1422 bool KeyStoreService::isKeystoreUnlocked(State state) {
1423 switch (state) {
1424 case ::STATE_NO_ERROR:
1425 return true;
1426 case ::STATE_UNINITIALIZED:
1427 case ::STATE_LOCKED:
1428 return false;
1429 }
1430 return false;
1431 }
1432
1433 /**
1434 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1435 * adds itself should be disallowed here.
1436 */
checkAllowedOperationParams(const hidl_vec<KeyParameter> & params)1437 bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1438 for (size_t i = 0; i < params.size(); ++i) {
1439 switch (params[i].tag) {
1440 case Tag::ATTESTATION_APPLICATION_ID:
1441 case Tag::RESET_SINCE_ID_ROTATION:
1442 return false;
1443 default:
1444 break;
1445 }
1446 }
1447 return true;
1448 }
1449
onKeyguardVisibilityChanged(bool isShowing,int32_t userId,int32_t * _aidl_return)1450 Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
1451 int32_t* _aidl_return) {
1452 if (isShowing) {
1453 if (!checkBinderPermission(P_LOCK, UID_SELF)) {
1454 LOG(WARNING) << "onKeyguardVisibilityChanged called with isShowing == true but "
1455 "without LOCK permission";
1456 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1457 }
1458 } else {
1459 if (!checkBinderPermission(P_UNLOCK, UID_SELF)) {
1460 LOG(WARNING) << "onKeyguardVisibilityChanged called with isShowing == false but "
1461 "without UNLOCK permission";
1462 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1463 }
1464 }
1465 mKeyStore->getEnforcementPolicy().set_device_locked(isShowing, userId);
1466 return AIDL_RETURN(ResponseCode::NO_ERROR);
1467 }
1468
1469 } // namespace keystore
1470