blob: 59485dcbc63a17233c63abfc8a18e4cedbdd2511 [file] [log] [blame]
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001/*
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
Janis Danisevskis011675d2016-09-01 11:41:29 +010017#define LOG_TAG "keystore"
18
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070019#include "key_store_service.h"
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070020#include "include/keystore/KeystoreArg.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070021
22#include <fcntl.h>
23#include <sys/stat.h>
24
Janis Danisevskis7612fd42016-09-01 11:50:02 +010025#include <algorithm>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070026#include <sstream>
27
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010028#include <binder/IInterface.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070029#include <binder/IPCThreadState.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010030#include <binder/IPermissionController.h>
31#include <binder/IServiceManager.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070032
33#include <private/android_filesystem_config.h>
34
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010035#include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070036
37#include "defaults.h"
Janis Danisevskis18f27ad2016-06-01 13:57:40 -070038#include "keystore_attestation_id.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010039#include "keystore_keymaster_enforcement.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070040#include "keystore_utils.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010041#include <keystore/keystore_hidl_support.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070042
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010043namespace keystore {
Shawn Willdend5a24e62017-02-28 13:53:24 -070044
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010045using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070046
Shawn Willdene2a7b522017-04-11 09:27:40 -060047namespace {
48
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070049using ::android::binder::Status;
50using ::android::hardware::keymaster::V3_0::KeyFormat;
51using android::security::KeystoreArg;
52using android::security::keymaster::ExportResult;
53using android::security::keymaster::KeymasterArguments;
54using android::security::keymaster::KeymasterBlob;
55using android::security::keymaster::KeymasterCertificateChain;
56using android::security::keymaster::OperationResult;
57
Shawn Willdene2a7b522017-04-11 09:27:40 -060058constexpr size_t kMaxOperations = 15;
59constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
60const char* kTimestampFilePath = "timestamp";
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070061
62struct BIGNUM_Delete {
63 void operator()(BIGNUM* p) const { BN_free(p); }
64};
Janis Danisevskisccfff102017-05-01 11:02:51 -070065typedef std::unique_ptr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070066
Shawn Willdene2a7b522017-04-11 09:27:40 -060067bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
68 return params.end() != std::find_if(params.begin(), params.end(),
69 [&](auto& param) { return param.tag == tag; });
70}
71
Shawn Willdend5a24e62017-02-28 13:53:24 -070072bool isAuthenticationBound(const hidl_vec<KeyParameter>& params) {
73 return !containsTag(params, Tag::NO_AUTH_REQUIRED);
74}
75
Shawn Willdene2a7b522017-04-11 09:27:40 -060076std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
77 struct stat sbuf;
78 if (stat(kTimestampFilePath, &sbuf) == 0) {
79 double diff_secs = difftime(time(NULL), sbuf.st_ctime);
80 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
81 }
82
83 if (errno != ENOENT) {
84 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
85 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
86 }
87
88 int fd = creat(kTimestampFilePath, 0600);
89 if (fd < 0) {
90 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
91 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
92 }
93
94 if (close(fd)) {
95 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
96 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
97 }
98
99 return {ResponseCode::NO_ERROR, true};
100}
101
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200102constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
103
104KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
105 KeyStoreServiceReturnCode responseCode;
106 bool factoryResetSinceIdRotation;
107 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
108
109 if (!responseCode.isOk()) return responseCode;
110 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
111
112 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
113 if (!asn1_attestation_id_result.isOk()) {
114 ALOGE("failed to gather attestation_id");
115 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
116 }
117 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
118
119 /*
120 * The attestation application ID cannot be longer than
121 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, so we truncate if too long.
122 */
123 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
124 asn1_attestation_id.resize(KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE);
125 }
126
127 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
128
129 return ResponseCode::NO_ERROR;
130}
131
Shawn Willdene2a7b522017-04-11 09:27:40 -0600132} // anonymous namespace
133
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700134void KeyStoreService::binderDied(const wp<IBinder>& who) {
135 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700136 for (const auto& token : operations) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700137 int32_t unused_result;
138 abort(token, &unused_result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700139 }
140}
141
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700142Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700143 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700144 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
145 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700146 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700147 *aidl_return = mKeyStore->getState(userId);
148 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700149}
150
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700151Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700152 uid_t targetUid = getEffectiveUid(uid);
153 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700154 // see keystore/keystore.h
155 return Status::fromServiceSpecificError(
156 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700157 }
158
159 String8 name8(name);
160 Blob keyBlob;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100161 KeyStoreServiceReturnCode rc =
162 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
163 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700164 *item = ::std::vector<uint8_t>();
165 // Return empty array if key is not found
166 // TODO: consider having returned value nullable or parse exception on the client.
167 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700168 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100169 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700170 // The static_cast here is needed to prevent a move, forcing a deep copy.
171 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
172 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700173}
174
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700175Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
176 int targetUid, int32_t flags, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700177 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700178 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700179 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100180 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700181 *aidl_return = static_cast<int32_t>(result);
182 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700183 }
184
185 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400186 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_GENERIC));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700187
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100188 Blob keyBlob(&item[0], item.size(), NULL, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700189 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
190
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700191 *aidl_return =
192 static_cast<int32_t>(mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid)));
193 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700194}
195
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700196Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700197 targetUid = getEffectiveUid(targetUid);
198 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700199 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
200 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700201 }
202 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000203 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700204 auto filename = mKeyStore->getBlobFileNameIfExists(name8, targetUid, ::TYPE_ANY);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700205 if (!filename.isOk()) {
206 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
207 return Status::ok();
208 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700209
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700210 ResponseCode result =
211 mKeyStore->del(filename.value().string(), ::TYPE_ANY, get_user_id(targetUid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100212 if (result != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700213 *aidl_return = static_cast<int32_t>(result);
214 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400215 }
216
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700217 filename = mKeyStore->getBlobFileNameIfExists(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS);
218 if (filename.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700219 *aidl_return = static_cast<int32_t>(mKeyStore->del(
220 filename.value().string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid)));
221 return Status::ok();
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700222 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700223 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
224 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700225}
226
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700227Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700228 targetUid = getEffectiveUid(targetUid);
229 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700230 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
231 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700232 }
233
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700234 auto filename = mKeyStore->getBlobFileNameIfExists(String8(name), targetUid, ::TYPE_ANY);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700235 *aidl_return = static_cast<int32_t>(filename.isOk() ? ResponseCode::NO_ERROR
236 : ResponseCode::KEY_NOT_FOUND);
237 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700238}
239
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700240Status KeyStoreService::list(const String16& prefix, int targetUid,
241 ::std::vector<::android::String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700242 targetUid = getEffectiveUid(targetUid);
243 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700244 return Status::fromServiceSpecificError(
245 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700246 }
247 const String8 prefix8(prefix);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400248 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid, TYPE_ANY));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700249 android::Vector<android::String16> matches_internal;
250 if (mKeyStore->list(filename, &matches_internal, get_user_id(targetUid)) !=
251 ResponseCode::NO_ERROR) {
252 return Status::fromServiceSpecificError(static_cast<int32_t>(ResponseCode::SYSTEM_ERROR));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700253 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700254 matches->clear();
255 for (size_t i = 0; i < matches_internal.size(); ++i) {
256 matches->push_back(matches_internal[i]);
257 }
258 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700259}
260
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700261Status KeyStoreService::reset(int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700262 if (!checkBinderPermission(P_RESET)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700263 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
264 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700265 }
266
267 uid_t callingUid = IPCThreadState::self()->getCallingUid();
268 mKeyStore->resetUser(get_user_id(callingUid), false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700269 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
270 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700271}
272
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700273Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
274 int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700275 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700276 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
277 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700278 }
279
280 const String8 password8(password);
281 // Flush the auth token table to prevent stale tokens from sticking
282 // around.
283 mAuthTokenTable.Clear();
284
285 if (password.size() == 0) {
286 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
287 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700288 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
289 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700290 } else {
291 switch (mKeyStore->getState(userId)) {
292 case ::STATE_UNINITIALIZED: {
293 // generate master key, encrypt with password, write to file,
294 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700295 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
296 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700297 }
298 case ::STATE_NO_ERROR: {
299 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700300 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
301 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700302 }
303 case ::STATE_LOCKED: {
304 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
305 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700306 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
307 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700308 }
309 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700310 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
311 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700312 }
313}
314
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700315Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700316 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700317 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
318 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700319 }
320
321 // Sanity check that the new user has an empty keystore.
322 if (!mKeyStore->isEmpty(userId)) {
323 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
324 }
325 // Unconditionally clear the keystore, just to be safe.
326 mKeyStore->resetUser(userId, false);
327 if (parentId != -1) {
328 // This profile must share the same master key password as the parent profile. Because the
329 // password of the parent profile is not known here, the best we can do is copy the parent's
330 // master key and master key file. This makes this profile use the same master key as the
331 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700332 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
333 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700334 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700335 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
336 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700337 }
338}
339
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700340Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700341 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700342 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
343 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700344 }
345
346 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700347 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
348 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700349}
350
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700351Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700352 if (!checkBinderPermission(P_LOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700353 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
354 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700355 }
356
357 State state = mKeyStore->getState(userId);
358 if (state != ::STATE_NO_ERROR) {
359 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700360 *aidl_return = static_cast<int32_t>(ResponseCode(state));
361 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700362 }
363
364 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700365 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
366 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700367}
368
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700369Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700370 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700371 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
372 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700373 }
374
375 State state = mKeyStore->getState(userId);
376 if (state != ::STATE_LOCKED) {
377 switch (state) {
378 case ::STATE_NO_ERROR:
379 ALOGI("calling unlock when already unlocked, ignoring.");
380 break;
381 case ::STATE_UNINITIALIZED:
382 ALOGE("unlock called on uninitialized keystore.");
383 break;
384 default:
385 ALOGE("unlock called on keystore in unknown state: %d", state);
386 break;
387 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700388 *aidl_return = static_cast<int32_t>(ResponseCode(state));
389 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700390 }
391
392 const String8 password8(pw);
393 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700394 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
395 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700396}
397
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700398Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700399 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700400 *aidl_return = static_cast<int32_t>(false);
401 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700402 }
403
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700404 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
405 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700406}
407
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700408Status KeyStoreService::generate(const String16& name, int32_t targetUid, int32_t keyType,
409 int32_t keySize, int32_t flags,
410 const ::android::security::KeystoreArguments& keystoreArgs,
411 int32_t* aidl_return) {
412 const Vector<sp<KeystoreArg>>* args = &(keystoreArgs.getArguments());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700413 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700414 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700415 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100416 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700417 *aidl_return = static_cast<int32_t>(result);
418 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700419 }
420
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100421 keystore::AuthorizationSet params;
422 add_legacy_key_authorizations(keyType, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700423
424 switch (keyType) {
425 case EVP_PKEY_EC: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100426 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700427 if (keySize == -1) {
428 keySize = EC_DEFAULT_KEY_SIZE;
429 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
430 ALOGI("invalid key size %d", keySize);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700431 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
432 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700433 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100434 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700435 break;
436 }
437 case EVP_PKEY_RSA: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100438 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700439 if (keySize == -1) {
440 keySize = RSA_DEFAULT_KEY_SIZE;
441 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
442 ALOGI("invalid key size %d", keySize);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700443 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
444 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700445 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100446 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700447 unsigned long exponent = RSA_DEFAULT_EXPONENT;
448 if (args->size() > 1) {
449 ALOGI("invalid number of arguments: %zu", args->size());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700450 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
451 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700452 } else if (args->size() == 1) {
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700453 const sp<KeystoreArg>& expArg = args->itemAt(0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700454 if (expArg != NULL) {
455 Unique_BIGNUM pubExpBn(BN_bin2bn(
456 reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
457 if (pubExpBn.get() == NULL) {
458 ALOGI("Could not convert public exponent to BN");
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700459 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
460 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700461 }
462 exponent = BN_get_word(pubExpBn.get());
463 if (exponent == 0xFFFFFFFFL) {
464 ALOGW("cannot represent public exponent as a long value");
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700465 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
466 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700467 }
468 } else {
469 ALOGW("public exponent not read");
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700470 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
471 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700472 }
473 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100474 params.push_back(TAG_RSA_PUBLIC_EXPONENT, exponent);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700475 break;
476 }
477 default: {
478 ALOGW("Unsupported key type %d", keyType);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700479 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
480 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700481 }
482 }
483
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700484 int32_t aidl_result;
485 android::security::keymaster::KeyCharacteristics unused_characteristics;
486 auto rc = generateKey(name, KeymasterArguments(params.hidl_data()), ::std::vector<uint8_t>(),
487 targetUid, flags, &unused_characteristics, &aidl_result);
488 if (!KeyStoreServiceReturnCode(aidl_result).isOk()) {
489 ALOGW("generate failed: %d", int32_t(aidl_result));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700490 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700491 *aidl_return = aidl_result;
492 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700493}
494
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700495Status KeyStoreService::import_key(const String16& name, const ::std::vector<uint8_t>& data,
496 int targetUid, int32_t flags, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700497
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100498 const uint8_t* ptr = &data[0];
499
500 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, data.size()));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700501 if (!pkcs8.get()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700502 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
503 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700504 }
505 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
506 if (!pkey.get()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700507 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
508 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700509 }
510 int type = EVP_PKEY_type(pkey->type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100511 AuthorizationSet params;
512 add_legacy_key_authorizations(type, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700513 switch (type) {
514 case EVP_PKEY_RSA:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100515 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700516 break;
517 case EVP_PKEY_EC:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100518 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700519 break;
520 default:
521 ALOGW("Unsupported key type %d", type);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700522 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
523 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700524 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100525
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700526 int import_result;
527 auto rc = importKey(name, KeymasterArguments(params.hidl_data()),
528 static_cast<int32_t>(KeyFormat::PKCS8), data, targetUid, flags,
529 /*outCharacteristics*/ NULL, &import_result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100530
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700531 if (!KeyStoreServiceReturnCode(import_result).isOk()) {
532 ALOGW("importKey failed: %d", int32_t(import_result));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700533 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700534 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
535 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700536}
537
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700538Status KeyStoreService::sign(const String16& name, const ::std::vector<uint8_t>& data,
539 ::std::vector<uint8_t>* out) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700540 if (!checkBinderPermission(P_SIGN)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700541 return Status::fromServiceSpecificError(
542 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700543 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700544 hidl_vec<uint8_t> legacy_out;
545 KeyStoreServiceReturnCode res =
546 doLegacySignVerify(name, data, &legacy_out, hidl_vec<uint8_t>(), KeyPurpose::SIGN);
547 *out = legacy_out;
548 return Status::fromServiceSpecificError((res));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700549}
550
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700551Status KeyStoreService::verify(const String16& name, const ::std::vector<uint8_t>& data,
552 const ::std::vector<uint8_t>& signature, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700553 if (!checkBinderPermission(P_VERIFY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700554 return Status::fromServiceSpecificError(
555 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700556 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700557 *aidl_return = static_cast<int32_t>(
558 doLegacySignVerify(name, data, nullptr, signature, KeyPurpose::VERIFY));
559 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700560}
561
562/*
563 * TODO: The abstraction between things stored in hardware and regular blobs
564 * of data stored on the filesystem should be moved down to keystore itself.
565 * Unfortunately the Java code that calls this has naming conventions that it
566 * knows about. Ideally keystore shouldn't be used to store random blobs of
567 * data.
568 *
569 * Until that happens, it's necessary to have a separate "get_pubkey" and
570 * "del_key" since the Java code doesn't really communicate what it's
571 * intentions are.
572 */
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700573Status KeyStoreService::get_pubkey(const String16& name, ::std::vector<uint8_t>* pubKey) {
574 android::security::keymaster::ExportResult result;
575 KeymasterBlob clientId;
576 KeymasterBlob appId;
577 exportKey(name, static_cast<int32_t>(KeyFormat::X509), clientId, appId, UID_SELF, &result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100578 if (!result.resultCode.isOk()) {
579 ALOGW("export failed: %d", int32_t(result.resultCode));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700580 return Status::fromServiceSpecificError(static_cast<int32_t>(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700581 }
582
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100583 if (pubKey) *pubKey = std::move(result.exportData);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700584 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700585}
586
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700587Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
588 ::android::String16* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700589 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100590 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
591 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700592 *aidl_return = String16();
593 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700594 }
595
596 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400597 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700598
599 if (access(filename.string(), R_OK) == -1) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700600 *aidl_return = String16();
601 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700602 }
603
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700604 *aidl_return =
605 String16(mKeyStore->addGrant(String8(name).string(), callingUid, granteeUid).c_str());
606 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700607}
608
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700609Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700610 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700611 KeyStoreServiceReturnCode result = checkBinderPermissionAndKeystoreState(P_GRANT);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100612 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700613 *aidl_return = static_cast<int32_t>(result);
614 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700615 }
616
617 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400618 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700619
620 if (access(filename.string(), R_OK) == -1) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700621 *aidl_return = static_cast<int32_t>((errno != ENOENT) ? ResponseCode::SYSTEM_ERROR
622 : ResponseCode::KEY_NOT_FOUND);
623 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700624 }
625
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700626 *aidl_return = static_cast<int32_t>(mKeyStore->removeGrant(name8, callingUid, granteeUid)
627 ? ResponseCode::NO_ERROR
628 : ResponseCode::KEY_NOT_FOUND);
629 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700630}
631
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700632Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700633 uid_t targetUid = getEffectiveUid(uid);
634 if (!checkBinderPermission(P_GET, targetUid)) {
635 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700636 *time = -1L;
637 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700638 }
639
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700640 auto filename = mKeyStore->getBlobFileNameIfExists(String8(name), targetUid, ::TYPE_ANY);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700641
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700642 if (!filename.isOk()) {
643 ALOGW("could not access %s for getmtime", filename.value().string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700644 *time = -1L;
645 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700646 }
647
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700648 int fd = TEMP_FAILURE_RETRY(open(filename.value().string(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700649 if (fd < 0) {
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700650 ALOGW("could not open %s for getmtime", filename.value().string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700651 *time = -1L;
652 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700653 }
654
655 struct stat s;
656 int ret = fstat(fd, &s);
657 close(fd);
658 if (ret == -1) {
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700659 ALOGW("could not stat %s for getmtime", filename.value().string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700660 *time = -1L;
661 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700662 }
663
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700664 *time = static_cast<int64_t>(s.st_mtime);
665 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700666}
667
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400668// TODO(tuckeris): This is dead code, remove it. Don't bother copying over key characteristics here
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700669Status KeyStoreService::duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
670 int32_t destUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700671 uid_t callingUid = IPCThreadState::self()->getCallingUid();
672 pid_t spid = IPCThreadState::self()->getCallingPid();
673 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
674 ALOGW("permission denied for %d: duplicate", callingUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700675 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
676 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700677 }
678
679 State state = mKeyStore->getState(get_user_id(callingUid));
680 if (!isKeystoreUnlocked(state)) {
681 ALOGD("calling duplicate in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700682 *aidl_return = static_cast<int32_t>(ResponseCode(state));
683 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700684 }
685
686 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
687 srcUid = callingUid;
688 } else if (!is_granted_to(callingUid, srcUid)) {
689 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700690 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
691 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700692 }
693
694 if (destUid == -1) {
695 destUid = callingUid;
696 }
697
698 if (srcUid != destUid) {
699 if (static_cast<uid_t>(srcUid) != callingUid) {
700 ALOGD("can only duplicate from caller to other or to same uid: "
701 "calling=%d, srcUid=%d, destUid=%d",
702 callingUid, srcUid, destUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700703 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
704 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700705 }
706
707 if (!is_granted_to(callingUid, destUid)) {
708 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700709 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
710 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700711 }
712 }
713
714 String8 source8(srcKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400715 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700716
717 String8 target8(destKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400718 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700719
720 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
721 ALOGD("destination already exists: %s", targetFile.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700722 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
723 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700724 }
725
726 Blob keyBlob;
727 ResponseCode responseCode =
728 mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, get_user_id(srcUid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100729 if (responseCode != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700730 *aidl_return = static_cast<int32_t>(responseCode);
731 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700732 }
733
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700734 *aidl_return =
735 static_cast<int32_t>(mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid)));
736 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700737}
738
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700739Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
740 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
741 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700742}
743
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700744Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700745 uid_t targetUid = getEffectiveUid(targetUid64);
746 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700747 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
748 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700749 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000750 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700751
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700752 mKeyStore->removeAllGrantsToUid(targetUid);
753
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700754 String8 prefix = String8::format("%u_", targetUid);
755 Vector<String16> aliases;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100756 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700757 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
758 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700759 }
760
761 for (uint32_t i = 0; i < aliases.size(); i++) {
762 String8 name8(aliases[i]);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400763 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Rubin Xu85c85e92017-04-26 20:07:30 +0100764
765 if (get_app_id(targetUid) == AID_SYSTEM) {
766 Blob keyBlob;
767 ResponseCode responseCode =
768 mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, get_user_id(targetUid));
769 if (responseCode == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
770 // Do not clear keys critical to device encryption under system uid.
771 continue;
772 }
773 }
774
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700775 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400776
777 // del() will fail silently if no cached characteristics are present for this alias.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100778 String8 chr_filename(
779 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400780 mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700781 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700782 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
783 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700784}
785
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700786Status KeyStoreService::addRngEntropy(const ::std::vector<uint8_t>& entropy, int32_t* aidl_return) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100787 const auto& device = mKeyStore->getDevice();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700788 *aidl_return = static_cast<int32_t>(
789 KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device->addRngEntropy(entropy))));
790 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700791}
792
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700793Status
794KeyStoreService::generateKey(const String16& name, const KeymasterArguments& params,
795 const ::std::vector<uint8_t>& entropy, int uid, int flags,
796 android::security::keymaster::KeyCharacteristics* outCharacteristics,
797 int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700798 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100799 KeyStoreServiceReturnCode rc =
800 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
801 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700802 *aidl_return = static_cast<int32_t>(rc);
803 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700804 }
Rubin Xu67899de2017-04-21 19:15:13 +0100805 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
806 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700807 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
808 return Status::ok();
Rubin Xu67899de2017-04-21 19:15:13 +0100809 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700810
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700811 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
812 if (!checkBinderPermission(P_GEN_UNIQUE_ID)) {
813 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
814 return Status::ok();
815 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600816 }
817
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100818 bool usingFallback = false;
819 auto& dev = mKeyStore->getDevice();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700820 AuthorizationSet keyCharacteristics = params.getParameters();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400821
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700822 // TODO: Seed from Linux RNG before this.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700823 int32_t result;
824 addRngEntropy(entropy, &result); // binder error is not possible.
825 if (!KeyStoreServiceReturnCode(result).isOk()) {
826 *aidl_return = static_cast<int32_t>(result);
827 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700828 }
829
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100830 KeyStoreServiceReturnCode error;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700831 auto hidl_cb = [&](ErrorCode ret, const ::std::vector<uint8_t>& hidlKeyBlob,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100832 const KeyCharacteristics& keyCharacteristics) {
833 error = ret;
834 if (!error.isOk()) {
835 return;
836 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700837 if (outCharacteristics)
838 *outCharacteristics =
839 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700840
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100841 // Write the key
842 String8 name8(name);
843 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700844
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100845 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
846 keyBlob.setFallback(usingFallback);
Rubin Xu67899de2017-04-21 19:15:13 +0100847 keyBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700848 if (isAuthenticationBound(params.getParameters()) &&
849 !keyBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -0700850 keyBlob.setSuperEncrypted(true);
851 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100852 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700853
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100854 error = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
855 };
856
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700857 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(params.getParameters(), hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100858 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700859 *aidl_return = static_cast<int32_t>(rc);
860 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400861 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100862 if (!error.isOk()) {
863 ALOGE("Failed to generate key -> falling back to software keymaster");
864 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000865 auto fallback = mKeyStore->getFallbackDevice();
866 if (!fallback.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700867 *aidl_return = static_cast<int32_t>(error);
868 return Status::ok();
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000869 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700870 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->generateKey(params.getParameters(), hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100871 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700872 *aidl_return = static_cast<int32_t>(rc);
873 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100874 }
875 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700876 *aidl_return = static_cast<int32_t>(error);
877 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100878 }
879 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400880
881 // Write the characteristics:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100882 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400883 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
884
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100885 std::stringstream kc_stream;
886 keyCharacteristics.Serialize(&kc_stream);
887 if (kc_stream.bad()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700888 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
889 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100890 }
891 auto kc_buf = kc_stream.str();
892 Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
893 ::TYPE_KEY_CHARACTERISTICS);
894 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400895 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
896
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700897 *aidl_return =
898 static_cast<int32_t>(mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid)));
899 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700900}
901
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700902Status KeyStoreService::getKeyCharacteristics(
903 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
904 const ::android::security::keymaster::KeymasterBlob& appId, int32_t uid,
905 ::android::security::keymaster::KeyCharacteristics* outCharacteristics, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700906 if (!outCharacteristics) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700907 *aidl_return =
908 static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::UNEXPECTED_NULL_POINTER));
909 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700910 }
911
912 uid_t targetUid = getEffectiveUid(uid);
913 uid_t callingUid = IPCThreadState::self()->getCallingUid();
914 if (!is_granted_to(callingUid, targetUid)) {
915 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
916 targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700917 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
918 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700919 }
920
921 Blob keyBlob;
922 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700923
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100924 KeyStoreServiceReturnCode rc =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700925 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskisd714a672017-09-01 14:31:36 -0700926 if (rc == ResponseCode::UNINITIALIZED) {
927 /*
928 * If we fail reading the blob because the master key is missing we try to retrieve the
929 * key characteristics from the characteristics file. This happens when auth-bound
930 * keys are used after a screen lock has been removed by the user.
931 */
932 rc = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
933 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700934 *aidl_return = static_cast<int32_t>(rc);
935 return Status::ok();
Janis Danisevskisd714a672017-09-01 14:31:36 -0700936 }
937 AuthorizationSet keyCharacteristics;
938 // TODO write one shot stream buffer to avoid copying (twice here)
939 std::string charBuffer(reinterpret_cast<const char*>(keyBlob.getValue()),
940 keyBlob.getLength());
941 std::stringstream charStream(charBuffer);
942 keyCharacteristics.Deserialize(&charStream);
943
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700944 outCharacteristics->softwareEnforced = KeymasterArguments(keyCharacteristics.hidl_data());
945 *aidl_return = static_cast<int32_t>(rc);
946 return Status::ok();
Janis Danisevskisd714a672017-09-01 14:31:36 -0700947 } else if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700948 *aidl_return = static_cast<int32_t>(rc);
949 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700950 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100951
952 auto hidlKeyBlob = blob2hidlVec(keyBlob);
953 auto& dev = mKeyStore->getDevice(keyBlob);
954
955 KeyStoreServiceReturnCode error;
956
957 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
958 error = ret;
959 if (!error.isOk()) {
960 return;
Shawn Willden98c59162016-03-20 09:10:18 -0600961 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700962 *outCharacteristics =
963 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100964 };
965
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700966 rc = KS_HANDLE_HIDL_ERROR(
967 dev->getKeyCharacteristics(hidlKeyBlob, clientId.getData(), appId.getData(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100968 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700969 *aidl_return = static_cast<int32_t>(rc);
970 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100971 }
972
973 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
974 AuthorizationSet upgradeParams;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700975 if (clientId.getData().size()) {
976 upgradeParams.push_back(TAG_APPLICATION_ID, clientId.getData());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100977 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700978 if (appId.getData().size()) {
979 upgradeParams.push_back(TAG_APPLICATION_DATA, appId.getData());
Shawn Willden98c59162016-03-20 09:10:18 -0600980 }
981 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100982 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700983 *aidl_return = static_cast<int32_t>(rc);
984 return Status::ok();
Shawn Willden98c59162016-03-20 09:10:18 -0600985 }
Shawn Willden715d0232016-01-21 00:45:13 -0700986
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100987 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
988
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700989 rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(
990 upgradedHidlKeyBlob, clientId.getData(), appId.getData(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100991 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700992 *aidl_return = static_cast<int32_t>(rc);
993 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100994 }
995 // Note that, on success, "error" will have been updated by the hidlCB callback.
996 // So it is fine to return "error" below.
997 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700998 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(error));
999 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001000}
1001
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001002Status
1003KeyStoreService::importKey(const String16& name, const KeymasterArguments& params, int32_t format,
1004 const ::std::vector<uint8_t>& keyData, int uid, int flags,
1005 ::android::security::keymaster::KeyCharacteristics* outCharacteristics,
1006 int32_t* aidl_return) {
1007
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001008 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001009 KeyStoreServiceReturnCode rc =
1010 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
1011 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001012 *aidl_return = static_cast<int32_t>(rc);
1013 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001014 }
Rubin Xu67899de2017-04-21 19:15:13 +01001015 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
1016 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001017 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
1018 return Status::ok();
Rubin Xu67899de2017-04-21 19:15:13 +01001019 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001020
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001021 bool usingFallback = false;
1022 auto& dev = mKeyStore->getDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001023
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001024 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001025
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001026 KeyStoreServiceReturnCode error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001027
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001028 auto hidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& keyBlob,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001029 const KeyCharacteristics& keyCharacteristics) {
1030 error = ret;
1031 if (!error.isOk()) {
1032 return;
1033 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001034 if (outCharacteristics)
1035 *outCharacteristics =
1036 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001037
1038 // Write the key:
1039 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1040
1041 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
1042 ksBlob.setFallback(usingFallback);
Rubin Xu67899de2017-04-21 19:15:13 +01001043 ksBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001044 if (isAuthenticationBound(params.getParameters()) &&
1045 !ksBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -07001046 ksBlob.setSuperEncrypted(true);
1047 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001048 ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1049
1050 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
1051 };
1052
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001053 rc = KS_HANDLE_HIDL_ERROR(
1054 dev->importKey(params.getParameters(), KeyFormat(format), keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001055 // possible hidl error
1056 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001057 *aidl_return = static_cast<int32_t>(rc);
1058 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001059 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001060 // now check error from callback
1061 if (!error.isOk()) {
1062 ALOGE("Failed to import key -> falling back to software keymaster");
1063 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +00001064 auto fallback = mKeyStore->getFallbackDevice();
1065 if (!fallback.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001066 *aidl_return = static_cast<int32_t>(error);
1067 return Status::ok();
Janis Danisevskise8ba1802017-01-30 10:49:51 +00001068 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001069 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->importKey(params.getParameters(),
1070 KeyFormat(format), keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001071 // possible hidl error
1072 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001073 *aidl_return = static_cast<int32_t>(rc);
1074 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001075 }
1076 // now check error from callback
1077 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001078 *aidl_return = static_cast<int32_t>(error);
1079 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001080 }
1081 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001082
1083 // Write the characteristics:
1084 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
1085
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001086 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001087 std::stringstream kcStream;
1088 opParams.Serialize(&kcStream);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001089 if (kcStream.bad()) {
1090 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
1091 return Status::ok();
1092 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001093 auto kcBuf = kcStream.str();
1094
1095 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
1096 ::TYPE_KEY_CHARACTERISTICS);
1097 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001098 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1099
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001100 *aidl_return =
1101 static_cast<int32_t>(mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid)));
1102
1103 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001104}
1105
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001106Status KeyStoreService::exportKey(const String16& name, int32_t format,
1107 const ::android::security::keymaster::KeymasterBlob& clientId,
1108 const ::android::security::keymaster::KeymasterBlob& appId,
1109 int32_t uid, ExportResult* result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001110
1111 uid_t targetUid = getEffectiveUid(uid);
1112 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1113 if (!is_granted_to(callingUid, targetUid)) {
1114 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001115 result->resultCode = ResponseCode::PERMISSION_DENIED;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001116 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001117 }
1118
1119 Blob keyBlob;
1120 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001121
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001122 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
1123 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001124 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001125 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001126
1127 auto key = blob2hidlVec(keyBlob);
1128 auto& dev = mKeyStore->getDevice(keyBlob);
1129
1130 auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
1131 result->resultCode = ret;
1132 if (!result->resultCode.isOk()) {
Ji Wang2c142312016-10-14 17:21:10 +08001133 return;
1134 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001135 result->exportData = keyMaterial;
1136 };
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001137 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
1138 dev->exportKey(KeyFormat(format), key, clientId.getData(), appId.getData(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001139 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
1140 // callback hidlCb.
1141 if (!rc.isOk()) {
1142 result->resultCode = rc;
Ji Wang2c142312016-10-14 17:21:10 +08001143 }
1144
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001145 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1146 AuthorizationSet upgradeParams;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001147 if (clientId.getData().size()) {
1148 upgradeParams.push_back(TAG_APPLICATION_ID, clientId.getData());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001149 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001150 if (appId.getData().size()) {
1151 upgradeParams.push_back(TAG_APPLICATION_DATA, appId.getData());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001152 }
1153 result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
1154 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001155 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001156 }
1157
1158 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
1159
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001160 result->resultCode = KS_HANDLE_HIDL_ERROR(dev->exportKey(
1161 KeyFormat(format), upgradedHidlKeyBlob, clientId.getData(), appId.getData(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001162 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001163 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001164 }
1165 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001166 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001167}
1168
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001169static inline void addAuthTokenToParams(AuthorizationSet* params, const HardwareAuthToken* token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001170 if (token) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001171 params->push_back(TAG_AUTH_TOKEN, authToken2HidlVec(*token));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001172 }
1173}
1174
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001175Status KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, int32_t purpose,
1176 bool pruneable, const KeymasterArguments& params,
1177 const ::std::vector<uint8_t>& entropy, int32_t uid,
1178 OperationResult* result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001179 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1180 uid_t targetUid = getEffectiveUid(uid);
1181 if (!is_granted_to(callingUid, targetUid)) {
1182 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001183 result->resultCode = ResponseCode::PERMISSION_DENIED;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001184 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001185 }
1186 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
1187 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001188 result->resultCode = ResponseCode::PERMISSION_DENIED;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001189 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001190 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001191 if (!checkAllowedOperationParams(params.getParameters())) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001192 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001193 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001194 }
1195 Blob keyBlob;
1196 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001197 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Shawn Willdend5a24e62017-02-28 13:53:24 -07001198 if (result->resultCode == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
1199 result->resultCode = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1200 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001201 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001202 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001203 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001204
1205 auto key = blob2hidlVec(keyBlob);
1206 auto& dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001207 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001208 KeyCharacteristics characteristics;
1209 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
1210
1211 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1212 result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
1213 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001214 return Status::ok();
Shawn Willden98c59162016-03-20 09:10:18 -06001215 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001216 key = blob2hidlVec(keyBlob);
1217 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
Shawn Willden98c59162016-03-20 09:10:18 -06001218 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001219 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001220 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001221 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001222
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001223 const HardwareAuthToken* authToken = NULL;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001224
1225 // Merge these characteristics with the ones cached when the key was generated or imported
1226 Blob charBlob;
1227 AuthorizationSet persistedCharacteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001228 result->resultCode =
1229 mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
1230 if (result->resultCode.isOk()) {
1231 // TODO write one shot stream buffer to avoid copying (twice here)
1232 std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
1233 charBlob.getLength());
1234 std::stringstream charStream(charBuffer);
1235 persistedCharacteristics.Deserialize(&charStream);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001236 } else {
1237 ALOGD("Unable to read cached characteristics for key");
1238 }
1239
1240 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001241 AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
1242 AuthorizationSet teeEnforced = characteristics.teeEnforced;
1243 persistedCharacteristics.Union(softwareEnforced);
1244 persistedCharacteristics.Subtract(teeEnforced);
1245 characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001246
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001247 auto authResult = getAuthToken(characteristics, 0, KeyPurpose(purpose), &authToken,
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001248 /*failOnTokenMissing*/ false);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001249 // If per-operation auth is needed we need to begin the operation and
1250 // the client will need to authorize that operation before calling
1251 // update. Any other auth issues stop here.
Shawn Willden827243a2017-09-12 05:41:33 -06001252 if (!authResult.isOk() && authResult != ResponseCode::OP_AUTH_NEEDED) {
1253 result->resultCode = authResult;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001254 return Status::ok();
Shawn Willden827243a2017-09-12 05:41:33 -06001255 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001256
1257 addAuthTokenToParams(&opParams, authToken);
1258
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001259 // Add entropy to the device first.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001260 if (entropy.size()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001261 int32_t resultCode;
1262 addRngEntropy(entropy, &resultCode); // binder error is not possible
1263 result->resultCode = KeyStoreServiceReturnCode(resultCode);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001264 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001265 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001266 }
1267 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001268
1269 // Create a keyid for this key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001270 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001271 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
1272 ALOGE("Failed to create a key ID for authorization checking.");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001273 result->resultCode = ErrorCode::UNKNOWN_ERROR;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001274 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001275 }
1276
1277 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001278 AuthorizationSet key_auths = characteristics.teeEnforced;
1279 key_auths.append(&characteristics.softwareEnforced[0],
1280 &characteristics.softwareEnforced[characteristics.softwareEnforced.size()]);
1281
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001282 result->resultCode =
1283 enforcement_policy.AuthorizeOperation(KeyPurpose(purpose), keyid, key_auths, opParams,
1284 0 /* op_handle */, true /* is_begin_operation */);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001285 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001286 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001287 }
1288
Shawn Willdene2a7b522017-04-11 09:27:40 -06001289 // If there are more than kMaxOperations, abort the oldest operation that was started as
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001290 // pruneable.
Shawn Willdene2a7b522017-04-11 09:27:40 -06001291 while (mOperationMap.getOperationCount() >= kMaxOperations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001292 ALOGD("Reached or exceeded concurrent operations limit");
1293 if (!pruneOperation()) {
1294 break;
1295 }
1296 }
1297
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001298 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1299 uint64_t operationHandle) {
1300 result->resultCode = ret;
1301 if (!result->resultCode.isOk()) {
1302 return;
1303 }
1304 result->handle = operationHandle;
1305 result->outParams = outParams;
1306 };
1307
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001308 ErrorCode rc =
1309 KS_HANDLE_HIDL_ERROR(dev->begin(KeyPurpose(purpose), key, opParams.hidl_data(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001310 if (rc != ErrorCode::OK) {
1311 ALOGW("Got error %d from begin()", rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001312 }
1313
1314 // If there are too many operations abort the oldest operation that was
1315 // started as pruneable and try again.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001316 while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1317 ALOGW("Ran out of operation handles");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001318 if (!pruneOperation()) {
1319 break;
1320 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001321 rc = KS_HANDLE_HIDL_ERROR(
1322 dev->begin(KeyPurpose(purpose), key, opParams.hidl_data(), hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001323 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001324 if (rc != ErrorCode::OK) {
1325 result->resultCode = rc;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001326 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001327 }
1328
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001329 // Note: The operation map takes possession of the contents of "characteristics".
1330 // It is safe to use characteristics after the following line but it will be empty.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001331 sp<IBinder> operationToken =
1332 mOperationMap.addOperation(result->handle, keyid, KeyPurpose(purpose), dev, appToken,
1333 std::move(characteristics), pruneable);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001334 assert(characteristics.teeEnforced.size() == 0);
1335 assert(characteristics.softwareEnforced.size() == 0);
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001336 result->token = operationToken;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001337
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001338 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001339 mOperationMap.setOperationAuthToken(operationToken, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001340 }
1341 // Return the authentication lookup result. If this is a per operation
1342 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1343 // application should get an auth token using the handle before the
1344 // first call to update, which will fail if keystore hasn't received the
1345 // auth token.
Shawn Willden2f96c792017-09-07 23:59:08 -06001346 if (result->resultCode == ErrorCode::OK) {
1347 result->resultCode = authResult;
1348 }
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001349
1350 // Other result fields were set in the begin operation's callback.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001351 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001352}
1353
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001354Status KeyStoreService::update(const sp<IBinder>& token, const KeymasterArguments& params,
1355 const ::std::vector<uint8_t>& data, OperationResult* result) {
1356 if (!checkAllowedOperationParams(params.getParameters())) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001357 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001358 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001359 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001360 km_device_t dev;
1361 uint64_t handle;
1362 KeyPurpose purpose;
1363 km_id_t keyid;
1364 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001365 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001366 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001367 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001368 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001369 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001370 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1371 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001372 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001373 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001374
1375 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001376 AuthorizationSet key_auths(characteristics->teeEnforced);
1377 key_auths.append(&characteristics->softwareEnforced[0],
1378 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001379 result->resultCode = enforcement_policy.AuthorizeOperation(
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001380 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1381 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001382 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001383 }
1384
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001385 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001386 const hidl_vec<KeyParameter>& outParams,
1387 const ::std::vector<uint8_t>& output) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001388 result->resultCode = ret;
1389 if (!result->resultCode.isOk()) {
1390 return;
1391 }
1392 result->inputConsumed = inputConsumed;
1393 result->outParams = outParams;
1394 result->data = output;
1395 };
1396
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001397 KeyStoreServiceReturnCode rc =
1398 KS_HANDLE_HIDL_ERROR(dev->update(handle, opParams.hidl_data(), data, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001399 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1400 // it if there was a communication error indicated by the ErrorCode.
1401 if (!rc.isOk()) {
1402 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001403 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001404 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001405}
1406
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001407Status KeyStoreService::finish(const sp<IBinder>& token, const KeymasterArguments& params,
1408 const ::std::vector<uint8_t>& signature,
1409 const ::std::vector<uint8_t>& entropy, OperationResult* result) {
1410 if (!checkAllowedOperationParams(params.getParameters())) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001411 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001412 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001413 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001414 km_device_t dev;
1415 uint64_t handle;
1416 KeyPurpose purpose;
1417 km_id_t keyid;
1418 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001419 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001420 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001421 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001422 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001423 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001424 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1425 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001426 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001427 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001428
1429 if (entropy.size()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001430 int resultCode;
1431 addRngEntropy(entropy, &resultCode); // binder error is not possible
1432 result->resultCode = KeyStoreServiceReturnCode(resultCode);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001433 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001434 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001435 }
1436 }
1437
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001438 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001439 AuthorizationSet key_auths(characteristics->teeEnforced);
1440 key_auths.append(&characteristics->softwareEnforced[0],
1441 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
1442 result->resultCode = enforcement_policy.AuthorizeOperation(
1443 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001444 if (!result->resultCode.isOk()) return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001445
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001446 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001447 const ::std::vector<uint8_t>& output) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001448 result->resultCode = ret;
1449 if (!result->resultCode.isOk()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001450 }
1451 result->outParams = outParams;
1452 result->data = output;
1453 };
1454
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001455 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
1456 dev->finish(handle, opParams.hidl_data(),
1457 ::std::vector<uint8_t>() /* TODO(swillden): wire up input to finish() */,
1458 signature, hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001459 // Remove the operation regardless of the result
1460 mOperationMap.removeOperation(token);
1461 mAuthTokenTable.MarkCompleted(handle);
1462
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001463 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1464 // it if there was a communication error indicated by the ErrorCode.
1465 if (!rc.isOk()) {
1466 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001467 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001468 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001469}
1470
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001471Status KeyStoreService::abort(const sp<IBinder>& token, int32_t* aidl_return) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001472 km_device_t dev;
1473 uint64_t handle;
1474 KeyPurpose purpose;
1475 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001476 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001477 *aidl_return =
1478 static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_OPERATION_HANDLE));
1479 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001480 }
1481 mOperationMap.removeOperation(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001482
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001483 ErrorCode error_code = KS_HANDLE_HIDL_ERROR(dev->abort(handle));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001484 mAuthTokenTable.MarkCompleted(handle);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001485 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(error_code));
1486 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001487}
1488
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001489Status KeyStoreService::isOperationAuthorized(const sp<IBinder>& token, bool* aidl_return) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001490 km_device_t dev;
1491 uint64_t handle;
1492 const KeyCharacteristics* characteristics;
1493 KeyPurpose purpose;
1494 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001495 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001496 *aidl_return = false;
1497 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001498 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001499 const HardwareAuthToken* authToken = NULL;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001500 mOperationMap.getOperationAuthToken(token, &authToken);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001501 AuthorizationSet ignored;
1502 auto authResult = addOperationAuthTokenIfNeeded(token, &ignored);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001503 *aidl_return = authResult.isOk();
1504 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001505}
1506
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001507Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
1508 int32_t* aidl_return) {
1509
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001510 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1511 // receive a HardwareAuthToken, rather than an opaque byte array.
1512
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001513 if (!checkBinderPermission(P_ADD_AUTH)) {
1514 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001515 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
1516 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001517 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001518 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
1519 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1520 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001521 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001522
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001523 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001524 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001525 if (authToken.version != 0) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001526 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1527 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001528 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001529
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001530 std::unique_ptr<HardwareAuthToken> hidlAuthToken(new HardwareAuthToken);
1531 hidlAuthToken->challenge = authToken.challenge;
1532 hidlAuthToken->userId = authToken.user_id;
1533 hidlAuthToken->authenticatorId = authToken.authenticator_id;
1534 hidlAuthToken->authenticatorType = authToken.authenticator_type;
1535 hidlAuthToken->timestamp = authToken.timestamp;
1536 static_assert(
1537 std::is_same<decltype(hidlAuthToken->hmac),
1538 ::android::hardware::hidl_array<uint8_t, sizeof(authToken.hmac)>>::value,
1539 "This function assumes token HMAC is 32 bytes, but it might not be.");
1540 std::copy(authToken.hmac, authToken.hmac + sizeof(authToken.hmac), hidlAuthToken->hmac.data());
1541
1542 // The table takes ownership of authToken.
1543 mAuthTokenTable.AddAuthenticationToken(hidlAuthToken.release());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001544 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1545 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001546}
1547
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001548bool isDeviceIdAttestationRequested(const KeymasterArguments& params) {
1549 const hardware::hidl_vec<KeyParameter> paramsVec = params.getParameters();
1550 for (size_t i = 0; i < paramsVec.size(); ++i) {
1551 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -06001552 case Tag::ATTESTATION_ID_BRAND:
1553 case Tag::ATTESTATION_ID_DEVICE:
1554 case Tag::ATTESTATION_ID_IMEI:
1555 case Tag::ATTESTATION_ID_MANUFACTURER:
1556 case Tag::ATTESTATION_ID_MEID:
1557 case Tag::ATTESTATION_ID_MODEL:
1558 case Tag::ATTESTATION_ID_PRODUCT:
1559 case Tag::ATTESTATION_ID_SERIAL:
1560 return true;
1561 default:
1562 break;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001563 }
1564 }
1565 return false;
1566}
1567
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001568Status KeyStoreService::attestKey(const String16& name, const KeymasterArguments& params,
1569 ::android::security::keymaster::KeymasterCertificateChain* chain,
1570 int32_t* aidl_return) {
1571 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1572 if (!checkAllowedOperationParams(params.getParameters())) {
1573 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1574 return Status::ok();
Shawn Willden50eb1b22016-01-21 12:41:23 -07001575 }
1576
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001577 if (isDeviceIdAttestationRequested(params)) {
1578 // There is a dedicated attestDeviceIds() method for device ID attestation.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001579 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1580 return Status::ok();
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001581 }
1582
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001583 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1584
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001585 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001586 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1587 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001588 *aidl_return = static_cast<int32_t>(rc);
1589 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001590 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001591
Shawn Willden50eb1b22016-01-21 12:41:23 -07001592 Blob keyBlob;
1593 String8 name8(name);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001594 rc = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
1595 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001596 *aidl_return = static_cast<int32_t>(rc);
1597 return Status::ok();
Shawn Willden50eb1b22016-01-21 12:41:23 -07001598 }
1599
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001600 KeyStoreServiceReturnCode error;
1601 auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1602 error = ret;
1603 if (!error.isOk()) {
1604 return;
1605 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001606 if (chain) {
1607 *chain = KeymasterCertificateChain(certChain);
1608 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001609 };
1610
1611 auto hidlKey = blob2hidlVec(keyBlob);
1612 auto& dev = mKeyStore->getDevice(keyBlob);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001613 rc = KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
1614 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001615 *aidl_return = static_cast<int32_t>(rc);
1616 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001617 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001618 *aidl_return = static_cast<int32_t>(error);
1619 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001620}
1621
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001622Status
1623KeyStoreService::attestDeviceIds(const KeymasterArguments& params,
1624 ::android::security::keymaster::KeymasterCertificateChain* chain,
1625 int32_t* aidl_return) {
1626 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001627
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001628 if (!checkAllowedOperationParams(params.getParameters())) {
1629 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1630 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001631 }
1632
1633 if (!isDeviceIdAttestationRequested(params)) {
1634 // There is an attestKey() method for attesting keys without device ID attestation.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001635 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1636 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001637 }
1638
1639 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1640 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1641 if (binder == 0) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001642 *aidl_return =
1643 static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::CANNOT_ATTEST_IDS));
1644 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001645 }
1646 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1647 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1648 IPCThreadState::self()->getCallingPid(), callingUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001649 *aidl_return =
1650 static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::CANNOT_ATTEST_IDS));
1651 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001652 }
1653
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001654 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001655 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1656 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001657 *aidl_return = static_cast<int32_t>(rc);
1658 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001659 }
1660
1661 // Generate temporary key.
1662 auto& dev = mKeyStore->getDevice();
1663 KeyStoreServiceReturnCode error;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001664 ::std::vector<uint8_t> hidlKey;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001665
1666 AuthorizationSet keyCharacteristics;
1667 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1668 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1669 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1670 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1671 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001672 auto generateHidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& hidlKeyBlob,
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001673 const KeyCharacteristics&) {
1674 error = ret;
1675 if (!error.isOk()) {
1676 return;
1677 }
1678 hidlKey = hidlKeyBlob;
1679 };
1680
1681 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(keyCharacteristics.hidl_data(), generateHidlCb));
1682 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001683 *aidl_return = static_cast<int32_t>(rc);
1684 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001685 }
1686 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001687 *aidl_return = static_cast<int32_t>(error);
1688 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001689 }
1690
1691 // Attest key and device IDs.
1692 auto attestHidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1693 error = ret;
1694 if (!error.isOk()) {
1695 return;
1696 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001697 *chain = ::android::security::keymaster::KeymasterCertificateChain(certChain);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001698 };
1699 KeyStoreServiceReturnCode attestationRc =
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001700 KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), attestHidlCb));
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001701
1702 // Delete temporary key.
1703 KeyStoreServiceReturnCode deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001704
1705 if (!attestationRc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001706 *aidl_return = static_cast<int32_t>(attestationRc);
1707 return Status::ok();
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001708 }
1709 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001710 *aidl_return = static_cast<int32_t>(error);
1711 return Status::ok();
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001712 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001713 *aidl_return = static_cast<int32_t>(deletionRc);
1714 return Status::ok();
Shawn Willden50eb1b22016-01-21 12:41:23 -07001715}
1716
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001717Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001718 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1719 mAuthTokenTable.onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001720 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1721 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001722}
1723
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001724/**
1725 * Prune the oldest pruneable operation.
1726 */
1727bool KeyStoreService::pruneOperation() {
1728 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1729 ALOGD("Trying to prune operation %p", oldest.get());
1730 size_t op_count_before_abort = mOperationMap.getOperationCount();
1731 // We mostly ignore errors from abort() because all we care about is whether at least
1732 // one operation has been removed.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001733 int32_t abort_error;
1734 abort(oldest, &abort_error);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001735 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1736 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1737 return false;
1738 }
1739 return true;
1740}
1741
1742/**
1743 * Get the effective target uid for a binder operation that takes an
1744 * optional uid as the target.
1745 */
1746uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1747 if (targetUid == UID_SELF) {
1748 return IPCThreadState::self()->getCallingUid();
1749 }
1750 return static_cast<uid_t>(targetUid);
1751}
1752
1753/**
1754 * Check if the caller of the current binder method has the required
1755 * permission and if acting on other uids the grants to do so.
1756 */
1757bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1758 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1759 pid_t spid = IPCThreadState::self()->getCallingPid();
1760 if (!has_permission(callingUid, permission, spid)) {
1761 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1762 return false;
1763 }
1764 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1765 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1766 return false;
1767 }
1768 return true;
1769}
1770
1771/**
1772 * Check if the caller of the current binder method has the required
1773 * permission and the target uid is the caller or the caller is system.
1774 */
1775bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1776 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1777 pid_t spid = IPCThreadState::self()->getCallingPid();
1778 if (!has_permission(callingUid, permission, spid)) {
1779 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1780 return false;
1781 }
1782 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1783}
1784
1785/**
1786 * Check if the caller of the current binder method has the required
1787 * permission or the target of the operation is the caller's uid. This is
1788 * for operation where the permission is only for cross-uid activity and all
1789 * uids are allowed to act on their own (ie: clearing all entries for a
1790 * given uid).
1791 */
1792bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1793 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1794 if (getEffectiveUid(targetUid) == callingUid) {
1795 return true;
1796 } else {
1797 return checkBinderPermission(permission, targetUid);
1798 }
1799}
1800
1801/**
1802 * Helper method to check that the caller has the required permission as
1803 * well as the keystore is in the unlocked state if checkUnlocked is true.
1804 *
1805 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1806 * otherwise the state of keystore when not unlocked and checkUnlocked is
1807 * true.
1808 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001809KeyStoreServiceReturnCode
1810KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1811 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001812 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001813 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001814 }
1815 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1816 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001817 // All State values coincide with ResponseCodes
1818 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001819 }
1820
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001821 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001822}
1823
1824bool KeyStoreService::isKeystoreUnlocked(State state) {
1825 switch (state) {
1826 case ::STATE_NO_ERROR:
1827 return true;
1828 case ::STATE_UNINITIALIZED:
1829 case ::STATE_LOCKED:
1830 return false;
1831 }
1832 return false;
1833}
1834
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001835/**
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001836 * Check that all KeyParameter's provided by the application are
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001837 * allowed. Any parameter that keystore adds itself should be disallowed here.
1838 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001839bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1840 for (size_t i = 0; i < params.size(); ++i) {
1841 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001842 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001843 case Tag::AUTH_TOKEN:
1844 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001845 return false;
1846 default:
1847 break;
1848 }
1849 }
1850 return true;
1851}
1852
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001853ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
1854 km_device_t* dev,
1855 const AuthorizationSet& params,
1856 KeyCharacteristics* out) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001857 ::std::vector<uint8_t> appId;
1858 ::std::vector<uint8_t> appData;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001859 for (auto param : params) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001860 if (param.tag == Tag::APPLICATION_ID) {
1861 appId = authorizationValue(TAG_APPLICATION_ID, param).value();
1862 } else if (param.tag == Tag::APPLICATION_DATA) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001863 appId = authorizationValue(TAG_APPLICATION_DATA, param).value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001864 }
1865 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001866 ErrorCode error = ErrorCode::OK;
1867
1868 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
1869 error = ret;
1870 if (error != ErrorCode::OK) {
1871 return;
1872 }
1873 if (out) *out = keyCharacteristics;
1874 };
1875
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001876 ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appId, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001877 if (rc != ErrorCode::OK) {
1878 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001879 }
1880 return error;
1881}
1882
1883/**
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001884 * Get the auth token for this operation from the auth token table.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001885 *
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001886 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
1887 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1888 * authorization token exists for that operation and
1889 * failOnTokenMissing is false.
1890 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1891 * token for the operation
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001892 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001893KeyStoreServiceReturnCode KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics,
1894 uint64_t handle, KeyPurpose purpose,
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001895 const HardwareAuthToken** authToken,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001896 bool failOnTokenMissing) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001897
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001898 AuthorizationSet allCharacteristics;
1899 for (size_t i = 0; i < characteristics.softwareEnforced.size(); i++) {
1900 allCharacteristics.push_back(characteristics.softwareEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001901 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001902 for (size_t i = 0; i < characteristics.teeEnforced.size(); i++) {
1903 allCharacteristics.push_back(characteristics.teeEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001904 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001905 AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
1906 allCharacteristics, KeyPurpose(purpose), handle, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001907 switch (err) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001908 case AuthTokenTable::OK:
1909 case AuthTokenTable::AUTH_NOT_REQUIRED:
1910 return ResponseCode::NO_ERROR;
1911 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1912 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
1913 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001914 ALOGE("getAuthToken failed: %d", err); // STOPSHIP: debug only, to be removed
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001915 return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1916 case AuthTokenTable::OP_HANDLE_REQUIRED:
1917 return failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
1918 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001919 default:
1920 ALOGE("Unexpected FindAuthorization return value %d", err);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001921 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001922 }
1923}
1924
1925/**
1926 * Add the auth token for the operation to the param list if the operation
1927 * requires authorization. Uses the cached result in the OperationMap if available
1928 * otherwise gets the token from the AuthTokenTable and caches the result.
1929 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001930 * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001931 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1932 * authenticated.
1933 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1934 * operation token.
1935 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001936KeyStoreServiceReturnCode KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
1937 AuthorizationSet* params) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001938 const HardwareAuthToken* authToken = nullptr;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001939 mOperationMap.getOperationAuthToken(token, &authToken);
1940 if (!authToken) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001941 km_device_t dev;
1942 uint64_t handle;
1943 const KeyCharacteristics* characteristics = nullptr;
1944 KeyPurpose purpose;
1945 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001946 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001947 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001948 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001949 auto result = getAuthToken(*characteristics, handle, purpose, &authToken);
1950 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001951 return result;
1952 }
1953 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001954 mOperationMap.setOperationAuthToken(token, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001955 }
1956 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001957 addAuthTokenToParams(params, authToken);
1958 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001959}
1960
1961/**
1962 * Translate a result value to a legacy return value. All keystore errors are
1963 * preserved and keymaster errors become SYSTEM_ERRORs
1964 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001965KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001966 if (result > 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001967 return static_cast<ResponseCode>(result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001968 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001969 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001970}
1971
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001972static NullOr<const Algorithm&> getKeyAlgoritmFromKeyCharacteristics(
1973 const ::android::security::keymaster::KeyCharacteristics& characteristics) {
1974 for (size_t i = 0; i < characteristics.teeEnforced.getParameters().size(); ++i) {
1975 auto algo =
1976 authorizationValue(TAG_ALGORITHM, characteristics.teeEnforced.getParameters()[i]);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001977 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001978 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001979 for (size_t i = 0; i < characteristics.softwareEnforced.getParameters().size(); ++i) {
1980 auto algo =
1981 authorizationValue(TAG_ALGORITHM, characteristics.softwareEnforced.getParameters()[i]);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001982 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001983 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001984 return {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001985}
1986
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001987void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001988 // All legacy keys are DIGEST_NONE/PAD_NONE.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001989 params->push_back(TAG_DIGEST, Digest::NONE);
1990 params->push_back(TAG_PADDING, PaddingMode::NONE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001991
1992 // Look up the algorithm of the key.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001993 ::android::security::keymaster::KeyCharacteristics characteristics;
1994 int32_t result;
1995 auto rc = getKeyCharacteristics(name, ::android::security::keymaster::KeymasterBlob(),
1996 ::android::security::keymaster::KeymasterBlob(), UID_SELF,
1997 &characteristics, &result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001998 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001999 ALOGE("Failed to get key characteristics");
2000 return;
2001 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002002 auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
2003 if (!algorithm.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002004 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
2005 return;
2006 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002007 params->push_back(TAG_ALGORITHM, algorithm.value());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002008}
2009
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002010KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
2011 const hidl_vec<uint8_t>& data,
2012 hidl_vec<uint8_t>* out,
2013 const hidl_vec<uint8_t>& signature,
2014 KeyPurpose purpose) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002015
2016 std::basic_stringstream<uint8_t> outBuffer;
2017 OperationResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002018 AuthorizationSet inArgs;
2019 addLegacyBeginParams(name, &inArgs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002020 sp<IBinder> appToken(new BBinder);
2021 sp<IBinder> token;
2022
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002023 begin(appToken, name, static_cast<int32_t>(purpose), true,
2024 KeymasterArguments(inArgs.hidl_data()), ::std::vector<uint8_t>(), UID_SELF, &result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002025 if (!result.resultCode.isOk()) {
2026 if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002027 ALOGW("Key not found");
2028 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002029 ALOGW("Error in begin: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002030 }
2031 return translateResultToLegacyResult(result.resultCode);
2032 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002033 inArgs.Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002034 token = result.token;
2035 size_t consumed = 0;
2036 size_t lastConsumed = 0;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002037 hidl_vec<uint8_t> data_view;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002038 do {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002039 data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002040 update(token, KeymasterArguments(inArgs.hidl_data()), data_view, &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002041 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002042 ALOGW("Error in update: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002043 return translateResultToLegacyResult(result.resultCode);
2044 }
2045 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002046 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002047 }
2048 lastConsumed = result.inputConsumed;
2049 consumed += lastConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002050 } while (consumed < data.size() && lastConsumed > 0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002051
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002052 if (consumed != data.size()) {
2053 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
2054 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002055 }
2056
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002057 finish(token, KeymasterArguments(inArgs.hidl_data()), signature, ::std::vector<uint8_t>(),
2058 &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002059 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002060 ALOGW("Error in finish: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002061 return translateResultToLegacyResult(result.resultCode);
2062 }
2063 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002064 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002065 }
2066
2067 if (out) {
2068 auto buf = outBuffer.str();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002069 out->resize(buf.size());
2070 memcpy(&(*out)[0], buf.data(), out->size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002071 }
2072
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002073 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002074}
2075
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002076KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
2077 const AuthorizationSet& params,
2078 Blob* blob) {
Shawn Willden98c59162016-03-20 09:10:18 -06002079 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
2080 String8 name8(name);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002081 KeyStoreServiceReturnCode responseCode =
2082 mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002083 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willden98c59162016-03-20 09:10:18 -06002084 return responseCode;
2085 }
Rubin Xu7675c9f2017-03-15 19:26:52 +00002086 ALOGI("upgradeKeyBlob %s %d", name8.string(), uid);
Shawn Willden98c59162016-03-20 09:10:18 -06002087
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002088 auto hidlKey = blob2hidlVec(*blob);
2089 auto& dev = mKeyStore->getDevice(*blob);
Shawn Willden98c59162016-03-20 09:10:18 -06002090
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002091 KeyStoreServiceReturnCode error;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002092 auto hidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& upgradedKeyBlob) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002093 error = ret;
2094 if (!error.isOk()) {
2095 return;
2096 }
2097
Janis Danisevskisaf7783f2017-09-21 11:29:47 -07002098 auto filename = mKeyStore->getBlobFileNameIfExists(name8, uid, ::TYPE_KEYMASTER_10);
2099 if (!filename.isOk()) {
2100 ALOGI("trying to upgrade a non existing blob");
2101 return;
2102 }
2103 error = mKeyStore->del(filename.value().string(), ::TYPE_ANY, get_user_id(uid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002104 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00002105 ALOGI("upgradeKeyBlob keystore->del failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002106 return;
2107 }
2108
2109 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
2110 0 /* infoLength */, ::TYPE_KEYMASTER_10);
2111 newBlob.setFallback(blob->isFallback());
2112 newBlob.setEncrypted(blob->isEncrypted());
Rubin Xu67899de2017-04-21 19:15:13 +01002113 newBlob.setSuperEncrypted(blob->isSuperEncrypted());
2114 newBlob.setCriticalToDeviceEncryption(blob->isCriticalToDeviceEncryption());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002115
Janis Danisevskisaf7783f2017-09-21 11:29:47 -07002116 error = mKeyStore->put(filename.value().string(), &newBlob, get_user_id(uid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002117 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00002118 ALOGI("upgradeKeyBlob keystore->put failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002119 return;
2120 }
2121
2122 // Re-read blob for caller. We can't use newBlob because writing it modified it.
2123 error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
2124 };
2125
2126 KeyStoreServiceReturnCode rc =
2127 KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
2128 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06002129 return rc;
2130 }
2131
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002132 return error;
Shawn Willden98c59162016-03-20 09:10:18 -06002133}
2134
Shawn Willdene2a7b522017-04-11 09:27:40 -06002135} // namespace keystore