key_store_service.cpp 53 KB

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