• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "include/keystore/KeystoreArg.h"
21 
22 #include <fcntl.h>
23 #include <sys/stat.h>
24 
25 #include <algorithm>
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 <log/log_event_list.h>
34 
35 #include <private/android_filesystem_config.h>
36 #include <private/android_logger.h>
37 
38 #include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
39 
40 #include "defaults.h"
41 #include "key_proto_handler.h"
42 #include "keystore_attestation_id.h"
43 #include "keystore_keymaster_enforcement.h"
44 #include "keystore_utils.h"
45 #include <keystore/keystore_hidl_support.h>
46 
47 #include <hardware/hw_auth_token.h>
48 
49 namespace keystore {
50 
51 using namespace android;
52 
53 namespace {
54 
55 using ::android::binder::Status;
56 using android::security::KeystoreArg;
57 using android::security::keymaster::ExportResult;
58 using android::security::keymaster::KeymasterArguments;
59 using android::security::keymaster::KeymasterBlob;
60 using android::security::keymaster::KeymasterCertificateChain;
61 using android::security::keymaster::OperationResult;
62 using ConfirmationResponseCode = android::hardware::confirmationui::V1_0::ResponseCode;
63 
64 constexpr size_t kMaxOperations = 15;
65 constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
66 const char* kTimestampFilePath = "timestamp";
67 const int ID_ATTESTATION_REQUEST_GENERIC_INFO = 1 << 0;
68 const int ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID = 1 << 1;
69 
70 struct BIGNUM_Delete {
operator ()keystore::__anon816f92b20111::BIGNUM_Delete71     void operator()(BIGNUM* p) const { BN_free(p); }
72 };
73 typedef std::unique_ptr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
74 
containsTag(const hidl_vec<KeyParameter> & params,Tag tag)75 bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
76     return params.end() != std::find_if(params.begin(), params.end(),
77                                         [&](auto& param) { return param.tag == tag; });
78 }
79 
isAuthenticationBound(const hidl_vec<KeyParameter> & params)80 bool isAuthenticationBound(const hidl_vec<KeyParameter>& params) {
81     return !containsTag(params, Tag::NO_AUTH_REQUIRED);
82 }
83 #define KEYSTORE_SERVICE_LOCK \
84 	std::lock_guard<decltype(keystoreServiceMutex_)> keystore_lock(keystoreServiceMutex_)
85 
hadFactoryResetSinceIdRotation()86 std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
87     struct stat sbuf;
88     if (stat(kTimestampFilePath, &sbuf) == 0) {
89         double diff_secs = difftime(time(NULL), sbuf.st_ctime);
90         return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
91     }
92 
93     if (errno != ENOENT) {
94         ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
95         return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
96     }
97 
98     int fd = creat(kTimestampFilePath, 0600);
99     if (fd < 0) {
100         ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
101         return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
102     }
103 
104     if (close(fd)) {
105         ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
106         return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
107     }
108 
109     return {ResponseCode::NO_ERROR, true};
110 }
111 
112 constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
113 
updateParamsForAttestation(uid_t callingUid,AuthorizationSet * params)114 KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
115     KeyStoreServiceReturnCode responseCode;
116     bool factoryResetSinceIdRotation;
117     std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
118 
119     if (!responseCode.isOk()) return responseCode;
120     if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
121 
122     auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
123     if (!asn1_attestation_id_result.isOk()) {
124         ALOGE("failed to gather attestation_id");
125         return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
126     }
127     std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
128 
129     /*
130      * The attestation application ID cannot be longer than
131      * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, so we truncate if too long.
132      */
133     if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
134         asn1_attestation_id.resize(KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE);
135     }
136 
137     params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
138 
139     return ResponseCode::NO_ERROR;
140 }
141 
142 }  // anonymous namespace
143 
binderDied(const wp<IBinder> & who)144 void KeyStoreService::binderDied(const wp<IBinder>& who) {
145     auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
146     for (const auto& token : operations) {
147         int32_t unused_result;
148         abort(token, &unused_result);
149     }
150     mConfirmationManager->binderDied(who);
151 }
152 
getState(int32_t userId,int32_t * aidl_return)153 Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
154     KEYSTORE_SERVICE_LOCK;
155     if (!checkBinderPermission(P_GET_STATE)) {
156         *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
157         return Status::ok();
158     }
159     *aidl_return = mKeyStore->getState(userId);
160     return Status::ok();
161 }
162 
get(const String16 & name,int32_t uid,::std::vector<uint8_t> * item)163 Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
164     KEYSTORE_SERVICE_LOCK;
165     uid_t targetUid = getEffectiveUid(uid);
166     if (!checkBinderPermission(P_GET, targetUid)) {
167         // see keystore/keystore.h
168         return Status::fromServiceSpecificError(
169             static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
170     }
171 
172     String8 name8(name);
173     Blob keyBlob;
174     KeyStoreServiceReturnCode rc =
175         mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
176     if (!rc.isOk()) {
177         *item = ::std::vector<uint8_t>();
178         // Return empty array if key is not found
179         // TODO: consider having returned value nullable or parse exception on the client.
180         return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
181     }
182     auto resultBlob = blob2hidlVec(keyBlob);
183     // The static_cast here is needed to prevent a move, forcing a deep copy.
184     if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
185     return Status::ok();
186 }
187 
insert(const String16 & name,const::std::vector<uint8_t> & item,int targetUid,int32_t flags,int32_t * aidl_return)188 Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
189                                int targetUid, int32_t flags, int32_t* aidl_return) {
190     KEYSTORE_SERVICE_LOCK;
191     targetUid = getEffectiveUid(targetUid);
192     KeyStoreServiceReturnCode result =
193         checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
194     if (!result.isOk()) {
195         *aidl_return = static_cast<int32_t>(result);
196         return Status::ok();
197     }
198 
199     String8 name8(name);
200     String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_GENERIC));
201 
202     Blob keyBlob(&item[0], item.size(), NULL, 0, ::TYPE_GENERIC);
203     keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
204 
205     *aidl_return =
206         static_cast<int32_t>(mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid)));
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     KEYSTORE_SERVICE_LOCK;
212     targetUid = getEffectiveUid(targetUid);
213     if (!checkBinderPermission(P_DELETE, targetUid)) {
214         *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
215         return Status::ok();
216     }
217     String8 name8(name);
218     ALOGI("del %s %d", name8.string(), targetUid);
219     auto filename = mKeyStore->getBlobFileNameIfExists(name8, targetUid, ::TYPE_ANY);
220     if (!filename.isOk()) {
221         *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
222         return Status::ok();
223     }
224 
225     ResponseCode result =
226         mKeyStore->del(filename.value().string(), ::TYPE_ANY, get_user_id(targetUid));
227     if (result != ResponseCode::NO_ERROR) {
228         *aidl_return = static_cast<int32_t>(result);
229         return Status::ok();
230     }
231 
232     filename = mKeyStore->getBlobFileNameIfExists(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS);
233     if (filename.isOk()) {
234         *aidl_return = static_cast<int32_t>(mKeyStore->del(
235             filename.value().string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid)));
236         return Status::ok();
237     }
238     *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
239     return Status::ok();
240 }
241 
exist(const String16 & name,int targetUid,int32_t * aidl_return)242 Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
243     KEYSTORE_SERVICE_LOCK;
244     targetUid = getEffectiveUid(targetUid);
245     if (!checkBinderPermission(P_EXIST, targetUid)) {
246         *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
247         return Status::ok();
248     }
249 
250     auto filename = mKeyStore->getBlobFileNameIfExists(String8(name), targetUid, ::TYPE_ANY);
251     *aidl_return = static_cast<int32_t>(filename.isOk() ? ResponseCode::NO_ERROR
252                                                         : ResponseCode::KEY_NOT_FOUND);
253     return Status::ok();
254 }
255 
list(const String16 & prefix,int targetUid,::std::vector<::android::String16> * matches)256 Status KeyStoreService::list(const String16& prefix, int targetUid,
257                              ::std::vector<::android::String16>* matches) {
258     KEYSTORE_SERVICE_LOCK;
259     targetUid = getEffectiveUid(targetUid);
260     if (!checkBinderPermission(P_LIST, targetUid)) {
261         return Status::fromServiceSpecificError(
262             static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
263     }
264     const String8 prefix8(prefix);
265     String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid, TYPE_ANY));
266     android::Vector<android::String16> matches_internal;
267     if (mKeyStore->list(filename, &matches_internal, get_user_id(targetUid)) !=
268         ResponseCode::NO_ERROR) {
269         return Status::fromServiceSpecificError(static_cast<int32_t>(ResponseCode::SYSTEM_ERROR));
270     }
271     matches->clear();
272     for (size_t i = 0; i < matches_internal.size(); ++i) {
273         matches->push_back(matches_internal[i]);
274     }
275     return Status::ok();
276 }
277 
reset(int32_t * aidl_return)278 Status KeyStoreService::reset(int32_t* aidl_return) {
279     KEYSTORE_SERVICE_LOCK;
280     if (!checkBinderPermission(P_RESET)) {
281         *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
282         return Status::ok();
283     }
284 
285     uid_t callingUid = IPCThreadState::self()->getCallingUid();
286     mKeyStore->resetUser(get_user_id(callingUid), false);
287     *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
288     return Status::ok();
289 }
290 
onUserPasswordChanged(int32_t userId,const String16 & password,int32_t * aidl_return)291 Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
292                                               int32_t* aidl_return) {
293     KEYSTORE_SERVICE_LOCK;
294     if (!checkBinderPermission(P_PASSWORD)) {
295         *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
296         return Status::ok();
297     }
298 
299     const String8 password8(password);
300     // Flush the auth token table to prevent stale tokens from sticking
301     // around.
302     mAuthTokenTable.Clear();
303 
304     if (password.size() == 0) {
305         ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
306         mKeyStore->resetUser(userId, true);
307         *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
308         return Status::ok();
309     } else {
310         switch (mKeyStore->getState(userId)) {
311         case ::STATE_UNINITIALIZED: {
312             // generate master key, encrypt with password, write to file,
313             // initialize mMasterKey*.
314             *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
315             return Status::ok();
316         }
317         case ::STATE_NO_ERROR: {
318             // rewrite master key with new password.
319             *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
320             return Status::ok();
321         }
322         case ::STATE_LOCKED: {
323             ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
324             mKeyStore->resetUser(userId, true);
325             *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
326             return Status::ok();
327         }
328         }
329         *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
330         return Status::ok();
331     }
332 }
333 
onUserAdded(int32_t userId,int32_t parentId,int32_t * aidl_return)334 Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
335     KEYSTORE_SERVICE_LOCK;
336     if (!checkBinderPermission(P_USER_CHANGED)) {
337         *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
338         return Status::ok();
339     }
340 
341     // Sanity check that the new user has an empty keystore.
342     if (!mKeyStore->isEmpty(userId)) {
343         ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
344     }
345     // Unconditionally clear the keystore, just to be safe.
346     mKeyStore->resetUser(userId, false);
347     if (parentId != -1) {
348         // This profile must share the same master key password as the parent profile. Because the
349         // password of the parent profile is not known here, the best we can do is copy the parent's
350         // master key and master key file. This makes this profile use the same master key as the
351         // parent profile, forever.
352         *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
353         return Status::ok();
354     } else {
355         *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
356         return Status::ok();
357     }
358 }
359 
onUserRemoved(int32_t userId,int32_t * aidl_return)360 Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
361     KEYSTORE_SERVICE_LOCK;
362     if (!checkBinderPermission(P_USER_CHANGED)) {
363         *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
364         return Status::ok();
365     }
366 
367     mKeyStore->resetUser(userId, false);
368     *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
369     return Status::ok();
370 }
371 
lock(int32_t userId,int32_t * aidl_return)372 Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
373     KEYSTORE_SERVICE_LOCK;
374     if (!checkBinderPermission(P_LOCK)) {
375         *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
376         return Status::ok();
377     }
378 
379     State state = mKeyStore->getState(userId);
380     if (state != ::STATE_NO_ERROR) {
381         ALOGD("calling lock in state: %d", state);
382         *aidl_return = static_cast<int32_t>(ResponseCode(state));
383         return Status::ok();
384     }
385 
386     enforcement_policy.set_device_locked(true, userId);
387     mKeyStore->lock(userId);
388     *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
389     return Status::ok();
390 }
391 
unlock(int32_t userId,const String16 & pw,int32_t * aidl_return)392 Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
393     KEYSTORE_SERVICE_LOCK;
394     if (!checkBinderPermission(P_UNLOCK)) {
395         *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
396         return Status::ok();
397     }
398 
399     State state = mKeyStore->getState(userId);
400     if (state != ::STATE_LOCKED) {
401         switch (state) {
402         case ::STATE_NO_ERROR:
403             ALOGI("calling unlock when already unlocked, ignoring.");
404             break;
405         case ::STATE_UNINITIALIZED:
406             ALOGE("unlock called on uninitialized keystore.");
407             break;
408         default:
409             ALOGE("unlock called on keystore in unknown state: %d", state);
410             break;
411         }
412         *aidl_return = static_cast<int32_t>(ResponseCode(state));
413         return Status::ok();
414     }
415 
416     enforcement_policy.set_device_locked(false, userId);
417     const String8 password8(pw);
418     // read master key, decrypt with password, initialize mMasterKey*.
419     *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
420     return Status::ok();
421 }
422 
isEmpty(int32_t userId,int32_t * aidl_return)423 Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
424     KEYSTORE_SERVICE_LOCK;
425     if (!checkBinderPermission(P_IS_EMPTY)) {
426         *aidl_return = static_cast<int32_t>(false);
427         return Status::ok();
428     }
429 
430     *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
431     return Status::ok();
432 }
433 
generate(const String16 & name,int32_t targetUid,int32_t keyType,int32_t keySize,int32_t flags,const::android::security::KeystoreArguments & keystoreArgs,int32_t * aidl_return)434 Status KeyStoreService::generate(const String16& name, int32_t targetUid, int32_t keyType,
435                                  int32_t keySize, int32_t flags,
436                                  const ::android::security::KeystoreArguments& keystoreArgs,
437                                  int32_t* aidl_return) {
438     KEYSTORE_SERVICE_LOCK;
439     const Vector<sp<KeystoreArg>>* args = &(keystoreArgs.getArguments());
440     targetUid = getEffectiveUid(targetUid);
441     KeyStoreServiceReturnCode result =
442         checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
443     if (!result.isOk()) {
444         *aidl_return = static_cast<int32_t>(result);
445         return Status::ok();
446     }
447 
448     keystore::AuthorizationSet params;
449     add_legacy_key_authorizations(keyType, &params);
450 
451     switch (keyType) {
452     case EVP_PKEY_EC: {
453         params.push_back(TAG_ALGORITHM, Algorithm::EC);
454         if (keySize == -1) {
455             keySize = EC_DEFAULT_KEY_SIZE;
456         } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
457             ALOGI("invalid key size %d", keySize);
458             *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
459             return Status::ok();
460         }
461         params.push_back(TAG_KEY_SIZE, keySize);
462         break;
463     }
464     case EVP_PKEY_RSA: {
465         params.push_back(TAG_ALGORITHM, Algorithm::RSA);
466         if (keySize == -1) {
467             keySize = RSA_DEFAULT_KEY_SIZE;
468         } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
469             ALOGI("invalid key size %d", keySize);
470             *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
471             return Status::ok();
472         }
473         params.push_back(TAG_KEY_SIZE, keySize);
474         unsigned long exponent = RSA_DEFAULT_EXPONENT;
475         if (args->size() > 1) {
476             ALOGI("invalid number of arguments: %zu", args->size());
477             *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
478             return Status::ok();
479         } else if (args->size() == 1) {
480             const sp<KeystoreArg>& expArg = args->itemAt(0);
481             if (expArg != NULL) {
482                 Unique_BIGNUM pubExpBn(BN_bin2bn(
483                     reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
484                 if (pubExpBn.get() == NULL) {
485                     ALOGI("Could not convert public exponent to BN");
486                     *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
487                     return Status::ok();
488                 }
489                 exponent = BN_get_word(pubExpBn.get());
490                 if (exponent == 0xFFFFFFFFL) {
491                     ALOGW("cannot represent public exponent as a long value");
492                     *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
493                     return Status::ok();
494                 }
495             } else {
496                 ALOGW("public exponent not read");
497                 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
498                 return Status::ok();
499             }
500         }
501         params.push_back(TAG_RSA_PUBLIC_EXPONENT, exponent);
502         break;
503     }
504     default: {
505         ALOGW("Unsupported key type %d", keyType);
506         *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
507         return Status::ok();
508     }
509     }
510 
511     int32_t aidl_result;
512     android::security::keymaster::KeyCharacteristics unused_characteristics;
513     auto rc = generateKey(name, KeymasterArguments(params.hidl_data()), ::std::vector<uint8_t>(),
514                           targetUid, flags, &unused_characteristics, &aidl_result);
515     if (!KeyStoreServiceReturnCode(aidl_result).isOk()) {
516         ALOGW("generate failed: %d", int32_t(aidl_result));
517     }
518     *aidl_return = aidl_result;
519     return Status::ok();
520 }
521 
import_key(const String16 & name,const::std::vector<uint8_t> & data,int targetUid,int32_t flags,int32_t * aidl_return)522 Status KeyStoreService::import_key(const String16& name, const ::std::vector<uint8_t>& data,
523                                    int targetUid, int32_t flags, int32_t* aidl_return) {
524 
525     KEYSTORE_SERVICE_LOCK;
526     const uint8_t* ptr = &data[0];
527 
528     Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, data.size()));
529     if (!pkcs8.get()) {
530         *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
531         return Status::ok();
532     }
533     Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
534     if (!pkey.get()) {
535         *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
536         return Status::ok();
537     }
538     int type = EVP_PKEY_type(pkey->type);
539     AuthorizationSet params;
540     add_legacy_key_authorizations(type, &params);
541     switch (type) {
542     case EVP_PKEY_RSA:
543         params.push_back(TAG_ALGORITHM, Algorithm::RSA);
544         break;
545     case EVP_PKEY_EC:
546         params.push_back(TAG_ALGORITHM, Algorithm::EC);
547         break;
548     default:
549         ALOGW("Unsupported key type %d", type);
550         *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
551         return Status::ok();
552     }
553 
554     int import_result;
555     auto rc = importKey(name, KeymasterArguments(params.hidl_data()),
556                         static_cast<int32_t>(KeyFormat::PKCS8), data, targetUid, flags,
557                         /*outCharacteristics*/ NULL, &import_result);
558 
559     if (!KeyStoreServiceReturnCode(import_result).isOk()) {
560         ALOGW("importKey failed: %d", int32_t(import_result));
561     }
562     *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
563     return Status::ok();
564 }
565 
sign(const String16 & name,const::std::vector<uint8_t> & data,::std::vector<uint8_t> * out)566 Status KeyStoreService::sign(const String16& name, const ::std::vector<uint8_t>& data,
567                              ::std::vector<uint8_t>* out) {
568     KEYSTORE_SERVICE_LOCK;
569     if (!checkBinderPermission(P_SIGN)) {
570         return Status::fromServiceSpecificError(
571             static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
572     }
573     hidl_vec<uint8_t> legacy_out;
574     KeyStoreServiceReturnCode res =
575         doLegacySignVerify(name, data, &legacy_out, hidl_vec<uint8_t>(), KeyPurpose::SIGN);
576     if (!res.isOk()) {
577         return Status::fromServiceSpecificError((res));
578     }
579     *out = legacy_out;
580     return Status::ok();
581 }
582 
verify(const String16 & name,const::std::vector<uint8_t> & data,const::std::vector<uint8_t> & signature,int32_t * aidl_return)583 Status KeyStoreService::verify(const String16& name, const ::std::vector<uint8_t>& data,
584                                const ::std::vector<uint8_t>& signature, int32_t* aidl_return) {
585     KEYSTORE_SERVICE_LOCK;
586     if (!checkBinderPermission(P_VERIFY)) {
587         return Status::fromServiceSpecificError(
588             static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
589     }
590     *aidl_return = static_cast<int32_t>(
591         doLegacySignVerify(name, data, nullptr, signature, KeyPurpose::VERIFY));
592     return Status::ok();
593 }
594 
595 /*
596  * TODO: The abstraction between things stored in hardware and regular blobs
597  * of data stored on the filesystem should be moved down to keystore itself.
598  * Unfortunately the Java code that calls this has naming conventions that it
599  * knows about. Ideally keystore shouldn't be used to store random blobs of
600  * data.
601  *
602  * Until that happens, it's necessary to have a separate "get_pubkey" and
603  * "del_key" since the Java code doesn't really communicate what it's
604  * intentions are.
605  */
get_pubkey(const String16 & name,::std::vector<uint8_t> * pubKey)606 Status KeyStoreService::get_pubkey(const String16& name, ::std::vector<uint8_t>* pubKey) {
607     KEYSTORE_SERVICE_LOCK;
608     android::security::keymaster::ExportResult result;
609     KeymasterBlob clientId;
610     KeymasterBlob appData;
611     exportKey(name, static_cast<int32_t>(KeyFormat::X509), clientId, appData, UID_SELF, &result);
612     if (!result.resultCode.isOk()) {
613         ALOGW("export failed: %d", int32_t(result.resultCode));
614         return Status::fromServiceSpecificError(static_cast<int32_t>(result.resultCode));
615     }
616 
617     if (pubKey) *pubKey = std::move(result.exportData);
618     return Status::ok();
619 }
620 
grant(const String16 & name,int32_t granteeUid,::android::String16 * aidl_return)621 Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
622                               ::android::String16* aidl_return) {
623     KEYSTORE_SERVICE_LOCK;
624     uid_t callingUid = IPCThreadState::self()->getCallingUid();
625     auto result =
626         checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
627     if (!result.isOk()) {
628         *aidl_return = String16();
629         return Status::ok();
630     }
631 
632     String8 name8(name);
633     String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
634 
635     if (access(filename.string(), R_OK) == -1) {
636         *aidl_return = String16();
637         return Status::ok();
638     }
639 
640     *aidl_return =
641         String16(mKeyStore->addGrant(String8(name).string(), callingUid, granteeUid).c_str());
642     return Status::ok();
643 }
644 
ungrant(const String16 & name,int32_t granteeUid,int32_t * aidl_return)645 Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
646     KEYSTORE_SERVICE_LOCK;
647     uid_t callingUid = IPCThreadState::self()->getCallingUid();
648     KeyStoreServiceReturnCode result =
649         checkBinderPermissionAndKeystoreState(P_GRANT, /*targetUid=*/-1, /*checkUnlocked=*/false);
650     if (!result.isOk()) {
651         *aidl_return = static_cast<int32_t>(result);
652         return Status::ok();
653     }
654 
655     String8 name8(name);
656     String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
657 
658     if (access(filename.string(), R_OK) == -1) {
659         *aidl_return = static_cast<int32_t>((errno != ENOENT) ? ResponseCode::SYSTEM_ERROR
660                                                               : ResponseCode::KEY_NOT_FOUND);
661         return Status::ok();
662     }
663 
664     *aidl_return = static_cast<int32_t>(mKeyStore->removeGrant(name8, callingUid, granteeUid)
665                                             ? ResponseCode::NO_ERROR
666                                             : ResponseCode::KEY_NOT_FOUND);
667     return Status::ok();
668 }
669 
getmtime(const String16 & name,int32_t uid,int64_t * time)670 Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
671     KEYSTORE_SERVICE_LOCK;
672     uid_t targetUid = getEffectiveUid(uid);
673     if (!checkBinderPermission(P_GET, targetUid)) {
674         ALOGW("permission denied for %d: getmtime", targetUid);
675         *time = -1L;
676         return Status::ok();
677     }
678 
679     auto filename = mKeyStore->getBlobFileNameIfExists(String8(name), targetUid, ::TYPE_ANY);
680 
681     if (!filename.isOk()) {
682         ALOGW("could not access %s for getmtime", filename.value().string());
683         *time = -1L;
684         return Status::ok();
685     }
686 
687     int fd = TEMP_FAILURE_RETRY(open(filename.value().string(), O_NOFOLLOW, O_RDONLY));
688     if (fd < 0) {
689         ALOGW("could not open %s for getmtime", filename.value().string());
690         *time = -1L;
691         return Status::ok();
692     }
693 
694     struct stat s;
695     int ret = fstat(fd, &s);
696     close(fd);
697     if (ret == -1) {
698         ALOGW("could not stat %s for getmtime", filename.value().string());
699         *time = -1L;
700         return Status::ok();
701     }
702 
703     *time = static_cast<int64_t>(s.st_mtime);
704     return Status::ok();
705 }
706 
is_hardware_backed(const String16 & keyType,int32_t * aidl_return)707 Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
708     KEYSTORE_SERVICE_LOCK;
709     *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
710     return Status::ok();
711 }
712 
clear_uid(int64_t targetUid64,int32_t * aidl_return)713 Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* aidl_return) {
714     KEYSTORE_SERVICE_LOCK;
715     uid_t targetUid = getEffectiveUid(targetUid64);
716     if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
717         *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
718         return Status::ok();
719     }
720     ALOGI("clear_uid %" PRId64, targetUid64);
721 
722     mKeyStore->removeAllGrantsToUid(targetUid);
723 
724     String8 prefix = String8::format("%u_", targetUid);
725     Vector<String16> aliases;
726     if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
727         *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
728         return Status::ok();
729     }
730 
731     for (uint32_t i = 0; i < aliases.size(); i++) {
732         String8 name8(aliases[i]);
733         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
734 
735         if (get_app_id(targetUid) == AID_SYSTEM) {
736             Blob keyBlob;
737             ResponseCode responseCode =
738                 mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, get_user_id(targetUid));
739             if (responseCode == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
740                 // Do not clear keys critical to device encryption under system uid.
741                 continue;
742             }
743         }
744 
745         mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
746 
747         // del() will fail silently if no cached characteristics are present for this alias.
748         String8 chr_filename(
749             mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
750         mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
751     }
752     *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
753     return Status::ok();
754 }
755 
addRngEntropy(const::std::vector<uint8_t> & entropy,int32_t flags,int32_t * aidl_return)756 Status KeyStoreService::addRngEntropy(const ::std::vector<uint8_t>& entropy, int32_t flags,
757                                       int32_t* aidl_return) {
758     KEYSTORE_SERVICE_LOCK;
759     auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
760     if (!device) {
761         *aidl_return = static_cast<int32_t>(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
762     } else {
763         *aidl_return = static_cast<int32_t>(
764             KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device->addRngEntropy(entropy))));
765     }
766     return Status::ok();
767 }
768 
769 Status
generateKey(const String16 & name,const KeymasterArguments & params,const::std::vector<uint8_t> & entropy,int uid,int flags,android::security::keymaster::KeyCharacteristics * outCharacteristics,int32_t * aidl_return)770 KeyStoreService::generateKey(const String16& name, const KeymasterArguments& params,
771                              const ::std::vector<uint8_t>& entropy, int uid, int flags,
772                              android::security::keymaster::KeyCharacteristics* outCharacteristics,
773                              int32_t* aidl_return) {
774     KEYSTORE_SERVICE_LOCK;
775     // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
776     uid_t originalUid = IPCThreadState::self()->getCallingUid();
777     uid = getEffectiveUid(uid);
778     auto logOnScopeExit = android::base::make_scope_guard([&] {
779         if (__android_log_security()) {
780             android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
781                 << int32_t(*aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
782                 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
783         }
784     });
785     KeyStoreServiceReturnCode rc =
786         checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
787     if (!rc.isOk()) {
788         *aidl_return = static_cast<int32_t>(rc);
789         return Status::ok();
790     }
791     if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
792         ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
793         *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
794         return Status::ok();
795     }
796 
797     if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
798         // TODO(jbires): remove uid checking upon implementation of b/25646100
799         if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
800             originalUid != IPCThreadState::self()->getCallingUid()) {
801             *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
802             return Status::ok();
803         }
804     }
805 
806     SecurityLevel securityLevel = flagsToSecurityLevel(flags);
807     auto dev = mKeyStore->getDevice(securityLevel);
808     if (!dev) {
809         *aidl_return = static_cast<int32_t>(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
810         return Status::ok();
811     }
812     AuthorizationSet keyCharacteristics = params.getParameters();
813 
814     // TODO: Seed from Linux RNG before this.
815     rc = KS_HANDLE_HIDL_ERROR(dev->addRngEntropy(entropy));
816     if (!rc.isOk()) {
817         *aidl_return = static_cast<int32_t>(rc);
818         return Status::ok();
819     }
820 
821     KeyStoreServiceReturnCode error;
822     auto hidl_cb = [&](ErrorCode ret, const ::std::vector<uint8_t>& hidlKeyBlob,
823                        const KeyCharacteristics& keyCharacteristics) {
824         error = ret;
825         if (!error.isOk()) {
826             return;
827         }
828         if (outCharacteristics)
829             *outCharacteristics =
830                 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
831 
832         // Write the key
833         String8 name8(name);
834         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
835 
836         Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
837         keyBlob.setSecurityLevel(securityLevel);
838         keyBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
839         if (isAuthenticationBound(params.getParameters()) &&
840             !keyBlob.isCriticalToDeviceEncryption()) {
841             keyBlob.setSuperEncrypted(true);
842         }
843         keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
844 
845         error = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
846     };
847 
848     rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(params.getParameters(), hidl_cb));
849     if (!rc.isOk()) {
850         *aidl_return = static_cast<int32_t>(rc);
851         return Status::ok();
852     }
853     if (!error.isOk()) {
854         ALOGE("Failed to generate key -> falling back to software keymaster");
855         uploadKeyCharacteristicsAsProto(params.getParameters(), false /* wasCreationSuccessful */);
856         securityLevel = SecurityLevel::SOFTWARE;
857 
858         // No fall back for 3DES
859         for (auto& param : params.getParameters()) {
860             auto algorithm = authorizationValue(TAG_ALGORITHM, param);
861             if (algorithm.isOk() && algorithm.value() == Algorithm::TRIPLE_DES) {
862                 *aidl_return = static_cast<int32_t>(ErrorCode::UNSUPPORTED_ALGORITHM);
863                 return Status::ok();
864             }
865         }
866 
867         auto fallback = mKeyStore->getFallbackDevice();
868         if (!fallback) {
869             *aidl_return = static_cast<int32_t>(error);
870             return Status::ok();
871         }
872         rc = KS_HANDLE_HIDL_ERROR(fallback->generateKey(params.getParameters(), hidl_cb));
873         if (!rc.isOk()) {
874             *aidl_return = static_cast<int32_t>(rc);
875             return Status::ok();
876         }
877         if (!error.isOk()) {
878             *aidl_return = static_cast<int32_t>(error);
879             return Status::ok();
880         }
881     } else {
882         uploadKeyCharacteristicsAsProto(params.getParameters(), true /* wasCreationSuccessful */);
883     }
884 
885     if (!containsTag(params.getParameters(), Tag::USER_ID)) {
886         // Most Java processes don't have access to this tag
887         KeyParameter user_id;
888         user_id.tag = Tag::USER_ID;
889         user_id.f.integer = mActiveUserId;
890         keyCharacteristics.push_back(user_id);
891     }
892 
893     // Write the characteristics:
894     String8 name8(name);
895     String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
896 
897     std::stringstream kc_stream;
898     keyCharacteristics.Serialize(&kc_stream);
899     if (kc_stream.bad()) {
900         *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
901         return Status::ok();
902     }
903     auto kc_buf = kc_stream.str();
904     Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
905                   ::TYPE_KEY_CHARACTERISTICS);
906     charBlob.setSecurityLevel(securityLevel);
907     charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
908 
909     *aidl_return =
910         static_cast<int32_t>(mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid)));
911     return Status::ok();
912 }
913 
getKeyCharacteristics(const String16 & name,const::android::security::keymaster::KeymasterBlob & clientId,const::android::security::keymaster::KeymasterBlob & appData,int32_t uid,::android::security::keymaster::KeyCharacteristics * outCharacteristics,int32_t * aidl_return)914 Status KeyStoreService::getKeyCharacteristics(
915     const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
916     const ::android::security::keymaster::KeymasterBlob& appData, int32_t uid,
917     ::android::security::keymaster::KeyCharacteristics* outCharacteristics, int32_t* aidl_return) {
918     KEYSTORE_SERVICE_LOCK;
919     if (!outCharacteristics) {
920         *aidl_return =
921             static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::UNEXPECTED_NULL_POINTER));
922         return Status::ok();
923     }
924 
925     uid_t targetUid = getEffectiveUid(uid);
926     uid_t callingUid = IPCThreadState::self()->getCallingUid();
927     if (!is_granted_to(callingUid, targetUid)) {
928         ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
929               targetUid);
930         *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
931         return Status::ok();
932     }
933 
934     Blob keyBlob;
935     String8 name8(name);
936 
937     KeyStoreServiceReturnCode rc =
938         mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
939     if (rc == ResponseCode::UNINITIALIZED) {
940         /*
941          * If we fail reading the blob because the master key is missing we try to retrieve the
942          * key characteristics from the characteristics file. This happens when auth-bound
943          * keys are used after a screen lock has been removed by the user.
944          */
945         rc = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
946         if (!rc.isOk()) {
947             *aidl_return = static_cast<int32_t>(rc);
948             return Status::ok();
949         }
950         AuthorizationSet keyCharacteristics;
951         // TODO write one shot stream buffer to avoid copying (twice here)
952         std::string charBuffer(reinterpret_cast<const char*>(keyBlob.getValue()),
953                                keyBlob.getLength());
954         std::stringstream charStream(charBuffer);
955         keyCharacteristics.Deserialize(&charStream);
956 
957         outCharacteristics->softwareEnforced = KeymasterArguments(keyCharacteristics.hidl_data());
958         *aidl_return = static_cast<int32_t>(rc);
959         return Status::ok();
960     } else if (!rc.isOk()) {
961         *aidl_return = static_cast<int32_t>(rc);
962         return Status::ok();
963     }
964 
965     auto hidlKeyBlob = blob2hidlVec(keyBlob);
966     auto dev = mKeyStore->getDevice(keyBlob);
967 
968     KeyStoreServiceReturnCode error;
969 
970     auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
971         error = ret;
972         if (!error.isOk()) {
973             if (error == ErrorCode::INVALID_KEY_BLOB) {
974                 log_key_integrity_violation(name8, targetUid);
975             }
976             return;
977         }
978         *outCharacteristics =
979             ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
980     };
981 
982     rc = KS_HANDLE_HIDL_ERROR(
983         dev->getKeyCharacteristics(hidlKeyBlob, clientId.getData(), appData.getData(), hidlCb));
984     if (!rc.isOk()) {
985         *aidl_return = static_cast<int32_t>(rc);
986         return Status::ok();
987     }
988 
989     if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
990         AuthorizationSet upgradeParams;
991         if (clientId.getData().size()) {
992             upgradeParams.push_back(TAG_APPLICATION_ID, clientId.getData());
993         }
994         if (appData.getData().size()) {
995             upgradeParams.push_back(TAG_APPLICATION_DATA, appData.getData());
996         }
997         rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
998         if (!rc.isOk()) {
999             *aidl_return = static_cast<int32_t>(rc);
1000             return Status::ok();
1001         }
1002 
1003         auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
1004 
1005         rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(
1006             upgradedHidlKeyBlob, clientId.getData(), appData.getData(), hidlCb));
1007         if (!rc.isOk()) {
1008             *aidl_return = static_cast<int32_t>(rc);
1009             return Status::ok();
1010         }
1011         // Note that, on success, "error" will have been updated by the hidlCB callback.
1012         // So it is fine to return "error" below.
1013     }
1014     *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(error));
1015     return Status::ok();
1016 }
1017 
1018 Status
importKey(const String16 & name,const KeymasterArguments & params,int32_t format,const::std::vector<uint8_t> & keyData,int uid,int flags,::android::security::keymaster::KeyCharacteristics * outCharacteristics,int32_t * aidl_return)1019 KeyStoreService::importKey(const String16& name, const KeymasterArguments& params, int32_t format,
1020                            const ::std::vector<uint8_t>& keyData, int uid, int flags,
1021                            ::android::security::keymaster::KeyCharacteristics* outCharacteristics,
1022                            int32_t* aidl_return) {
1023     KEYSTORE_SERVICE_LOCK;
1024 
1025     uid = getEffectiveUid(uid);
1026     auto logOnScopeExit = android::base::make_scope_guard([&] {
1027         if (__android_log_security()) {
1028             android_log_event_list(SEC_TAG_KEY_IMPORTED)
1029                 << int32_t(*aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
1030                 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
1031         }
1032     });
1033     KeyStoreServiceReturnCode rc =
1034         checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
1035     if (!rc.isOk()) {
1036         *aidl_return = static_cast<int32_t>(rc);
1037         return Status::ok();
1038     }
1039     if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
1040         ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
1041         *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
1042         return Status::ok();
1043     }
1044 
1045     SecurityLevel securityLevel = flagsToSecurityLevel(flags);
1046     auto dev = mKeyStore->getDevice(securityLevel);
1047     if (!dev) {
1048         *aidl_return = static_cast<int32_t>(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1049         return Status::ok();
1050     }
1051 
1052     String8 name8(name);
1053 
1054     KeyStoreServiceReturnCode error;
1055 
1056     auto hidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& keyBlob,
1057                       const KeyCharacteristics& keyCharacteristics) {
1058         error = ret;
1059         if (!error.isOk()) {
1060             return;
1061         }
1062         if (outCharacteristics)
1063             *outCharacteristics =
1064                 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
1065 
1066         // Write the key:
1067         String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1068 
1069         Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
1070         ksBlob.setSecurityLevel(securityLevel);
1071         ksBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
1072         if (isAuthenticationBound(params.getParameters()) &&
1073             !ksBlob.isCriticalToDeviceEncryption()) {
1074             ksBlob.setSuperEncrypted(true);
1075         }
1076         ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1077 
1078         error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
1079     };
1080 
1081     rc = KS_HANDLE_HIDL_ERROR(
1082         dev->importKey(params.getParameters(), KeyFormat(format), keyData, hidlCb));
1083     // possible hidl error
1084     if (!rc.isOk()) {
1085         *aidl_return = static_cast<int32_t>(rc);
1086         return Status::ok();
1087     }
1088     // now check error from callback
1089     if (!error.isOk()) {
1090         ALOGE("Failed to import key -> falling back to software keymaster");
1091         uploadKeyCharacteristicsAsProto(params.getParameters(), false /* wasCreationSuccessful */);
1092         securityLevel = SecurityLevel::SOFTWARE;
1093 
1094         // No fall back for 3DES
1095         for (auto& param : params.getParameters()) {
1096             auto algorithm = authorizationValue(TAG_ALGORITHM, param);
1097             if (algorithm.isOk() && algorithm.value() == Algorithm::TRIPLE_DES) {
1098                 *aidl_return = static_cast<int32_t>(ErrorCode::UNSUPPORTED_ALGORITHM);
1099                 return Status::ok();
1100             }
1101         }
1102 
1103         auto fallback = mKeyStore->getFallbackDevice();
1104         if (!fallback) {
1105             *aidl_return = static_cast<int32_t>(error);
1106             return Status::ok();
1107         }
1108         rc = KS_HANDLE_HIDL_ERROR(
1109             fallback->importKey(params.getParameters(), KeyFormat(format), keyData, hidlCb));
1110         // possible hidl error
1111         if (!rc.isOk()) {
1112             *aidl_return = static_cast<int32_t>(rc);
1113             return Status::ok();
1114         }
1115         // now check error from callback
1116         if (!error.isOk()) {
1117             *aidl_return = static_cast<int32_t>(error);
1118             return Status::ok();
1119         }
1120     } else {
1121         uploadKeyCharacteristicsAsProto(params.getParameters(), true /* wasCreationSuccessful */);
1122     }
1123 
1124     // Write the characteristics:
1125     String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
1126 
1127     AuthorizationSet opParams = params.getParameters();
1128     if (!containsTag(params.getParameters(), Tag::USER_ID)) {
1129         // Most Java processes don't have access to this tag
1130         KeyParameter user_id;
1131         user_id.tag = Tag::USER_ID;
1132         user_id.f.integer = mActiveUserId;
1133         opParams.push_back(user_id);
1134     }
1135 
1136     std::stringstream kcStream;
1137     opParams.Serialize(&kcStream);
1138     if (kcStream.bad()) {
1139         *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
1140         return Status::ok();
1141     }
1142     auto kcBuf = kcStream.str();
1143 
1144     Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
1145                   ::TYPE_KEY_CHARACTERISTICS);
1146     charBlob.setSecurityLevel(securityLevel);
1147     charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1148 
1149     *aidl_return =
1150         static_cast<int32_t>(mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid)));
1151 
1152     return Status::ok();
1153 }
1154 
exportKey(const String16 & name,int32_t format,const::android::security::keymaster::KeymasterBlob & clientId,const::android::security::keymaster::KeymasterBlob & appData,int32_t uid,ExportResult * result)1155 Status KeyStoreService::exportKey(const String16& name, int32_t format,
1156                                   const ::android::security::keymaster::KeymasterBlob& clientId,
1157                                   const ::android::security::keymaster::KeymasterBlob& appData,
1158                                   int32_t uid, ExportResult* result) {
1159     KEYSTORE_SERVICE_LOCK;
1160 
1161     uid_t targetUid = getEffectiveUid(uid);
1162     uid_t callingUid = IPCThreadState::self()->getCallingUid();
1163     if (!is_granted_to(callingUid, targetUid)) {
1164         ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
1165         result->resultCode = ResponseCode::PERMISSION_DENIED;
1166         return Status::ok();
1167     }
1168 
1169     Blob keyBlob;
1170     String8 name8(name);
1171 
1172     result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
1173     if (!result->resultCode.isOk()) {
1174         return Status::ok();
1175     }
1176 
1177     auto key = blob2hidlVec(keyBlob);
1178     auto dev = mKeyStore->getDevice(keyBlob);
1179 
1180     auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
1181         result->resultCode = ret;
1182         if (!result->resultCode.isOk()) {
1183             if (result->resultCode == ErrorCode::INVALID_KEY_BLOB) {
1184                 log_key_integrity_violation(name8, targetUid);
1185             }
1186             return;
1187         }
1188         result->exportData = keyMaterial;
1189     };
1190     KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
1191         dev->exportKey(KeyFormat(format), key, clientId.getData(), appData.getData(), hidlCb));
1192     // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
1193     // callback hidlCb.
1194     if (!rc.isOk()) {
1195         result->resultCode = rc;
1196     }
1197 
1198     if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1199         AuthorizationSet upgradeParams;
1200         if (clientId.getData().size()) {
1201             upgradeParams.push_back(TAG_APPLICATION_ID, clientId.getData());
1202         }
1203         if (appData.getData().size()) {
1204             upgradeParams.push_back(TAG_APPLICATION_DATA, appData.getData());
1205         }
1206         result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
1207         if (!result->resultCode.isOk()) {
1208             return Status::ok();
1209         }
1210 
1211         auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
1212 
1213         result->resultCode = KS_HANDLE_HIDL_ERROR(dev->exportKey(
1214             KeyFormat(format), upgradedHidlKeyBlob, clientId.getData(), appData.getData(), hidlCb));
1215         if (!result->resultCode.isOk()) {
1216             return Status::ok();
1217         }
1218     }
1219     return Status::ok();
1220 }
1221 
begin(const sp<IBinder> & appToken,const String16 & name,int32_t purpose,bool pruneable,const KeymasterArguments & params,const::std::vector<uint8_t> & entropy,int32_t uid,OperationResult * result)1222 Status KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, int32_t purpose,
1223                               bool pruneable, const KeymasterArguments& params,
1224                               const ::std::vector<uint8_t>& entropy, int32_t uid,
1225                               OperationResult* result) {
1226     KEYSTORE_SERVICE_LOCK;
1227     auto keyPurpose = static_cast<KeyPurpose>(purpose);
1228 
1229     uid_t callingUid = IPCThreadState::self()->getCallingUid();
1230     uid_t targetUid = getEffectiveUid(uid);
1231     if (!is_granted_to(callingUid, targetUid)) {
1232         ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
1233         result->resultCode = ResponseCode::PERMISSION_DENIED;
1234         return Status::ok();
1235     }
1236     if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
1237         ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
1238         result->resultCode = ResponseCode::PERMISSION_DENIED;
1239         return Status::ok();
1240     }
1241     if (!checkAllowedOperationParams(params.getParameters())) {
1242         result->resultCode = ErrorCode::INVALID_ARGUMENT;
1243         return Status::ok();
1244     }
1245 
1246     Blob keyBlob;
1247     String8 name8(name);
1248     result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
1249     if (result->resultCode == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
1250         result->resultCode = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1251     }
1252     if (!result->resultCode.isOk()) return Status::ok();
1253 
1254     auto key = blob2hidlVec(keyBlob);
1255     auto dev = mKeyStore->getDevice(keyBlob);
1256     AuthorizationSet opParams = params.getParameters();
1257     KeyCharacteristics characteristics;
1258     result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
1259 
1260     if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1261         result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
1262         if (!result->resultCode.isOk()) {
1263             return Status::ok();
1264         }
1265         key = blob2hidlVec(keyBlob);
1266         result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
1267     }
1268     if (!result->resultCode.isOk()) {
1269         return Status::ok();
1270     }
1271 
1272     // Merge these characteristics with the ones cached when the key was generated or imported
1273     Blob charBlob;
1274     AuthorizationSet persistedCharacteristics;
1275     result->resultCode =
1276         mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
1277     if (result->resultCode.isOk()) {
1278         // TODO write one shot stream buffer to avoid copying (twice here)
1279         std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
1280                                charBlob.getLength());
1281         std::stringstream charStream(charBuffer);
1282         persistedCharacteristics.Deserialize(&charStream);
1283     } else {
1284         ALOGD("Unable to read cached characteristics for key");
1285     }
1286 
1287     // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
1288     AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
1289     AuthorizationSet hardwareEnforced = characteristics.hardwareEnforced;
1290     persistedCharacteristics.Union(softwareEnforced);
1291     persistedCharacteristics.Subtract(hardwareEnforced);
1292     characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
1293 
1294     KeyStoreServiceReturnCode authResult;
1295     HardwareAuthToken authToken;
1296     std::tie(authResult, authToken) =
1297         getAuthToken(characteristics, 0 /* no challenge */, keyPurpose,
1298                      /*failOnTokenMissing*/ false);
1299 
1300     // If per-operation auth is needed we need to begin the operation and
1301     // the client will need to authorize that operation before calling
1302     // update. Any other auth issues stop here.
1303     if (!authResult.isOk() && authResult != ResponseCode::OP_AUTH_NEEDED) {
1304         result->resultCode = authResult;
1305         return Status::ok();
1306     }
1307 
1308     // Add entropy to the device first.
1309     if (entropy.size()) {
1310         result->resultCode = KS_HANDLE_HIDL_ERROR(dev->addRngEntropy(entropy));
1311         if (!result->resultCode.isOk()) {
1312             return Status::ok();
1313         }
1314     }
1315 
1316     // Create a keyid for this key.
1317     km_id_t keyid;
1318     if (!enforcement_policy.CreateKeyId(key, &keyid)) {
1319         ALOGE("Failed to create a key ID for authorization checking.");
1320         result->resultCode = ErrorCode::UNKNOWN_ERROR;
1321         return Status::ok();
1322     }
1323 
1324     // Check that all key authorization policy requirements are met.
1325     AuthorizationSet key_auths = characteristics.hardwareEnforced;
1326     key_auths.append(characteristics.softwareEnforced.begin(),
1327                      characteristics.softwareEnforced.end());
1328 
1329     result->resultCode =
1330         enforcement_policy.AuthorizeOperation(keyPurpose, keyid, key_auths, opParams, authToken,
1331                                               0 /* op_handle */, true /* is_begin_operation */);
1332     if (!result->resultCode.isOk()) {
1333         return Status::ok();
1334     }
1335 
1336     // If there are more than kMaxOperations, abort the oldest operation that was started as
1337     // pruneable.
1338     while (mOperationMap.getOperationCount() >= kMaxOperations) {
1339         ALOGD("Reached or exceeded concurrent operations limit");
1340         if (!pruneOperation()) {
1341             break;
1342         }
1343     }
1344 
1345     auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1346                       uint64_t operationHandle) {
1347         result->resultCode = ret;
1348         if (!result->resultCode.isOk()) {
1349             if (result->resultCode == ErrorCode::INVALID_KEY_BLOB) {
1350                 log_key_integrity_violation(name8, targetUid);
1351             }
1352             return;
1353         }
1354         result->handle = operationHandle;
1355         result->outParams = outParams;
1356     };
1357 
1358     ErrorCode rc =
1359         KS_HANDLE_HIDL_ERROR(dev->begin(keyPurpose, key, opParams.hidl_data(), authToken, hidlCb));
1360     if (rc != ErrorCode::OK) {
1361         ALOGW("Got error %d from begin()", rc);
1362     }
1363 
1364     // If there are too many operations abort the oldest operation that was
1365     // started as pruneable and try again.
1366     while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1367         ALOGW("Ran out of operation handles");
1368         if (!pruneOperation()) {
1369             break;
1370         }
1371         rc = KS_HANDLE_HIDL_ERROR(
1372             dev->begin(keyPurpose, key, opParams.hidl_data(), authToken, hidlCb));
1373     }
1374     if (rc != ErrorCode::OK) {
1375         result->resultCode = rc;
1376         return Status::ok();
1377     }
1378 
1379     VerificationToken verificationToken;
1380     if (authResult.isOk() && authToken.mac.size() &&
1381         dev->halVersion().securityLevel == SecurityLevel::STRONGBOX) {
1382         // This operation needs an auth token, but the device is a STRONGBOX, so it can't check the
1383         // timestamp in the auth token.  Get a VerificationToken from the TEE, which will be passed
1384         // to update() and begin().
1385         rc = KS_HANDLE_HIDL_ERROR(mKeyStore->getDevice(SecurityLevel::TRUSTED_ENVIRONMENT)
1386                                       ->verifyAuthorization(result->handle,
1387                                                             {} /* parametersToVerify */, authToken,
1388                                                             [&](auto error, const auto& token) {
1389                                                                 result->resultCode = error;
1390                                                                 verificationToken = token;
1391                                                             }));
1392 
1393         if (rc != ErrorCode::OK) result->resultCode = rc;
1394         if (result->resultCode != ErrorCode::OK) {
1395             ALOGW("Failed to verify authorization %d from begin()", rc);
1396             rc = KS_HANDLE_HIDL_ERROR(dev->abort(result->handle));
1397             if (rc != ErrorCode::OK) {
1398                 ALOGW("Failed to abort operation %d from begin()", rc);
1399             }
1400             return Status::ok();
1401         }
1402     }
1403 
1404     // Note: The operation map takes possession of the contents of "characteristics".
1405     // It is safe to use characteristics after the following line but it will be empty.
1406     sp<IBinder> operationToken =
1407         mOperationMap.addOperation(result->handle, keyid, keyPurpose, dev, appToken,
1408                                    std::move(characteristics), params.getParameters(), pruneable);
1409     assert(characteristics.hardwareEnforced.size() == 0);
1410     assert(characteristics.softwareEnforced.size() == 0);
1411     result->token = operationToken;
1412 
1413     mOperationMap.setOperationAuthToken(operationToken, std::move(authToken));
1414     mOperationMap.setOperationVerificationToken(operationToken, std::move(verificationToken));
1415 
1416     // Return the authentication lookup result. If this is a per operation
1417     // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1418     // application should get an auth token using the handle before the
1419     // first call to update, which will fail if keystore hasn't received the
1420     // auth token.
1421     if (result->resultCode == ErrorCode::OK) {
1422         result->resultCode = authResult;
1423     }
1424 
1425     // Other result fields were set in the begin operation's callback.
1426     return Status::ok();
1427 }
1428 
appendConfirmationTokenIfNeeded(const KeyCharacteristics & keyCharacteristics,std::vector<KeyParameter> * params)1429 void KeyStoreService::appendConfirmationTokenIfNeeded(const KeyCharacteristics& keyCharacteristics,
1430                                                       std::vector<KeyParameter>* params) {
1431     if (!(containsTag(keyCharacteristics.softwareEnforced, Tag::TRUSTED_CONFIRMATION_REQUIRED) ||
1432           containsTag(keyCharacteristics.hardwareEnforced, Tag::TRUSTED_CONFIRMATION_REQUIRED))) {
1433         return;
1434     }
1435 
1436     hidl_vec<uint8_t> confirmationToken = mConfirmationManager->getLatestConfirmationToken();
1437     if (confirmationToken.size() == 0) {
1438         return;
1439     }
1440 
1441     params->push_back(
1442         Authorization(keymaster::TAG_CONFIRMATION_TOKEN, std::move(confirmationToken)));
1443     ALOGD("Appending confirmation token\n");
1444 }
1445 
update(const sp<IBinder> & token,const KeymasterArguments & params,const::std::vector<uint8_t> & data,OperationResult * result)1446 Status KeyStoreService::update(const sp<IBinder>& token, const KeymasterArguments& params,
1447                                const ::std::vector<uint8_t>& data, OperationResult* result) {
1448     KEYSTORE_SERVICE_LOCK;
1449     if (!checkAllowedOperationParams(params.getParameters())) {
1450         result->resultCode = ErrorCode::INVALID_ARGUMENT;
1451         return Status::ok();
1452     }
1453 
1454     auto getOpResult = mOperationMap.getOperation(token);
1455     if (!getOpResult.isOk()) {
1456         result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
1457         return Status::ok();
1458     }
1459     const auto& op = getOpResult.value();
1460 
1461     HardwareAuthToken authToken;
1462     std::tie(result->resultCode, authToken) = getOperationAuthTokenIfNeeded(token);
1463     if (!result->resultCode.isOk()) return Status::ok();
1464 
1465     // Check that all key authorization policy requirements are met.
1466     AuthorizationSet key_auths(op.characteristics.hardwareEnforced);
1467     key_auths.append(op.characteristics.softwareEnforced.begin(),
1468                      op.characteristics.softwareEnforced.end());
1469 
1470     result->resultCode = enforcement_policy.AuthorizeOperation(
1471         op.purpose, op.keyid, key_auths, params.getParameters(), authToken, op.handle,
1472         false /* is_begin_operation */);
1473     if (!result->resultCode.isOk()) return Status::ok();
1474 
1475     std::vector<KeyParameter> inParams = params.getParameters();
1476 
1477     auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
1478                       const hidl_vec<KeyParameter>& outParams,
1479                       const ::std::vector<uint8_t>& output) {
1480         result->resultCode = ret;
1481         if (result->resultCode.isOk()) {
1482             result->inputConsumed = inputConsumed;
1483             result->outParams = outParams;
1484             result->data = output;
1485         }
1486     };
1487 
1488     KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
1489         op.device->update(op.handle, inParams, data, authToken, op.verificationToken, hidlCb));
1490 
1491     // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1492     // it if there was a communication error indicated by the ErrorCode.
1493     if (!rc.isOk()) {
1494         result->resultCode = rc;
1495         // removeOperation() will free the memory 'op' used, so the order is important
1496         mAuthTokenTable.MarkCompleted(op.handle);
1497         mOperationMap.removeOperation(token, /* wasOpSuccessful */ false);
1498     }
1499 
1500     return Status::ok();
1501 }
1502 
finish(const sp<IBinder> & token,const KeymasterArguments & params,const::std::vector<uint8_t> & signature,const::std::vector<uint8_t> & entropy,OperationResult * result)1503 Status KeyStoreService::finish(const sp<IBinder>& token, const KeymasterArguments& params,
1504                                const ::std::vector<uint8_t>& signature,
1505                                const ::std::vector<uint8_t>& entropy, OperationResult* result) {
1506     KEYSTORE_SERVICE_LOCK;
1507     auto getOpResult = mOperationMap.getOperation(token);
1508     if (!getOpResult.isOk()) {
1509         result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
1510         return Status::ok();
1511     }
1512     const auto& op = std::move(getOpResult.value());
1513     if (!checkAllowedOperationParams(params.getParameters())) {
1514         result->resultCode = ErrorCode::INVALID_ARGUMENT;
1515         return Status::ok();
1516     }
1517 
1518     HardwareAuthToken authToken;
1519     std::tie(result->resultCode, authToken) = getOperationAuthTokenIfNeeded(token);
1520     if (!result->resultCode.isOk()) return Status::ok();
1521 
1522     if (entropy.size()) {
1523         result->resultCode = KS_HANDLE_HIDL_ERROR(op.device->addRngEntropy(entropy));
1524         if (!result->resultCode.isOk()) {
1525             return Status::ok();
1526         }
1527     }
1528 
1529     // Check that all key authorization policy requirements are met.
1530     AuthorizationSet key_auths(op.characteristics.hardwareEnforced);
1531     key_auths.append(op.characteristics.softwareEnforced.begin(),
1532                      op.characteristics.softwareEnforced.end());
1533 
1534     std::vector<KeyParameter> inParams = params.getParameters();
1535     appendConfirmationTokenIfNeeded(op.characteristics, &inParams);
1536 
1537     result->resultCode = enforcement_policy.AuthorizeOperation(
1538         op.purpose, op.keyid, key_auths, params.getParameters(), authToken, op.handle,
1539         false /* is_begin_operation */);
1540     if (!result->resultCode.isOk()) return Status::ok();
1541 
1542     auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1543                       const ::std::vector<uint8_t>& output) {
1544         result->resultCode = ret;
1545         if (result->resultCode.isOk()) {
1546             result->outParams = outParams;
1547             result->data = output;
1548         }
1549     };
1550 
1551     KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
1552         op.device->finish(op.handle, inParams,
1553                           ::std::vector<uint8_t>() /* TODO(swillden): wire up input to finish() */,
1554                           signature, authToken, op.verificationToken, hidlCb));
1555 
1556     bool wasOpSuccessful = true;
1557     // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1558     // it if there was a communication error indicated by the ErrorCode.
1559     if (!rc.isOk()) {
1560         result->resultCode = rc;
1561         wasOpSuccessful = false;
1562     }
1563 
1564     // removeOperation() will free the memory 'op' used, so the order is important
1565     mAuthTokenTable.MarkCompleted(op.handle);
1566     mOperationMap.removeOperation(token, wasOpSuccessful);
1567     return Status::ok();
1568 }
1569 
abort(const sp<IBinder> & token,int32_t * aidl_return)1570 Status KeyStoreService::abort(const sp<IBinder>& token, int32_t* aidl_return) {
1571     KEYSTORE_SERVICE_LOCK;
1572     auto getOpResult = mOperationMap.removeOperation(token, false /* wasOpSuccessful */);
1573     if (!getOpResult.isOk()) {
1574         *aidl_return = static_cast<int32_t>(ErrorCode::INVALID_OPERATION_HANDLE);
1575         return Status::ok();
1576     }
1577     auto op = std::move(getOpResult.value());
1578     mAuthTokenTable.MarkCompleted(op.handle);
1579 
1580     ErrorCode error_code = KS_HANDLE_HIDL_ERROR(op.device->abort(op.handle));
1581     *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(error_code));
1582     return Status::ok();
1583 }
1584 
isOperationAuthorized(const sp<IBinder> & token,bool * aidl_return)1585 Status KeyStoreService::isOperationAuthorized(const sp<IBinder>& token, bool* aidl_return) {
1586     KEYSTORE_SERVICE_LOCK;
1587     AuthorizationSet ignored;
1588     KeyStoreServiceReturnCode rc;
1589     std::tie(rc, std::ignore) = getOperationAuthTokenIfNeeded(token);
1590     *aidl_return = rc.isOk();
1591     return Status::ok();
1592 }
1593 
addAuthToken(const::std::vector<uint8_t> & authTokenAsVector,int32_t * aidl_return)1594 Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
1595                                      int32_t* aidl_return) {
1596     KEYSTORE_SERVICE_LOCK;
1597 
1598     // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1599     // receive a HardwareAuthToken, rather than an opaque byte array.
1600 
1601     if (!checkBinderPermission(P_ADD_AUTH)) {
1602         ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
1603         *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
1604         return Status::ok();
1605     }
1606     if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
1607         *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1608         return Status::ok();
1609     }
1610 
1611     hw_auth_token_t authToken;
1612     memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
1613     if (authToken.version != 0) {
1614         *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1615         return Status::ok();
1616     }
1617 
1618     mAuthTokenTable.AddAuthenticationToken(hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
1619     *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1620     return Status::ok();
1621 }
1622 
isDeviceIdAttestationRequested(const KeymasterArguments & params)1623 int isDeviceIdAttestationRequested(const KeymasterArguments& params) {
1624     const hardware::hidl_vec<KeyParameter> paramsVec = params.getParameters();
1625     int result = 0;
1626     for (size_t i = 0; i < paramsVec.size(); ++i) {
1627         switch (paramsVec[i].tag) {
1628         case Tag::ATTESTATION_ID_BRAND:
1629         case Tag::ATTESTATION_ID_DEVICE:
1630         case Tag::ATTESTATION_ID_MANUFACTURER:
1631         case Tag::ATTESTATION_ID_MODEL:
1632         case Tag::ATTESTATION_ID_PRODUCT:
1633             result |= ID_ATTESTATION_REQUEST_GENERIC_INFO;
1634             break;
1635         case Tag::ATTESTATION_ID_IMEI:
1636         case Tag::ATTESTATION_ID_MEID:
1637         case Tag::ATTESTATION_ID_SERIAL:
1638             result |= ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID;
1639             break;
1640         default:
1641             continue;
1642         }
1643     }
1644     return result;
1645 }
1646 
attestKey(const String16 & name,const KeymasterArguments & params,::android::security::keymaster::KeymasterCertificateChain * chain,int32_t * aidl_return)1647 Status KeyStoreService::attestKey(const String16& name, const KeymasterArguments& params,
1648                                   ::android::security::keymaster::KeymasterCertificateChain* chain,
1649                                   int32_t* aidl_return) {
1650     KEYSTORE_SERVICE_LOCK;
1651     // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1652     if (!checkAllowedOperationParams(params.getParameters())) {
1653         *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1654         return Status::ok();
1655     }
1656 
1657     uid_t callingUid = IPCThreadState::self()->getCallingUid();
1658 
1659     int needsIdAttestation = isDeviceIdAttestationRequested(params);
1660     bool needsUniqueIdAttestation = needsIdAttestation & ID_ATTESTATION_REQUEST_UNIQUE_DEVICE_ID;
1661     bool isPrimaryUserSystemUid = (callingUid == AID_SYSTEM);
1662     bool isSomeUserSystemUid = (get_app_id(callingUid) == AID_SYSTEM);
1663     // Allow system context from any user to request attestation with basic device information,
1664     // while only allow system context from user 0 (device owner) to request attestation with
1665     // unique device ID.
1666     if ((needsIdAttestation && !isSomeUserSystemUid) ||
1667         (needsUniqueIdAttestation && !isPrimaryUserSystemUid)) {
1668         *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1669         return Status::ok();
1670     }
1671 
1672     AuthorizationSet mutableParams = params.getParameters();
1673     KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1674     if (!rc.isOk()) {
1675         *aidl_return = static_cast<int32_t>(rc);
1676         return Status::ok();
1677     }
1678 
1679     Blob keyBlob;
1680     String8 name8(name);
1681     rc = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
1682     if (!rc.isOk()) {
1683         *aidl_return = static_cast<int32_t>(rc);
1684         return Status::ok();
1685     }
1686 
1687     KeyStoreServiceReturnCode error;
1688     auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1689         error = ret;
1690         if (!error.isOk()) {
1691             return;
1692         }
1693         if (chain) {
1694             *chain = KeymasterCertificateChain(certChain);
1695         }
1696     };
1697 
1698     auto hidlKey = blob2hidlVec(keyBlob);
1699     auto dev = mKeyStore->getDevice(keyBlob);
1700     rc = KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
1701     if (!rc.isOk()) {
1702         *aidl_return = static_cast<int32_t>(rc);
1703         return Status::ok();
1704     }
1705     *aidl_return = static_cast<int32_t>(error);
1706     return Status::ok();
1707 }
1708 
1709 Status
attestDeviceIds(const KeymasterArguments & params,::android::security::keymaster::KeymasterCertificateChain * chain,int32_t * aidl_return)1710 KeyStoreService::attestDeviceIds(const KeymasterArguments& params,
1711                                  ::android::security::keymaster::KeymasterCertificateChain* chain,
1712                                  int32_t* aidl_return) {
1713     KEYSTORE_SERVICE_LOCK;
1714     // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1715 
1716     if (!checkAllowedOperationParams(params.getParameters())) {
1717         *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1718         return Status::ok();
1719     }
1720 
1721     if (!isDeviceIdAttestationRequested(params)) {
1722         // There is an attestKey() method for attesting keys without device ID attestation.
1723         *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1724         return Status::ok();
1725     }
1726 
1727     uid_t callingUid = IPCThreadState::self()->getCallingUid();
1728     sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1729     if (binder == 0) {
1730         *aidl_return =
1731             static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::CANNOT_ATTEST_IDS));
1732         return Status::ok();
1733     }
1734     if (!interface_cast<IPermissionController>(binder)->checkPermission(
1735             String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1736             IPCThreadState::self()->getCallingPid(), callingUid)) {
1737         *aidl_return =
1738             static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::CANNOT_ATTEST_IDS));
1739         return Status::ok();
1740     }
1741 
1742     AuthorizationSet mutableParams = params.getParameters();
1743     KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1744     if (!rc.isOk()) {
1745         *aidl_return = static_cast<int32_t>(rc);
1746         return Status::ok();
1747     }
1748 
1749     // Generate temporary key.
1750     sp<Keymaster> dev;
1751     SecurityLevel securityLevel;
1752     std::tie(dev, securityLevel) = mKeyStore->getMostSecureDevice();
1753 
1754     if (securityLevel == SecurityLevel::SOFTWARE) {
1755         *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
1756         return Status::ok();
1757     }
1758 
1759     KeyStoreServiceReturnCode error;
1760     ::std::vector<uint8_t> hidlKey;
1761 
1762     AuthorizationSet keyCharacteristics;
1763     keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1764     keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1765     keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1766     keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1767     keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
1768     auto generateHidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& hidlKeyBlob,
1769                               const KeyCharacteristics&) {
1770         error = ret;
1771         if (!error.isOk()) {
1772             return;
1773         }
1774         hidlKey = hidlKeyBlob;
1775     };
1776 
1777     rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(keyCharacteristics.hidl_data(), generateHidlCb));
1778     if (!rc.isOk()) {
1779         *aidl_return = static_cast<int32_t>(rc);
1780         return Status::ok();
1781     }
1782     if (!error.isOk()) {
1783         *aidl_return = static_cast<int32_t>(error);
1784         return Status::ok();
1785     }
1786 
1787     // Attest key and device IDs.
1788     auto attestHidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1789         error = ret;
1790         if (!error.isOk()) {
1791             return;
1792         }
1793         *chain = ::android::security::keymaster::KeymasterCertificateChain(certChain);
1794     };
1795     KeyStoreServiceReturnCode attestationRc =
1796         KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), attestHidlCb));
1797 
1798     // Delete temporary key.
1799     KeyStoreServiceReturnCode deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
1800 
1801     if (!attestationRc.isOk()) {
1802         *aidl_return = static_cast<int32_t>(attestationRc);
1803         return Status::ok();
1804     }
1805     if (!error.isOk()) {
1806         *aidl_return = static_cast<int32_t>(error);
1807         return Status::ok();
1808     }
1809     *aidl_return = static_cast<int32_t>(deletionRc);
1810     return Status::ok();
1811 }
1812 
onDeviceOffBody(int32_t * aidl_return)1813 Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
1814     KEYSTORE_SERVICE_LOCK;
1815     // TODO(tuckeris): add permission check.  This should be callable from ClockworkHome only.
1816     mAuthTokenTable.onDeviceOffBody();
1817     *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1818     return Status::ok();
1819 }
1820 
1821 #define AIDL_RETURN(rc)                                                                            \
1822     (*_aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(rc)), Status::ok())
1823 
importWrappedKey(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,::android::security::keymaster::KeyCharacteristics * outCharacteristics,int32_t * _aidl_return)1824 Status KeyStoreService::importWrappedKey(
1825     const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1826     const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1827     const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
1828     ::android::security::keymaster::KeyCharacteristics* outCharacteristics, int32_t* _aidl_return) {
1829     KEYSTORE_SERVICE_LOCK;
1830 
1831     uid_t callingUid = IPCThreadState::self()->getCallingUid();
1832 
1833     if (!checkBinderPermission(P_INSERT, callingUid)) {
1834         return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1835     }
1836 
1837     Blob wrappingKeyBlob;
1838     String8 wrappingKeyName8(wrappingKeyAlias);
1839     KeyStoreServiceReturnCode rc =
1840         mKeyStore->getKeyForName(&wrappingKeyBlob, wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
1841     if (!rc.isOk()) {
1842         return AIDL_RETURN(rc);
1843     }
1844 
1845     SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1846     auto dev = mKeyStore->getDevice(securityLevel);
1847     if (!dev) {
1848         return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1849     }
1850 
1851     auto hidlWrappingKey = blob2hidlVec(wrappingKeyBlob);
1852     String8 wrappedKeyAlias8(wrappedKeyAlias);
1853 
1854     KeyStoreServiceReturnCode error;
1855 
1856     auto hidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& keyBlob,
1857                       const KeyCharacteristics& keyCharacteristics) {
1858         error = ret;
1859         if (!error.isOk()) {
1860             return;
1861         }
1862         if (outCharacteristics) {
1863             *outCharacteristics =
1864                 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
1865         }
1866 
1867         // Write the key:
1868         String8 filename(
1869             mKeyStore->getKeyNameForUidWithDir(wrappedKeyAlias8, callingUid, ::TYPE_KEYMASTER_10));
1870 
1871         Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
1872         ksBlob.setSecurityLevel(securityLevel);
1873 
1874         if (containsTag(keyCharacteristics.hardwareEnforced, Tag::USER_SECURE_ID)) {
1875             ksBlob.setSuperEncrypted(true);
1876         }
1877 
1878         error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(callingUid));
1879     };
1880 
1881     rc = KS_HANDLE_HIDL_ERROR(dev->importWrappedKey(wrappedKey, hidlWrappingKey, maskingKey,
1882                                                     params.getParameters(), rootSid, fingerprintSid,
1883                                                     hidlCb));
1884 
1885     // possible hidl error
1886     if (!rc.isOk()) {
1887         return AIDL_RETURN(rc);
1888     }
1889     // now check error from callback
1890     if (!error.isOk()) {
1891         return AIDL_RETURN(error);
1892     }
1893 
1894     // Write the characteristics:
1895     String8 cFilename(mKeyStore->getKeyNameForUidWithDir(wrappedKeyAlias8, callingUid,
1896                                                          ::TYPE_KEY_CHARACTERISTICS));
1897 
1898     AuthorizationSet opParams = params.getParameters();
1899     std::stringstream kcStream;
1900     opParams.Serialize(&kcStream);
1901     if (kcStream.bad()) {
1902         return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
1903     }
1904     auto kcBuf = kcStream.str();
1905 
1906     Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
1907                   ::TYPE_KEY_CHARACTERISTICS);
1908     charBlob.setSecurityLevel(securityLevel);
1909 
1910     return AIDL_RETURN(mKeyStore->put(cFilename.string(), &charBlob, get_user_id(callingUid)));
1911 }
1912 
presentConfirmationPrompt(const sp<IBinder> & listener,const String16 & promptText,const::std::vector<uint8_t> & extraData,const String16 & locale,int32_t uiOptionsAsFlags,int32_t * aidl_return)1913 Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1914                                                   const String16& promptText,
1915                                                   const ::std::vector<uint8_t>& extraData,
1916                                                   const String16& locale, int32_t uiOptionsAsFlags,
1917                                                   int32_t* aidl_return) {
1918     KEYSTORE_SERVICE_LOCK;
1919     return mConfirmationManager->presentConfirmationPrompt(listener, promptText, extraData, locale,
1920                                                            uiOptionsAsFlags, aidl_return);
1921 }
1922 
cancelConfirmationPrompt(const sp<IBinder> & listener,int32_t * aidl_return)1923 Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1924                                                  int32_t* aidl_return) {
1925     KEYSTORE_SERVICE_LOCK;
1926     return mConfirmationManager->cancelConfirmationPrompt(listener, aidl_return);
1927 }
1928 
isConfirmationPromptSupported(bool * aidl_return)1929 Status KeyStoreService::isConfirmationPromptSupported(bool* aidl_return) {
1930     KEYSTORE_SERVICE_LOCK;
1931     return mConfirmationManager->isConfirmationPromptSupported(aidl_return);
1932 }
1933 
1934 /**
1935  * Prune the oldest pruneable operation.
1936  */
pruneOperation()1937 bool KeyStoreService::pruneOperation() {
1938     sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1939     ALOGD("Trying to prune operation %p", oldest.get());
1940     size_t op_count_before_abort = mOperationMap.getOperationCount();
1941     // We mostly ignore errors from abort() because all we care about is whether at least
1942     // one operation has been removed.
1943     int32_t abort_error;
1944     abort(oldest, &abort_error);
1945     if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1946         ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1947         return false;
1948     }
1949     return true;
1950 }
1951 
1952 /**
1953  * Get the effective target uid for a binder operation that takes an
1954  * optional uid as the target.
1955  */
getEffectiveUid(int32_t targetUid)1956 uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1957     if (targetUid == UID_SELF) {
1958         return IPCThreadState::self()->getCallingUid();
1959     }
1960     return static_cast<uid_t>(targetUid);
1961 }
1962 
1963 /**
1964  * Check if the caller of the current binder method has the required
1965  * permission and if acting on other uids the grants to do so.
1966  */
checkBinderPermission(perm_t permission,int32_t targetUid)1967 bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1968     uid_t callingUid = IPCThreadState::self()->getCallingUid();
1969     pid_t spid = IPCThreadState::self()->getCallingPid();
1970     if (!has_permission(callingUid, permission, spid)) {
1971         ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1972         return false;
1973     }
1974     if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1975         ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1976         return false;
1977     }
1978     return true;
1979 }
1980 
1981 /**
1982  * Check if the caller of the current binder method has the required
1983  * permission and the target uid is the caller or the caller is system.
1984  */
checkBinderPermissionSelfOrSystem(perm_t permission,int32_t targetUid)1985 bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1986     uid_t callingUid = IPCThreadState::self()->getCallingUid();
1987     pid_t spid = IPCThreadState::self()->getCallingPid();
1988     if (!has_permission(callingUid, permission, spid)) {
1989         ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1990         return false;
1991     }
1992     return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1993 }
1994 
1995 /**
1996  * Check if the caller of the current binder method has the required
1997  * permission or the target of the operation is the caller's uid. This is
1998  * for operation where the permission is only for cross-uid activity and all
1999  * uids are allowed to act on their own (ie: clearing all entries for a
2000  * given uid).
2001  */
checkBinderPermissionOrSelfTarget(perm_t permission,int32_t targetUid)2002 bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2003     uid_t callingUid = IPCThreadState::self()->getCallingUid();
2004     if (getEffectiveUid(targetUid) == callingUid) {
2005         return true;
2006     } else {
2007         return checkBinderPermission(permission, targetUid);
2008     }
2009 }
2010 
2011 /**
2012  * Helper method to check that the caller has the required permission as
2013  * well as the keystore is in the unlocked state if checkUnlocked is true.
2014  *
2015  * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2016  * otherwise the state of keystore when not unlocked and checkUnlocked is
2017  * true.
2018  */
2019 KeyStoreServiceReturnCode
checkBinderPermissionAndKeystoreState(perm_t permission,int32_t targetUid,bool checkUnlocked)2020 KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
2021                                                        bool checkUnlocked) {
2022     if (!checkBinderPermission(permission, targetUid)) {
2023         return ResponseCode::PERMISSION_DENIED;
2024     }
2025     State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
2026     if (checkUnlocked && !isKeystoreUnlocked(state)) {
2027         // All State values coincide with ResponseCodes
2028         return static_cast<ResponseCode>(state);
2029     }
2030 
2031     return ResponseCode::NO_ERROR;
2032 }
2033 
isKeystoreUnlocked(State state)2034 bool KeyStoreService::isKeystoreUnlocked(State state) {
2035     switch (state) {
2036     case ::STATE_NO_ERROR:
2037         return true;
2038     case ::STATE_UNINITIALIZED:
2039     case ::STATE_LOCKED:
2040         return false;
2041     }
2042     return false;
2043 }
2044 
2045 /**
2046  * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
2047  * adds itself should be disallowed here.
2048  */
checkAllowedOperationParams(const hidl_vec<KeyParameter> & params)2049 bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
2050     for (size_t i = 0; i < params.size(); ++i) {
2051         switch (params[i].tag) {
2052         case Tag::ATTESTATION_APPLICATION_ID:
2053         case Tag::RESET_SINCE_ID_ROTATION:
2054             return false;
2055         default:
2056             break;
2057         }
2058     }
2059     return true;
2060 }
2061 
getOperationCharacteristics(const hidl_vec<uint8_t> & key,sp<Keymaster> * dev,const AuthorizationSet & params,KeyCharacteristics * out)2062 ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
2063                                                        sp<Keymaster>* dev,
2064                                                        const AuthorizationSet& params,
2065                                                        KeyCharacteristics* out) {
2066     ::std::vector<uint8_t> clientId;
2067     ::std::vector<uint8_t> appData;
2068     for (auto param : params) {
2069         if (param.tag == Tag::APPLICATION_ID) {
2070             clientId = authorizationValue(TAG_APPLICATION_ID, param).value();
2071         } else if (param.tag == Tag::APPLICATION_DATA) {
2072             appData = authorizationValue(TAG_APPLICATION_DATA, param).value();
2073         }
2074     }
2075     ErrorCode error = ErrorCode::OK;
2076 
2077     auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
2078         error = ret;
2079         if (error != ErrorCode::OK) {
2080             return;
2081         }
2082         if (out) *out = keyCharacteristics;
2083     };
2084 
2085     ErrorCode rc =
2086         KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, clientId, appData, hidlCb));
2087     if (rc != ErrorCode::OK) {
2088         return rc;
2089     }
2090     return error;
2091 }
2092 
2093 /**
2094  * Get the auth token for this operation from the auth token table.
2095  *
2096  * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
2097  *         ::OP_AUTH_NEEDED if it is a per op authorization, no
2098  *         authorization token exists for that operation and
2099  *         failOnTokenMissing is false.
2100  *         KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2101  *         token for the operation
2102  */
2103 std::pair<KeyStoreServiceReturnCode, HardwareAuthToken>
getAuthToken(const KeyCharacteristics & characteristics,uint64_t handle,KeyPurpose purpose,bool failOnTokenMissing)2104 KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics, uint64_t handle,
2105                               KeyPurpose purpose, bool failOnTokenMissing) {
2106 
2107     AuthorizationSet allCharacteristics(characteristics.softwareEnforced);
2108     allCharacteristics.append(characteristics.hardwareEnforced.begin(),
2109                               characteristics.hardwareEnforced.end());
2110 
2111     const HardwareAuthToken* authToken = nullptr;
2112     AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
2113         allCharacteristics, static_cast<KeyPurpose>(purpose), handle, &authToken);
2114 
2115     KeyStoreServiceReturnCode rc;
2116 
2117     switch (err) {
2118     case AuthTokenTable::OK:
2119     case AuthTokenTable::AUTH_NOT_REQUIRED:
2120         rc = ResponseCode::NO_ERROR;
2121         break;
2122 
2123     case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2124     case AuthTokenTable::AUTH_TOKEN_EXPIRED:
2125     case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2126         ALOGE("getAuthToken failed: %d", err);  // STOPSHIP: debug only, to be removed
2127         rc = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
2128         break;
2129 
2130     case AuthTokenTable::OP_HANDLE_REQUIRED:
2131         rc = failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
2132                                 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
2133         break;
2134 
2135     default:
2136         ALOGE("Unexpected FindAuthorization return value %d", err);
2137         rc = ErrorCode::INVALID_ARGUMENT;
2138     }
2139 
2140     return {rc, authToken ? std::move(*authToken) : HardwareAuthToken()};
2141 }
2142 
2143 /**
2144  * Add the auth token for the operation to the param list if the operation
2145  * requires authorization. Uses the cached result in the OperationMap if available
2146  * otherwise gets the token from the AuthTokenTable and caches the result.
2147  *
2148  * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
2149  *         KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2150  *         authenticated.
2151  *         KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2152  *         operation token.
2153  */
2154 std::pair<KeyStoreServiceReturnCode, const HardwareAuthToken&>
getOperationAuthTokenIfNeeded(const sp<IBinder> & token)2155 KeyStoreService::getOperationAuthTokenIfNeeded(const sp<IBinder>& token) {
2156     static HardwareAuthToken emptyToken = {};
2157 
2158     auto getOpResult = mOperationMap.getOperation(token);
2159     if (!getOpResult.isOk()) return {ErrorCode::INVALID_OPERATION_HANDLE, emptyToken};
2160     const auto& op = getOpResult.value();
2161 
2162     if (!op.hasAuthToken()) {
2163         KeyStoreServiceReturnCode rc;
2164         HardwareAuthToken found;
2165         std::tie(rc, found) = getAuthToken(op.characteristics, op.handle, op.purpose);
2166         if (!rc.isOk()) return {rc, emptyToken};
2167         mOperationMap.setOperationAuthToken(token, std::move(found));
2168     }
2169 
2170     return {ResponseCode::NO_ERROR, op.authToken};
2171 }
2172 
2173 /**
2174  * Translate a result value to a legacy return value. All keystore errors are
2175  * preserved and keymaster errors become SYSTEM_ERRORs
2176  */
translateResultToLegacyResult(int32_t result)2177 KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
2178     if (result > 0) return static_cast<ResponseCode>(result);
2179     return ResponseCode::SYSTEM_ERROR;
2180 }
2181 
getKeyAlgoritmFromKeyCharacteristics(const::android::security::keymaster::KeyCharacteristics & characteristics)2182 static NullOr<const Algorithm&> getKeyAlgoritmFromKeyCharacteristics(
2183     const ::android::security::keymaster::KeyCharacteristics& characteristics) {
2184     for (const auto& param : characteristics.hardwareEnforced.getParameters()) {
2185         auto algo = authorizationValue(TAG_ALGORITHM, param);
2186         if (algo.isOk()) return algo;
2187     }
2188     for (const auto& param : characteristics.softwareEnforced.getParameters()) {
2189         auto algo = authorizationValue(TAG_ALGORITHM, param);
2190         if (algo.isOk()) return algo;
2191     }
2192     return {};
2193 }
2194 
addLegacyBeginParams(const String16 & name,AuthorizationSet * params)2195 void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
2196     // All legacy keys are DIGEST_NONE/PAD_NONE.
2197     params->push_back(TAG_DIGEST, Digest::NONE);
2198     params->push_back(TAG_PADDING, PaddingMode::NONE);
2199 
2200     // Look up the algorithm of the key.
2201     ::android::security::keymaster::KeyCharacteristics characteristics;
2202     int32_t result;
2203     auto rc = getKeyCharacteristics(name, ::android::security::keymaster::KeymasterBlob(),
2204                                     ::android::security::keymaster::KeymasterBlob(), UID_SELF,
2205                                     &characteristics, &result);
2206     if (!rc.isOk()) {
2207         ALOGE("Failed to get key characteristics");
2208         return;
2209     }
2210     auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
2211     if (!algorithm.isOk()) {
2212         ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
2213         return;
2214     }
2215     params->push_back(TAG_ALGORITHM, algorithm.value());
2216 }
2217 
doLegacySignVerify(const String16 & name,const hidl_vec<uint8_t> & data,hidl_vec<uint8_t> * out,const hidl_vec<uint8_t> & signature,KeyPurpose purpose)2218 KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
2219                                                               const hidl_vec<uint8_t>& data,
2220                                                               hidl_vec<uint8_t>* out,
2221                                                               const hidl_vec<uint8_t>& signature,
2222                                                               KeyPurpose purpose) {
2223 
2224     std::basic_stringstream<uint8_t> outBuffer;
2225     OperationResult result;
2226     AuthorizationSet inArgs;
2227     addLegacyBeginParams(name, &inArgs);
2228     sp<IBinder> appToken(new BBinder);
2229     sp<IBinder> token;
2230 
2231     begin(appToken, name, static_cast<int32_t>(purpose), true,
2232           KeymasterArguments(inArgs.hidl_data()), ::std::vector<uint8_t>(), UID_SELF, &result);
2233     if (!result.resultCode.isOk()) {
2234         if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
2235             ALOGW("Key not found");
2236         } else {
2237             ALOGW("Error in begin: %d", int32_t(result.resultCode));
2238         }
2239         return translateResultToLegacyResult(result.resultCode);
2240     }
2241     inArgs.Clear();
2242     token = result.token;
2243     size_t consumed = 0;
2244     size_t lastConsumed = 0;
2245     hidl_vec<uint8_t> data_view;
2246     do {
2247         data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
2248         update(token, KeymasterArguments(inArgs.hidl_data()), data_view, &result);
2249         if (result.resultCode != ResponseCode::NO_ERROR) {
2250             ALOGW("Error in update: %d", int32_t(result.resultCode));
2251             return translateResultToLegacyResult(result.resultCode);
2252         }
2253         if (out) {
2254             outBuffer.write(&result.data[0], result.data.size());
2255         }
2256         lastConsumed = result.inputConsumed;
2257         consumed += lastConsumed;
2258     } while (consumed < data.size() && lastConsumed > 0);
2259 
2260     if (consumed != data.size()) {
2261         ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
2262         return ResponseCode::SYSTEM_ERROR;
2263     }
2264 
2265     finish(token, KeymasterArguments(inArgs.hidl_data()), signature, ::std::vector<uint8_t>(),
2266            &result);
2267     if (result.resultCode != ResponseCode::NO_ERROR) {
2268         ALOGW("Error in finish: %d", int32_t(result.resultCode));
2269         return translateResultToLegacyResult(result.resultCode);
2270     }
2271     if (out) {
2272         outBuffer.write(&result.data[0], result.data.size());
2273     }
2274 
2275     if (out) {
2276         auto buf = outBuffer.str();
2277         out->resize(buf.size());
2278         memcpy(&(*out)[0], buf.data(), out->size());
2279     }
2280 
2281     return ResponseCode::NO_ERROR;
2282 }
2283 
upgradeKeyBlob(const String16 & name,uid_t uid,const AuthorizationSet & params,Blob * blob)2284 KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
2285                                                           const AuthorizationSet& params,
2286                                                           Blob* blob) {
2287     // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
2288     String8 name8(name);
2289     KeyStoreServiceReturnCode responseCode =
2290         mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
2291     if (responseCode != ResponseCode::NO_ERROR) {
2292         return responseCode;
2293     }
2294     ALOGI("upgradeKeyBlob %s %d", name8.string(), uid);
2295 
2296     auto hidlKey = blob2hidlVec(*blob);
2297     auto dev = mKeyStore->getDevice(*blob);
2298 
2299     KeyStoreServiceReturnCode error;
2300     auto hidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& upgradedKeyBlob) {
2301         error = ret;
2302         if (!error.isOk()) {
2303             if (error == ErrorCode::INVALID_KEY_BLOB) {
2304                 log_key_integrity_violation(name8, uid);
2305             }
2306             return;
2307         }
2308 
2309         auto filename = mKeyStore->getBlobFileNameIfExists(name8, uid, ::TYPE_KEYMASTER_10);
2310         if (!filename.isOk()) {
2311             ALOGI("trying to upgrade a non existing blob");
2312             return;
2313         }
2314         error = mKeyStore->del(filename.value().string(), ::TYPE_ANY, get_user_id(uid));
2315         if (!error.isOk()) {
2316             ALOGI("upgradeKeyBlob keystore->del failed %d", (int)error);
2317             return;
2318         }
2319 
2320         Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
2321                      0 /* infoLength */, ::TYPE_KEYMASTER_10);
2322         newBlob.setSecurityLevel(blob->getSecurityLevel());
2323         newBlob.setEncrypted(blob->isEncrypted());
2324         newBlob.setSuperEncrypted(blob->isSuperEncrypted());
2325         newBlob.setCriticalToDeviceEncryption(blob->isCriticalToDeviceEncryption());
2326 
2327         error = mKeyStore->put(filename.value().string(), &newBlob, get_user_id(uid));
2328         if (!error.isOk()) {
2329             ALOGI("upgradeKeyBlob keystore->put failed %d", (int)error);
2330             return;
2331         }
2332 
2333         // Re-read blob for caller.  We can't use newBlob because writing it modified it.
2334         error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
2335     };
2336 
2337     KeyStoreServiceReturnCode rc =
2338         KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
2339     if (!rc.isOk()) {
2340         return rc;
2341     }
2342 
2343     return error;
2344 }
2345 
onKeyguardVisibilityChanged(bool isShowing,int32_t userId,int32_t * _aidl_return)2346 Status KeyStoreService::onKeyguardVisibilityChanged(bool isShowing, int32_t userId,
2347                                                     int32_t* _aidl_return) {
2348     KEYSTORE_SERVICE_LOCK;
2349     if (isShowing) {
2350         if (!checkBinderPermission(P_LOCK, UID_SELF)) {
2351             LOG(WARNING) << "onKeyguardVisibilityChanged called with isShowing == true but "
2352                             "without LOCK permission";
2353             return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
2354         }
2355     } else {
2356         if (!checkBinderPermission(P_UNLOCK, UID_SELF)) {
2357             LOG(WARNING) << "onKeyguardVisibilityChanged called with isShowing == false but "
2358                             "without UNLOCK permission";
2359             return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
2360         }
2361         mActiveUserId = userId;
2362     }
2363     enforcement_policy.set_device_locked(isShowing, userId);
2364     return AIDL_RETURN(ResponseCode::NO_ERROR);
2365 }
2366 
2367 }  // namespace keystore
2368