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