blob: a61f7dce1a04a75b47f08c9586a61b42af4de864 [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 Danisevskis8f737ad2017-11-21 12:30:15 -080043#include <hardware/hw_auth_token.h>
44
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010045namespace keystore {
Shawn Willdend5a24e62017-02-28 13:53:24 -070046
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010047using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070048
Shawn Willdene2a7b522017-04-11 09:27:40 -060049namespace {
50
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070051using ::android::binder::Status;
52using ::android::hardware::keymaster::V3_0::KeyFormat;
53using android::security::KeystoreArg;
54using android::security::keymaster::ExportResult;
55using android::security::keymaster::KeymasterArguments;
56using android::security::keymaster::KeymasterBlob;
57using android::security::keymaster::KeymasterCertificateChain;
58using android::security::keymaster::OperationResult;
59
Shawn Willdene2a7b522017-04-11 09:27:40 -060060constexpr size_t kMaxOperations = 15;
61constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
62const char* kTimestampFilePath = "timestamp";
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070063
64struct BIGNUM_Delete {
65 void operator()(BIGNUM* p) const { BN_free(p); }
66};
Janis Danisevskisccfff102017-05-01 11:02:51 -070067typedef std::unique_ptr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070068
Shawn Willdene2a7b522017-04-11 09:27:40 -060069bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
70 return params.end() != std::find_if(params.begin(), params.end(),
71 [&](auto& param) { return param.tag == tag; });
72}
73
Shawn Willdend5a24e62017-02-28 13:53:24 -070074bool isAuthenticationBound(const hidl_vec<KeyParameter>& params) {
75 return !containsTag(params, Tag::NO_AUTH_REQUIRED);
76}
77
Shawn Willdene2a7b522017-04-11 09:27:40 -060078std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
79 struct stat sbuf;
80 if (stat(kTimestampFilePath, &sbuf) == 0) {
81 double diff_secs = difftime(time(NULL), sbuf.st_ctime);
82 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
83 }
84
85 if (errno != ENOENT) {
86 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
87 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
88 }
89
90 int fd = creat(kTimestampFilePath, 0600);
91 if (fd < 0) {
92 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
93 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
94 }
95
96 if (close(fd)) {
97 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
98 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
99 }
100
101 return {ResponseCode::NO_ERROR, true};
102}
103
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200104constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
105
106KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
107 KeyStoreServiceReturnCode responseCode;
108 bool factoryResetSinceIdRotation;
109 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
110
111 if (!responseCode.isOk()) return responseCode;
112 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
113
114 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
115 if (!asn1_attestation_id_result.isOk()) {
116 ALOGE("failed to gather attestation_id");
117 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
118 }
119 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
120
121 /*
122 * The attestation application ID cannot be longer than
123 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, so we truncate if too long.
124 */
125 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
126 asn1_attestation_id.resize(KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE);
127 }
128
129 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
130
131 return ResponseCode::NO_ERROR;
132}
133
Shawn Willdene2a7b522017-04-11 09:27:40 -0600134} // anonymous namespace
135
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700136void KeyStoreService::binderDied(const wp<IBinder>& who) {
137 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700138 for (const auto& token : operations) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700139 int32_t unused_result;
140 abort(token, &unused_result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700141 }
142}
143
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700144Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700145 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700146 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
147 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700148 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700149 *aidl_return = mKeyStore->getState(userId);
150 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700151}
152
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700153Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700154 uid_t targetUid = getEffectiveUid(uid);
155 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700156 // see keystore/keystore.h
157 return Status::fromServiceSpecificError(
158 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700159 }
160
161 String8 name8(name);
162 Blob keyBlob;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100163 KeyStoreServiceReturnCode rc =
164 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
165 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700166 *item = ::std::vector<uint8_t>();
167 // Return empty array if key is not found
168 // TODO: consider having returned value nullable or parse exception on the client.
169 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700170 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100171 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700172 // The static_cast here is needed to prevent a move, forcing a deep copy.
173 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
174 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700175}
176
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700177Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
178 int targetUid, int32_t flags, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700179 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700180 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700181 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100182 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700183 *aidl_return = static_cast<int32_t>(result);
184 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700185 }
186
187 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400188 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_GENERIC));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700189
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100190 Blob keyBlob(&item[0], item.size(), NULL, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700191 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
192
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700193 *aidl_return =
194 static_cast<int32_t>(mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid)));
195 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700196}
197
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700198Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700199 targetUid = getEffectiveUid(targetUid);
200 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700201 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
202 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700203 }
204 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000205 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700206 auto filename = mKeyStore->getBlobFileNameIfExists(name8, targetUid, ::TYPE_ANY);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700207 if (!filename.isOk()) {
208 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
209 return Status::ok();
210 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700211
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700212 ResponseCode result =
213 mKeyStore->del(filename.value().string(), ::TYPE_ANY, get_user_id(targetUid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100214 if (result != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700215 *aidl_return = static_cast<int32_t>(result);
216 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400217 }
218
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700219 filename = mKeyStore->getBlobFileNameIfExists(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS);
220 if (filename.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700221 *aidl_return = static_cast<int32_t>(mKeyStore->del(
222 filename.value().string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid)));
223 return Status::ok();
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700224 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700225 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
226 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700227}
228
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700229Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700230 targetUid = getEffectiveUid(targetUid);
231 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700232 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
233 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700234 }
235
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700236 auto filename = mKeyStore->getBlobFileNameIfExists(String8(name), targetUid, ::TYPE_ANY);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700237 *aidl_return = static_cast<int32_t>(filename.isOk() ? ResponseCode::NO_ERROR
238 : ResponseCode::KEY_NOT_FOUND);
239 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700240}
241
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700242Status KeyStoreService::list(const String16& prefix, int targetUid,
243 ::std::vector<::android::String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700244 targetUid = getEffectiveUid(targetUid);
245 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700246 return Status::fromServiceSpecificError(
247 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700248 }
249 const String8 prefix8(prefix);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400250 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid, TYPE_ANY));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700251 android::Vector<android::String16> matches_internal;
252 if (mKeyStore->list(filename, &matches_internal, get_user_id(targetUid)) !=
253 ResponseCode::NO_ERROR) {
254 return Status::fromServiceSpecificError(static_cast<int32_t>(ResponseCode::SYSTEM_ERROR));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700255 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700256 matches->clear();
257 for (size_t i = 0; i < matches_internal.size(); ++i) {
258 matches->push_back(matches_internal[i]);
259 }
260 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700261}
262
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700263Status KeyStoreService::reset(int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700264 if (!checkBinderPermission(P_RESET)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700265 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
266 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700267 }
268
269 uid_t callingUid = IPCThreadState::self()->getCallingUid();
270 mKeyStore->resetUser(get_user_id(callingUid), false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700271 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
272 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700273}
274
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700275Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
276 int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700277 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700278 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
279 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700280 }
281
282 const String8 password8(password);
283 // Flush the auth token table to prevent stale tokens from sticking
284 // around.
285 mAuthTokenTable.Clear();
286
287 if (password.size() == 0) {
288 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
289 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700290 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
291 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700292 } else {
293 switch (mKeyStore->getState(userId)) {
294 case ::STATE_UNINITIALIZED: {
295 // generate master key, encrypt with password, write to file,
296 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700297 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
298 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700299 }
300 case ::STATE_NO_ERROR: {
301 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700302 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
303 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700304 }
305 case ::STATE_LOCKED: {
306 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
307 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700308 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
309 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700310 }
311 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700312 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
313 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700314 }
315}
316
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700317Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700318 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700319 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
320 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700321 }
322
323 // Sanity check that the new user has an empty keystore.
324 if (!mKeyStore->isEmpty(userId)) {
325 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
326 }
327 // Unconditionally clear the keystore, just to be safe.
328 mKeyStore->resetUser(userId, false);
329 if (parentId != -1) {
330 // This profile must share the same master key password as the parent profile. Because the
331 // password of the parent profile is not known here, the best we can do is copy the parent's
332 // master key and master key file. This makes this profile use the same master key as the
333 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700334 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
335 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700336 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700337 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
338 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700339 }
340}
341
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700342Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700343 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700344 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
345 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700346 }
347
348 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700349 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
350 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700351}
352
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700353Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700354 if (!checkBinderPermission(P_LOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700355 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
356 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700357 }
358
359 State state = mKeyStore->getState(userId);
360 if (state != ::STATE_NO_ERROR) {
361 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700362 *aidl_return = static_cast<int32_t>(ResponseCode(state));
363 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700364 }
365
366 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700367 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
368 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700369}
370
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700371Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700372 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700373 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
374 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700375 }
376
377 State state = mKeyStore->getState(userId);
378 if (state != ::STATE_LOCKED) {
379 switch (state) {
380 case ::STATE_NO_ERROR:
381 ALOGI("calling unlock when already unlocked, ignoring.");
382 break;
383 case ::STATE_UNINITIALIZED:
384 ALOGE("unlock called on uninitialized keystore.");
385 break;
386 default:
387 ALOGE("unlock called on keystore in unknown state: %d", state);
388 break;
389 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700390 *aidl_return = static_cast<int32_t>(ResponseCode(state));
391 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700392 }
393
394 const String8 password8(pw);
395 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700396 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
397 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700398}
399
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700400Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700401 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700402 *aidl_return = static_cast<int32_t>(false);
403 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700404 }
405
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700406 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
407 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700408}
409
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700410Status KeyStoreService::generate(const String16& name, int32_t targetUid, int32_t keyType,
411 int32_t keySize, int32_t flags,
412 const ::android::security::KeystoreArguments& keystoreArgs,
413 int32_t* aidl_return) {
414 const Vector<sp<KeystoreArg>>* args = &(keystoreArgs.getArguments());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700415 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700416 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700417 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100418 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700419 *aidl_return = static_cast<int32_t>(result);
420 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700421 }
422
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100423 keystore::AuthorizationSet params;
424 add_legacy_key_authorizations(keyType, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700425
426 switch (keyType) {
427 case EVP_PKEY_EC: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100428 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700429 if (keySize == -1) {
430 keySize = EC_DEFAULT_KEY_SIZE;
431 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
432 ALOGI("invalid key size %d", keySize);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700433 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
434 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700435 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100436 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700437 break;
438 }
439 case EVP_PKEY_RSA: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100440 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700441 if (keySize == -1) {
442 keySize = RSA_DEFAULT_KEY_SIZE;
443 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
444 ALOGI("invalid key size %d", keySize);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700445 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
446 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700447 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100448 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700449 unsigned long exponent = RSA_DEFAULT_EXPONENT;
450 if (args->size() > 1) {
451 ALOGI("invalid number of arguments: %zu", args->size());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700452 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
453 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700454 } else if (args->size() == 1) {
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700455 const sp<KeystoreArg>& expArg = args->itemAt(0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700456 if (expArg != NULL) {
457 Unique_BIGNUM pubExpBn(BN_bin2bn(
458 reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
459 if (pubExpBn.get() == NULL) {
460 ALOGI("Could not convert public exponent to BN");
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700461 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
462 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700463 }
464 exponent = BN_get_word(pubExpBn.get());
465 if (exponent == 0xFFFFFFFFL) {
466 ALOGW("cannot represent public exponent as a long value");
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700467 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
468 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700469 }
470 } else {
471 ALOGW("public exponent not read");
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700472 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
473 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700474 }
475 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100476 params.push_back(TAG_RSA_PUBLIC_EXPONENT, exponent);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700477 break;
478 }
479 default: {
480 ALOGW("Unsupported key type %d", keyType);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700481 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
482 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700483 }
484 }
485
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700486 int32_t aidl_result;
487 android::security::keymaster::KeyCharacteristics unused_characteristics;
488 auto rc = generateKey(name, KeymasterArguments(params.hidl_data()), ::std::vector<uint8_t>(),
489 targetUid, flags, &unused_characteristics, &aidl_result);
490 if (!KeyStoreServiceReturnCode(aidl_result).isOk()) {
491 ALOGW("generate failed: %d", int32_t(aidl_result));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700492 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700493 *aidl_return = aidl_result;
494 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700495}
496
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700497Status KeyStoreService::import_key(const String16& name, const ::std::vector<uint8_t>& data,
498 int targetUid, int32_t flags, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700499
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100500 const uint8_t* ptr = &data[0];
501
502 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, data.size()));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700503 if (!pkcs8.get()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700504 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
505 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700506 }
507 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
508 if (!pkey.get()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700509 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
510 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700511 }
512 int type = EVP_PKEY_type(pkey->type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100513 AuthorizationSet params;
514 add_legacy_key_authorizations(type, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700515 switch (type) {
516 case EVP_PKEY_RSA:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100517 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700518 break;
519 case EVP_PKEY_EC:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100520 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700521 break;
522 default:
523 ALOGW("Unsupported key type %d", type);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700524 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
525 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700526 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100527
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700528 int import_result;
529 auto rc = importKey(name, KeymasterArguments(params.hidl_data()),
530 static_cast<int32_t>(KeyFormat::PKCS8), data, targetUid, flags,
531 /*outCharacteristics*/ NULL, &import_result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100532
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700533 if (!KeyStoreServiceReturnCode(import_result).isOk()) {
534 ALOGW("importKey failed: %d", int32_t(import_result));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700535 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700536 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
537 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700538}
539
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700540Status KeyStoreService::sign(const String16& name, const ::std::vector<uint8_t>& data,
541 ::std::vector<uint8_t>* out) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700542 if (!checkBinderPermission(P_SIGN)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700543 return Status::fromServiceSpecificError(
544 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700545 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700546 hidl_vec<uint8_t> legacy_out;
547 KeyStoreServiceReturnCode res =
548 doLegacySignVerify(name, data, &legacy_out, hidl_vec<uint8_t>(), KeyPurpose::SIGN);
549 *out = legacy_out;
550 return Status::fromServiceSpecificError((res));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700551}
552
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700553Status KeyStoreService::verify(const String16& name, const ::std::vector<uint8_t>& data,
554 const ::std::vector<uint8_t>& signature, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700555 if (!checkBinderPermission(P_VERIFY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700556 return Status::fromServiceSpecificError(
557 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700558 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700559 *aidl_return = static_cast<int32_t>(
560 doLegacySignVerify(name, data, nullptr, signature, KeyPurpose::VERIFY));
561 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700562}
563
564/*
565 * TODO: The abstraction between things stored in hardware and regular blobs
566 * of data stored on the filesystem should be moved down to keystore itself.
567 * Unfortunately the Java code that calls this has naming conventions that it
568 * knows about. Ideally keystore shouldn't be used to store random blobs of
569 * data.
570 *
571 * Until that happens, it's necessary to have a separate "get_pubkey" and
572 * "del_key" since the Java code doesn't really communicate what it's
573 * intentions are.
574 */
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700575Status KeyStoreService::get_pubkey(const String16& name, ::std::vector<uint8_t>* pubKey) {
576 android::security::keymaster::ExportResult result;
577 KeymasterBlob clientId;
578 KeymasterBlob appId;
579 exportKey(name, static_cast<int32_t>(KeyFormat::X509), clientId, appId, UID_SELF, &result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100580 if (!result.resultCode.isOk()) {
581 ALOGW("export failed: %d", int32_t(result.resultCode));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700582 return Status::fromServiceSpecificError(static_cast<int32_t>(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700583 }
584
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100585 if (pubKey) *pubKey = std::move(result.exportData);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700586 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700587}
588
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700589Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
590 ::android::String16* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700591 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100592 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
593 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700594 *aidl_return = String16();
595 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700596 }
597
598 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400599 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700600
601 if (access(filename.string(), R_OK) == -1) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700602 *aidl_return = String16();
603 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700604 }
605
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700606 *aidl_return =
607 String16(mKeyStore->addGrant(String8(name).string(), callingUid, granteeUid).c_str());
608 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700609}
610
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700611Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700612 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700613 KeyStoreServiceReturnCode result = checkBinderPermissionAndKeystoreState(P_GRANT);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100614 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700615 *aidl_return = static_cast<int32_t>(result);
616 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700617 }
618
619 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400620 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700621
622 if (access(filename.string(), R_OK) == -1) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700623 *aidl_return = static_cast<int32_t>((errno != ENOENT) ? ResponseCode::SYSTEM_ERROR
624 : ResponseCode::KEY_NOT_FOUND);
625 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700626 }
627
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700628 *aidl_return = static_cast<int32_t>(mKeyStore->removeGrant(name8, callingUid, granteeUid)
629 ? ResponseCode::NO_ERROR
630 : ResponseCode::KEY_NOT_FOUND);
631 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700632}
633
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700634Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700635 uid_t targetUid = getEffectiveUid(uid);
636 if (!checkBinderPermission(P_GET, targetUid)) {
637 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700638 *time = -1L;
639 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700640 }
641
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700642 auto filename = mKeyStore->getBlobFileNameIfExists(String8(name), targetUid, ::TYPE_ANY);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700643
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700644 if (!filename.isOk()) {
645 ALOGW("could not access %s for getmtime", filename.value().string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700646 *time = -1L;
647 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700648 }
649
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700650 int fd = TEMP_FAILURE_RETRY(open(filename.value().string(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700651 if (fd < 0) {
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700652 ALOGW("could not open %s for getmtime", filename.value().string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700653 *time = -1L;
654 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700655 }
656
657 struct stat s;
658 int ret = fstat(fd, &s);
659 close(fd);
660 if (ret == -1) {
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700661 ALOGW("could not stat %s for getmtime", filename.value().string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700662 *time = -1L;
663 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700664 }
665
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700666 *time = static_cast<int64_t>(s.st_mtime);
667 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700668}
669
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400670// TODO(tuckeris): This is dead code, remove it. Don't bother copying over key characteristics here
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700671Status KeyStoreService::duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
672 int32_t destUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700673 uid_t callingUid = IPCThreadState::self()->getCallingUid();
674 pid_t spid = IPCThreadState::self()->getCallingPid();
675 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
676 ALOGW("permission denied for %d: duplicate", callingUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700677 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
678 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700679 }
680
681 State state = mKeyStore->getState(get_user_id(callingUid));
682 if (!isKeystoreUnlocked(state)) {
683 ALOGD("calling duplicate in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700684 *aidl_return = static_cast<int32_t>(ResponseCode(state));
685 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700686 }
687
688 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
689 srcUid = callingUid;
690 } else if (!is_granted_to(callingUid, srcUid)) {
691 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700692 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
693 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700694 }
695
696 if (destUid == -1) {
697 destUid = callingUid;
698 }
699
700 if (srcUid != destUid) {
701 if (static_cast<uid_t>(srcUid) != callingUid) {
702 ALOGD("can only duplicate from caller to other or to same uid: "
703 "calling=%d, srcUid=%d, destUid=%d",
704 callingUid, srcUid, destUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700705 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
706 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700707 }
708
709 if (!is_granted_to(callingUid, destUid)) {
710 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700711 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
712 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700713 }
714 }
715
716 String8 source8(srcKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400717 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700718
719 String8 target8(destKey);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400720 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700721
722 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
723 ALOGD("destination already exists: %s", targetFile.string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700724 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
725 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700726 }
727
728 Blob keyBlob;
729 ResponseCode responseCode =
730 mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY, get_user_id(srcUid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100731 if (responseCode != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700732 *aidl_return = static_cast<int32_t>(responseCode);
733 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700734 }
735
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700736 *aidl_return =
737 static_cast<int32_t>(mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid)));
738 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700739}
740
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700741Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
742 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
743 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700744}
745
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700746Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700747 uid_t targetUid = getEffectiveUid(targetUid64);
748 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700749 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
750 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700751 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000752 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700753
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700754 mKeyStore->removeAllGrantsToUid(targetUid);
755
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700756 String8 prefix = String8::format("%u_", targetUid);
757 Vector<String16> aliases;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100758 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700759 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
760 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700761 }
762
763 for (uint32_t i = 0; i < aliases.size(); i++) {
764 String8 name8(aliases[i]);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400765 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Rubin Xu85c85e92017-04-26 20:07:30 +0100766
767 if (get_app_id(targetUid) == AID_SYSTEM) {
768 Blob keyBlob;
769 ResponseCode responseCode =
770 mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, get_user_id(targetUid));
771 if (responseCode == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
772 // Do not clear keys critical to device encryption under system uid.
773 continue;
774 }
775 }
776
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700777 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400778
779 // del() will fail silently if no cached characteristics are present for this alias.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100780 String8 chr_filename(
781 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400782 mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700783 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700784 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
785 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700786}
787
Janis Danisevskisc1460142017-12-18 16:48:46 -0800788Status KeyStoreService::addRngEntropy(const ::std::vector<uint8_t>& entropy, int32_t flags,
789 int32_t* aidl_return) {
790 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
791 if (!device) {
792 *aidl_return = static_cast<int32_t>(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
793 } else {
794 *aidl_return = static_cast<int32_t>(
795 KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device->addRngEntropy(entropy))));
796 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700797 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700798}
799
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700800Status
801KeyStoreService::generateKey(const String16& name, const KeymasterArguments& params,
802 const ::std::vector<uint8_t>& entropy, int uid, int flags,
803 android::security::keymaster::KeyCharacteristics* outCharacteristics,
804 int32_t* aidl_return) {
Max Biresef4f0672017-11-29 14:38:48 -0800805 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
806 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700807 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100808 KeyStoreServiceReturnCode rc =
809 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
810 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700811 *aidl_return = static_cast<int32_t>(rc);
812 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700813 }
Rubin Xu67899de2017-04-21 19:15:13 +0100814 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
815 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700816 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
817 return Status::ok();
Rubin Xu67899de2017-04-21 19:15:13 +0100818 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700819
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700820 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700821 // TODO(jbires): remove uid checking upon implementation of b/25646100
Max Bires670467d2017-12-12 11:16:43 -0800822 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Biresef4f0672017-11-29 14:38:48 -0800823 originalUid != IPCThreadState::self()->getCallingUid()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700824 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
825 return Status::ok();
826 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600827 }
828
Janis Danisevskisc1460142017-12-18 16:48:46 -0800829 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
830 auto dev = mKeyStore->getDevice(securityLevel);
831 if (!dev) {
832 *aidl_return = static_cast<int32_t>(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
833 return Status::ok();
834 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700835 AuthorizationSet keyCharacteristics = params.getParameters();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400836
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700837 // TODO: Seed from Linux RNG before this.
Janis Danisevskisc1460142017-12-18 16:48:46 -0800838 rc = KS_HANDLE_HIDL_ERROR(dev->addRngEntropy(entropy));
839 if (!rc.isOk()) {
840 *aidl_return = static_cast<int32_t>(rc);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700841 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700842 }
843
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100844 KeyStoreServiceReturnCode error;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700845 auto hidl_cb = [&](ErrorCode ret, const ::std::vector<uint8_t>& hidlKeyBlob,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100846 const KeyCharacteristics& keyCharacteristics) {
847 error = ret;
848 if (!error.isOk()) {
849 return;
850 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700851 if (outCharacteristics)
852 *outCharacteristics =
853 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700854
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100855 // Write the key
856 String8 name8(name);
857 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700858
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100859 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800860 keyBlob.setSecurityLevel(securityLevel);
Rubin Xu67899de2017-04-21 19:15:13 +0100861 keyBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700862 if (isAuthenticationBound(params.getParameters()) &&
863 !keyBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -0700864 keyBlob.setSuperEncrypted(true);
865 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100866 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700867
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100868 error = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
869 };
870
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700871 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(params.getParameters(), hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100872 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700873 *aidl_return = static_cast<int32_t>(rc);
874 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400875 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100876 if (!error.isOk()) {
877 ALOGE("Failed to generate key -> falling back to software keymaster");
Janis Danisevskisc1460142017-12-18 16:48:46 -0800878 securityLevel = SecurityLevel::SOFTWARE;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000879 auto fallback = mKeyStore->getFallbackDevice();
Janis Danisevskisc1460142017-12-18 16:48:46 -0800880 if (!fallback) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700881 *aidl_return = static_cast<int32_t>(error);
882 return Status::ok();
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000883 }
Janis Danisevskisc1460142017-12-18 16:48:46 -0800884 rc = KS_HANDLE_HIDL_ERROR(fallback->generateKey(params.getParameters(), hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100885 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700886 *aidl_return = static_cast<int32_t>(rc);
887 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100888 }
889 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700890 *aidl_return = static_cast<int32_t>(error);
891 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100892 }
893 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400894
895 // Write the characteristics:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100896 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400897 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
898
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100899 std::stringstream kc_stream;
900 keyCharacteristics.Serialize(&kc_stream);
901 if (kc_stream.bad()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700902 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
903 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100904 }
905 auto kc_buf = kc_stream.str();
906 Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
907 ::TYPE_KEY_CHARACTERISTICS);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800908 charBlob.setSecurityLevel(securityLevel);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400909 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
910
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700911 *aidl_return =
912 static_cast<int32_t>(mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid)));
913 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700914}
915
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700916Status KeyStoreService::getKeyCharacteristics(
917 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
918 const ::android::security::keymaster::KeymasterBlob& appId, int32_t uid,
919 ::android::security::keymaster::KeyCharacteristics* outCharacteristics, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700920 if (!outCharacteristics) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700921 *aidl_return =
922 static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::UNEXPECTED_NULL_POINTER));
923 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700924 }
925
926 uid_t targetUid = getEffectiveUid(uid);
927 uid_t callingUid = IPCThreadState::self()->getCallingUid();
928 if (!is_granted_to(callingUid, targetUid)) {
929 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
930 targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700931 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
932 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700933 }
934
935 Blob keyBlob;
936 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700937
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100938 KeyStoreServiceReturnCode rc =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700939 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskisd714a672017-09-01 14:31:36 -0700940 if (rc == ResponseCode::UNINITIALIZED) {
941 /*
942 * If we fail reading the blob because the master key is missing we try to retrieve the
943 * key characteristics from the characteristics file. This happens when auth-bound
944 * keys are used after a screen lock has been removed by the user.
945 */
946 rc = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
947 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700948 *aidl_return = static_cast<int32_t>(rc);
949 return Status::ok();
Janis Danisevskisd714a672017-09-01 14:31:36 -0700950 }
951 AuthorizationSet keyCharacteristics;
952 // TODO write one shot stream buffer to avoid copying (twice here)
953 std::string charBuffer(reinterpret_cast<const char*>(keyBlob.getValue()),
954 keyBlob.getLength());
955 std::stringstream charStream(charBuffer);
956 keyCharacteristics.Deserialize(&charStream);
957
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700958 outCharacteristics->softwareEnforced = KeymasterArguments(keyCharacteristics.hidl_data());
959 *aidl_return = static_cast<int32_t>(rc);
960 return Status::ok();
Janis Danisevskisd714a672017-09-01 14:31:36 -0700961 } else if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700962 *aidl_return = static_cast<int32_t>(rc);
963 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700964 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100965
966 auto hidlKeyBlob = blob2hidlVec(keyBlob);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800967 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100968
969 KeyStoreServiceReturnCode error;
970
971 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
972 error = ret;
973 if (!error.isOk()) {
974 return;
Shawn Willden98c59162016-03-20 09:10:18 -0600975 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700976 *outCharacteristics =
977 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100978 };
979
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700980 rc = KS_HANDLE_HIDL_ERROR(
981 dev->getKeyCharacteristics(hidlKeyBlob, clientId.getData(), appId.getData(), hidlCb));
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();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100985 }
986
987 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
988 AuthorizationSet upgradeParams;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700989 if (clientId.getData().size()) {
990 upgradeParams.push_back(TAG_APPLICATION_ID, clientId.getData());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100991 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700992 if (appId.getData().size()) {
993 upgradeParams.push_back(TAG_APPLICATION_DATA, appId.getData());
Shawn Willden98c59162016-03-20 09:10:18 -0600994 }
995 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100996 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700997 *aidl_return = static_cast<int32_t>(rc);
998 return Status::ok();
Shawn Willden98c59162016-03-20 09:10:18 -0600999 }
Shawn Willden715d0232016-01-21 00:45:13 -07001000
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001001 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
1002
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001003 rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(
1004 upgradedHidlKeyBlob, clientId.getData(), appId.getData(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001005 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001006 *aidl_return = static_cast<int32_t>(rc);
1007 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001008 }
1009 // Note that, on success, "error" will have been updated by the hidlCB callback.
1010 // So it is fine to return "error" below.
1011 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001012 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(error));
1013 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001014}
1015
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001016Status
1017KeyStoreService::importKey(const String16& name, const KeymasterArguments& params, int32_t format,
1018 const ::std::vector<uint8_t>& keyData, int uid, int flags,
1019 ::android::security::keymaster::KeyCharacteristics* outCharacteristics,
1020 int32_t* aidl_return) {
1021
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001022 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001023 KeyStoreServiceReturnCode rc =
1024 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
1025 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001026 *aidl_return = static_cast<int32_t>(rc);
1027 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001028 }
Rubin Xu67899de2017-04-21 19:15:13 +01001029 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
1030 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001031 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
1032 return Status::ok();
Rubin Xu67899de2017-04-21 19:15:13 +01001033 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001034
Janis Danisevskisc1460142017-12-18 16:48:46 -08001035 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
1036 auto dev = mKeyStore->getDevice(securityLevel);
1037 if (!dev) {
1038 *aidl_return = static_cast<int32_t>(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1039 return Status::ok();
1040 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001041
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001042 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001043
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001044 KeyStoreServiceReturnCode error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001045
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001046 auto hidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& keyBlob,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001047 const KeyCharacteristics& keyCharacteristics) {
1048 error = ret;
1049 if (!error.isOk()) {
1050 return;
1051 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001052 if (outCharacteristics)
1053 *outCharacteristics =
1054 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001055
1056 // Write the key:
1057 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1058
1059 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001060 ksBlob.setSecurityLevel(securityLevel);
Rubin Xu67899de2017-04-21 19:15:13 +01001061 ksBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001062 if (isAuthenticationBound(params.getParameters()) &&
1063 !ksBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -07001064 ksBlob.setSuperEncrypted(true);
1065 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001066 ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1067
1068 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
1069 };
1070
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001071 rc = KS_HANDLE_HIDL_ERROR(
1072 dev->importKey(params.getParameters(), KeyFormat(format), keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001073 // possible hidl error
1074 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001075 *aidl_return = static_cast<int32_t>(rc);
1076 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001077 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001078 // now check error from callback
1079 if (!error.isOk()) {
1080 ALOGE("Failed to import key -> falling back to software keymaster");
Janis Danisevskisc1460142017-12-18 16:48:46 -08001081 securityLevel = SecurityLevel::SOFTWARE;
Janis Danisevskise8ba1802017-01-30 10:49:51 +00001082 auto fallback = mKeyStore->getFallbackDevice();
Janis Danisevskisc1460142017-12-18 16:48:46 -08001083 if (!fallback) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001084 *aidl_return = static_cast<int32_t>(error);
1085 return Status::ok();
Janis Danisevskise8ba1802017-01-30 10:49:51 +00001086 }
Janis Danisevskisc1460142017-12-18 16:48:46 -08001087 rc = KS_HANDLE_HIDL_ERROR(
1088 fallback->importKey(params.getParameters(), KeyFormat(format), keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001089 // possible hidl error
1090 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001091 *aidl_return = static_cast<int32_t>(rc);
1092 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001093 }
1094 // now check error from callback
1095 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001096 *aidl_return = static_cast<int32_t>(error);
1097 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001098 }
1099 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001100
1101 // Write the characteristics:
1102 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
1103
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001104 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001105 std::stringstream kcStream;
1106 opParams.Serialize(&kcStream);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001107 if (kcStream.bad()) {
1108 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
1109 return Status::ok();
1110 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001111 auto kcBuf = kcStream.str();
1112
1113 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
1114 ::TYPE_KEY_CHARACTERISTICS);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001115 charBlob.setSecurityLevel(securityLevel);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001116 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1117
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001118 *aidl_return =
1119 static_cast<int32_t>(mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid)));
1120
1121 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001122}
1123
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001124Status KeyStoreService::exportKey(const String16& name, int32_t format,
1125 const ::android::security::keymaster::KeymasterBlob& clientId,
1126 const ::android::security::keymaster::KeymasterBlob& appId,
1127 int32_t uid, ExportResult* result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001128
1129 uid_t targetUid = getEffectiveUid(uid);
1130 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1131 if (!is_granted_to(callingUid, targetUid)) {
1132 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001133 result->resultCode = ResponseCode::PERMISSION_DENIED;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001134 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001135 }
1136
1137 Blob keyBlob;
1138 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001139
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001140 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
1141 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001142 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001143 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001144
1145 auto key = blob2hidlVec(keyBlob);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001146 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001147
1148 auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
1149 result->resultCode = ret;
1150 if (!result->resultCode.isOk()) {
Ji Wang2c142312016-10-14 17:21:10 +08001151 return;
1152 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001153 result->exportData = keyMaterial;
1154 };
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001155 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
1156 dev->exportKey(KeyFormat(format), key, clientId.getData(), appId.getData(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001157 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
1158 // callback hidlCb.
1159 if (!rc.isOk()) {
1160 result->resultCode = rc;
Ji Wang2c142312016-10-14 17:21:10 +08001161 }
1162
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001163 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1164 AuthorizationSet upgradeParams;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001165 if (clientId.getData().size()) {
1166 upgradeParams.push_back(TAG_APPLICATION_ID, clientId.getData());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001167 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001168 if (appId.getData().size()) {
1169 upgradeParams.push_back(TAG_APPLICATION_DATA, appId.getData());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001170 }
1171 result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
1172 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001173 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001174 }
1175
1176 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
1177
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001178 result->resultCode = KS_HANDLE_HIDL_ERROR(dev->exportKey(
1179 KeyFormat(format), upgradedHidlKeyBlob, clientId.getData(), appId.getData(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001180 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001181 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001182 }
1183 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001184 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001185}
1186
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001187Status KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, int32_t purpose,
1188 bool pruneable, const KeymasterArguments& params,
1189 const ::std::vector<uint8_t>& entropy, int32_t uid,
1190 OperationResult* result) {
Shawn Willden0329a822017-12-04 13:55:14 -07001191 auto keyPurpose = static_cast<KeyPurpose>(purpose);
1192
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001193 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1194 uid_t targetUid = getEffectiveUid(uid);
1195 if (!is_granted_to(callingUid, targetUid)) {
1196 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001197 result->resultCode = ResponseCode::PERMISSION_DENIED;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001198 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001199 }
1200 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
1201 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001202 result->resultCode = ResponseCode::PERMISSION_DENIED;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001203 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001204 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001205 if (!checkAllowedOperationParams(params.getParameters())) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001206 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001207 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001208 }
Shawn Willden0329a822017-12-04 13:55:14 -07001209
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001210 Blob keyBlob;
1211 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001212 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Shawn Willdend5a24e62017-02-28 13:53:24 -07001213 if (result->resultCode == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
1214 result->resultCode = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1215 }
Shawn Willden0329a822017-12-04 13:55:14 -07001216 if (!result->resultCode.isOk()) return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001217
1218 auto key = blob2hidlVec(keyBlob);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001219 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001220 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001221 KeyCharacteristics characteristics;
1222 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
1223
1224 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1225 result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
1226 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001227 return Status::ok();
Shawn Willden98c59162016-03-20 09:10:18 -06001228 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001229 key = blob2hidlVec(keyBlob);
1230 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
Shawn Willden98c59162016-03-20 09:10:18 -06001231 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001232 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001233 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001234 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001235
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001236 // Merge these characteristics with the ones cached when the key was generated or imported
1237 Blob charBlob;
1238 AuthorizationSet persistedCharacteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001239 result->resultCode =
1240 mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
1241 if (result->resultCode.isOk()) {
1242 // TODO write one shot stream buffer to avoid copying (twice here)
1243 std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
1244 charBlob.getLength());
1245 std::stringstream charStream(charBuffer);
1246 persistedCharacteristics.Deserialize(&charStream);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001247 } else {
1248 ALOGD("Unable to read cached characteristics for key");
1249 }
1250
1251 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001252 AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
Shawn Willden0329a822017-12-04 13:55:14 -07001253 AuthorizationSet hardwareEnforced = characteristics.hardwareEnforced;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001254 persistedCharacteristics.Union(softwareEnforced);
Shawn Willden0329a822017-12-04 13:55:14 -07001255 persistedCharacteristics.Subtract(hardwareEnforced);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001256 characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001257
Shawn Willden0329a822017-12-04 13:55:14 -07001258 KeyStoreServiceReturnCode authResult;
1259 HardwareAuthToken authToken;
1260 std::tie(authResult, authToken) =
1261 getAuthToken(characteristics, 0 /* no challenge */, keyPurpose,
1262 /*failOnTokenMissing*/ false);
1263
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001264 // If per-operation auth is needed we need to begin the operation and
1265 // the client will need to authorize that operation before calling
1266 // update. Any other auth issues stop here.
Shawn Willden827243a2017-09-12 05:41:33 -06001267 if (!authResult.isOk() && authResult != ResponseCode::OP_AUTH_NEEDED) {
1268 result->resultCode = authResult;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001269 return Status::ok();
Shawn Willden827243a2017-09-12 05:41:33 -06001270 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001271
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001272 // Add entropy to the device first.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001273 if (entropy.size()) {
Janis Danisevskisc1460142017-12-18 16:48:46 -08001274 result->resultCode = KS_HANDLE_HIDL_ERROR(dev->addRngEntropy(entropy));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001275 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001276 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001277 }
1278 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001279
1280 // Create a keyid for this key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001281 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001282 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
1283 ALOGE("Failed to create a key ID for authorization checking.");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001284 result->resultCode = ErrorCode::UNKNOWN_ERROR;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001285 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001286 }
1287
1288 // Check that all key authorization policy requirements are met.
Shawn Willden0329a822017-12-04 13:55:14 -07001289 AuthorizationSet key_auths = characteristics.hardwareEnforced;
1290 key_auths.append(characteristics.softwareEnforced.begin(),
1291 characteristics.softwareEnforced.end());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001292
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001293 result->resultCode =
Shawn Willden0329a822017-12-04 13:55:14 -07001294 enforcement_policy.AuthorizeOperation(keyPurpose, keyid, key_auths, opParams, authToken,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001295 0 /* op_handle */, true /* is_begin_operation */);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001296 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001297 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001298 }
1299
Shawn Willdene2a7b522017-04-11 09:27:40 -06001300 // If there are more than kMaxOperations, abort the oldest operation that was started as
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001301 // pruneable.
Shawn Willdene2a7b522017-04-11 09:27:40 -06001302 while (mOperationMap.getOperationCount() >= kMaxOperations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001303 ALOGD("Reached or exceeded concurrent operations limit");
1304 if (!pruneOperation()) {
1305 break;
1306 }
1307 }
1308
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001309 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1310 uint64_t operationHandle) {
1311 result->resultCode = ret;
1312 if (!result->resultCode.isOk()) {
1313 return;
1314 }
1315 result->handle = operationHandle;
1316 result->outParams = outParams;
1317 };
1318
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001319 ErrorCode rc =
Shawn Willden0329a822017-12-04 13:55:14 -07001320 KS_HANDLE_HIDL_ERROR(dev->begin(keyPurpose, key, opParams.hidl_data(), authToken, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001321 if (rc != ErrorCode::OK) {
1322 ALOGW("Got error %d from begin()", rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001323 }
1324
1325 // If there are too many operations abort the oldest operation that was
1326 // started as pruneable and try again.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001327 while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1328 ALOGW("Ran out of operation handles");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001329 if (!pruneOperation()) {
1330 break;
1331 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001332 rc = KS_HANDLE_HIDL_ERROR(
Shawn Willden0329a822017-12-04 13:55:14 -07001333 dev->begin(keyPurpose, key, opParams.hidl_data(), authToken, hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001334 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001335 if (rc != ErrorCode::OK) {
1336 result->resultCode = rc;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001337 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001338 }
1339
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001340 // Note: The operation map takes possession of the contents of "characteristics".
1341 // It is safe to use characteristics after the following line but it will be empty.
Shawn Willden0329a822017-12-04 13:55:14 -07001342 sp<IBinder> operationToken = mOperationMap.addOperation(
1343 result->handle, keyid, keyPurpose, dev, appToken, std::move(characteristics), pruneable);
1344 assert(characteristics.hardwareEnforced.size() == 0);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001345 assert(characteristics.softwareEnforced.size() == 0);
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001346 result->token = operationToken;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001347
Shawn Willden0329a822017-12-04 13:55:14 -07001348 mOperationMap.setOperationAuthToken(operationToken, std::move(authToken));
1349
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001350 // Return the authentication lookup result. If this is a per operation
1351 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1352 // application should get an auth token using the handle before the
1353 // first call to update, which will fail if keystore hasn't received the
1354 // auth token.
Shawn Willden2f96c792017-09-07 23:59:08 -06001355 if (result->resultCode == ErrorCode::OK) {
1356 result->resultCode = authResult;
1357 }
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001358
1359 // Other result fields were set in the begin operation's callback.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001360 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001361}
1362
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001363Status KeyStoreService::update(const sp<IBinder>& token, const KeymasterArguments& params,
1364 const ::std::vector<uint8_t>& data, OperationResult* result) {
1365 if (!checkAllowedOperationParams(params.getParameters())) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001366 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001367 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001368 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001369
1370 auto getOpResult = mOperationMap.getOperation(token);
1371 if (!getOpResult.isOk()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001372 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001373 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001374 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001375 const auto& op = getOpResult.value();
1376
Shawn Willden0329a822017-12-04 13:55:14 -07001377 HardwareAuthToken authToken;
1378 std::tie(result->resultCode, authToken) = getOperationAuthTokenIfNeeded(token);
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001379 if (!result->resultCode.isOk()) return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001380
1381 // Check that all key authorization policy requirements are met.
Shawn Willden0329a822017-12-04 13:55:14 -07001382 AuthorizationSet key_auths(op.characteristics.hardwareEnforced);
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001383 key_auths.append(op.characteristics.softwareEnforced.begin(),
1384 op.characteristics.softwareEnforced.end());
1385
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001386 result->resultCode = enforcement_policy.AuthorizeOperation(
Shawn Willden0329a822017-12-04 13:55:14 -07001387 op.purpose, op.keyid, key_auths, params.getParameters(), authToken, op.handle,
1388 false /* is_begin_operation */);
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001389 if (!result->resultCode.isOk()) return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001390
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001391 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001392 const hidl_vec<KeyParameter>& outParams,
1393 const ::std::vector<uint8_t>& output) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001394 result->resultCode = ret;
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001395 if (result->resultCode.isOk()) {
1396 result->inputConsumed = inputConsumed;
1397 result->outParams = outParams;
1398 result->data = output;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001399 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001400 };
1401
Shawn Willden0329a822017-12-04 13:55:14 -07001402 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(op.device->update(
1403 op.handle, params.getParameters(), data, authToken, VerificationToken(), hidlCb));
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001404
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001405 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1406 // it if there was a communication error indicated by the ErrorCode.
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001407 if (!rc.isOk()) result->resultCode = rc;
1408
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001409 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001410}
1411
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001412Status KeyStoreService::finish(const sp<IBinder>& token, const KeymasterArguments& params,
1413 const ::std::vector<uint8_t>& signature,
1414 const ::std::vector<uint8_t>& entropy, OperationResult* result) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001415 auto getOpResult = mOperationMap.getOperation(token);
1416 if (!getOpResult.isOk()) {
1417 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
1418 return Status::ok();
1419 }
1420 const auto& op = std::move(getOpResult.value());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001421 if (!checkAllowedOperationParams(params.getParameters())) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001422 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001423 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001424 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001425
Shawn Willden0329a822017-12-04 13:55:14 -07001426 HardwareAuthToken authToken;
1427 std::tie(result->resultCode, authToken) = getOperationAuthTokenIfNeeded(token);
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001428 if (!result->resultCode.isOk()) return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001429
1430 if (entropy.size()) {
Janis Danisevskisc1460142017-12-18 16:48:46 -08001431 result->resultCode = KS_HANDLE_HIDL_ERROR(op.device->addRngEntropy(entropy));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001432 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001433 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001434 }
1435 }
1436
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001437 // Check that all key authorization policy requirements are met.
Shawn Willden0329a822017-12-04 13:55:14 -07001438 AuthorizationSet key_auths(op.characteristics.hardwareEnforced);
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001439 key_auths.append(op.characteristics.softwareEnforced.begin(),
1440 op.characteristics.softwareEnforced.end());
1441
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001442 result->resultCode = enforcement_policy.AuthorizeOperation(
Shawn Willden0329a822017-12-04 13:55:14 -07001443 op.purpose, op.keyid, key_auths, params.getParameters(), authToken, op.handle,
1444 false /* is_begin_operation */);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001445 if (!result->resultCode.isOk()) return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001446
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001447 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001448 const ::std::vector<uint8_t>& output) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001449 result->resultCode = ret;
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001450 if (result->resultCode.isOk()) {
1451 result->outParams = outParams;
1452 result->data = output;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001453 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001454 };
1455
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001456 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
Shawn Willden0329a822017-12-04 13:55:14 -07001457 op.device->finish(op.handle, params.getParameters(),
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001458 ::std::vector<uint8_t>() /* TODO(swillden): wire up input to finish() */,
Shawn Willden0329a822017-12-04 13:55:14 -07001459 signature, authToken, VerificationToken(), hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001460 mOperationMap.removeOperation(token);
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001461 mAuthTokenTable.MarkCompleted(op.handle);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001462
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) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001472 auto getOpResult = mOperationMap.removeOperation(token);
1473 if (!getOpResult.isOk()) {
1474 *aidl_return = static_cast<int32_t>(ErrorCode::INVALID_OPERATION_HANDLE);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001475 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001476 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001477 auto op = std::move(getOpResult.value());
1478 mAuthTokenTable.MarkCompleted(op.handle);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001479
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001480 ErrorCode error_code = KS_HANDLE_HIDL_ERROR(op.device->abort(op.handle));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001481 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(error_code));
1482 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001483}
1484
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001485Status KeyStoreService::isOperationAuthorized(const sp<IBinder>& token, bool* aidl_return) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001486 AuthorizationSet ignored;
Shawn Willden0329a822017-12-04 13:55:14 -07001487 KeyStoreServiceReturnCode rc;
1488 std::tie(rc, std::ignore) = getOperationAuthTokenIfNeeded(token);
1489 *aidl_return = rc.isOk();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001490 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001491}
1492
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001493Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
1494 int32_t* aidl_return) {
1495
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001496 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1497 // receive a HardwareAuthToken, rather than an opaque byte array.
1498
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001499 if (!checkBinderPermission(P_ADD_AUTH)) {
1500 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001501 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
1502 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001503 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001504 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
1505 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1506 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001507 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001508
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001509 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001510 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001511 if (authToken.version != 0) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001512 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1513 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001514 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001515
Shawn Willden0329a822017-12-04 13:55:14 -07001516 mAuthTokenTable.AddAuthenticationToken(hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001517 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1518 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001519}
1520
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001521bool isDeviceIdAttestationRequested(const KeymasterArguments& params) {
1522 const hardware::hidl_vec<KeyParameter> paramsVec = params.getParameters();
1523 for (size_t i = 0; i < paramsVec.size(); ++i) {
1524 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -06001525 case Tag::ATTESTATION_ID_BRAND:
1526 case Tag::ATTESTATION_ID_DEVICE:
1527 case Tag::ATTESTATION_ID_IMEI:
1528 case Tag::ATTESTATION_ID_MANUFACTURER:
1529 case Tag::ATTESTATION_ID_MEID:
1530 case Tag::ATTESTATION_ID_MODEL:
1531 case Tag::ATTESTATION_ID_PRODUCT:
1532 case Tag::ATTESTATION_ID_SERIAL:
1533 return true;
1534 default:
1535 break;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001536 }
1537 }
1538 return false;
1539}
1540
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001541Status KeyStoreService::attestKey(const String16& name, const KeymasterArguments& params,
1542 ::android::security::keymaster::KeymasterCertificateChain* chain,
1543 int32_t* aidl_return) {
1544 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1545 if (!checkAllowedOperationParams(params.getParameters())) {
1546 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1547 return Status::ok();
Shawn Willden50eb1b22016-01-21 12:41:23 -07001548 }
1549
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001550 if (isDeviceIdAttestationRequested(params)) {
1551 // There is a dedicated attestDeviceIds() method for device ID attestation.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001552 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1553 return Status::ok();
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001554 }
1555
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001556 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1557
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001558 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001559 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1560 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001561 *aidl_return = static_cast<int32_t>(rc);
1562 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001563 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001564
Shawn Willden50eb1b22016-01-21 12:41:23 -07001565 Blob keyBlob;
1566 String8 name8(name);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001567 rc = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
1568 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001569 *aidl_return = static_cast<int32_t>(rc);
1570 return Status::ok();
Shawn Willden50eb1b22016-01-21 12:41:23 -07001571 }
1572
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001573 KeyStoreServiceReturnCode error;
1574 auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1575 error = ret;
1576 if (!error.isOk()) {
1577 return;
1578 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001579 if (chain) {
1580 *chain = KeymasterCertificateChain(certChain);
1581 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001582 };
1583
1584 auto hidlKey = blob2hidlVec(keyBlob);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001585 auto dev = mKeyStore->getDevice(keyBlob);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001586 rc = KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
1587 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001588 *aidl_return = static_cast<int32_t>(rc);
1589 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001590 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001591 *aidl_return = static_cast<int32_t>(error);
1592 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001593}
1594
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001595Status
1596KeyStoreService::attestDeviceIds(const KeymasterArguments& params,
1597 ::android::security::keymaster::KeymasterCertificateChain* chain,
1598 int32_t* aidl_return) {
1599 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001600
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001601 if (!checkAllowedOperationParams(params.getParameters())) {
1602 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1603 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001604 }
1605
1606 if (!isDeviceIdAttestationRequested(params)) {
1607 // There is an attestKey() method for attesting keys without device ID attestation.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001608 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1609 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001610 }
1611
1612 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1613 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1614 if (binder == 0) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001615 *aidl_return =
1616 static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::CANNOT_ATTEST_IDS));
1617 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001618 }
1619 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1620 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1621 IPCThreadState::self()->getCallingPid(), callingUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001622 *aidl_return =
1623 static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::CANNOT_ATTEST_IDS));
1624 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001625 }
1626
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001627 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001628 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1629 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001630 *aidl_return = static_cast<int32_t>(rc);
1631 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001632 }
1633
1634 // Generate temporary key.
Janis Danisevskisc1460142017-12-18 16:48:46 -08001635 sp<Keymaster> dev;
1636 SecurityLevel securityLevel;
1637 std::tie(dev, securityLevel) = mKeyStore->getMostSecureDevice();
1638
1639 if (securityLevel == SecurityLevel::SOFTWARE) {
1640 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
1641 return Status::ok();
1642 }
1643
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001644 KeyStoreServiceReturnCode error;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001645 ::std::vector<uint8_t> hidlKey;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001646
1647 AuthorizationSet keyCharacteristics;
1648 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1649 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1650 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1651 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1652 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001653 auto generateHidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& hidlKeyBlob,
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001654 const KeyCharacteristics&) {
1655 error = ret;
1656 if (!error.isOk()) {
1657 return;
1658 }
1659 hidlKey = hidlKeyBlob;
1660 };
1661
1662 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(keyCharacteristics.hidl_data(), generateHidlCb));
1663 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001664 *aidl_return = static_cast<int32_t>(rc);
1665 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001666 }
1667 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001668 *aidl_return = static_cast<int32_t>(error);
1669 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001670 }
1671
1672 // Attest key and device IDs.
1673 auto attestHidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1674 error = ret;
1675 if (!error.isOk()) {
1676 return;
1677 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001678 *chain = ::android::security::keymaster::KeymasterCertificateChain(certChain);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001679 };
1680 KeyStoreServiceReturnCode attestationRc =
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001681 KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), attestHidlCb));
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001682
1683 // Delete temporary key.
1684 KeyStoreServiceReturnCode deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001685
1686 if (!attestationRc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001687 *aidl_return = static_cast<int32_t>(attestationRc);
1688 return Status::ok();
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001689 }
1690 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001691 *aidl_return = static_cast<int32_t>(error);
1692 return Status::ok();
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001693 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001694 *aidl_return = static_cast<int32_t>(deletionRc);
1695 return Status::ok();
Shawn Willden50eb1b22016-01-21 12:41:23 -07001696}
1697
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001698Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001699 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1700 mAuthTokenTable.onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001701 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1702 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001703}
1704
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001705#define AIDL_RETURN(rc) \
1706 (*_aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(rc)), Status::ok())
1707
1708Status KeyStoreService::importWrappedKey(
1709 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1710 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1711 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
1712 ::android::security::keymaster::KeyCharacteristics* outCharacteristics, int32_t* _aidl_return) {
1713
1714 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1715
1716 if (!checkBinderPermission(P_INSERT, callingUid)) {
1717 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1718 }
1719
1720 Blob wrappingKeyBlob;
1721 String8 wrappingKeyName8(wrappingKeyAlias);
1722 KeyStoreServiceReturnCode rc =
1723 mKeyStore->getKeyForName(&wrappingKeyBlob, wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
1724 if (!rc.isOk()) {
1725 return AIDL_RETURN(rc);
1726 }
1727
1728 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1729 auto dev = mKeyStore->getDevice(securityLevel);
1730 if (!dev) {
1731 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1732 }
1733
1734 auto hidlWrappingKey = blob2hidlVec(wrappingKeyBlob);
1735 String8 wrappedKeyAlias8(wrappedKeyAlias);
1736
1737 KeyStoreServiceReturnCode error;
1738
1739 auto hidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& keyBlob,
1740 const KeyCharacteristics& keyCharacteristics) {
1741 error = ret;
1742 if (!error.isOk()) {
1743 return;
1744 }
1745 if (outCharacteristics) {
1746 *outCharacteristics =
1747 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
1748 }
1749
1750 // Write the key:
1751 String8 filename(
1752 mKeyStore->getKeyNameForUidWithDir(wrappedKeyAlias8, callingUid, ::TYPE_KEYMASTER_10));
1753
1754 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
1755 ksBlob.setSecurityLevel(securityLevel);
1756
1757 if (containsTag(keyCharacteristics.hardwareEnforced, Tag::USER_SECURE_ID)) {
1758 ksBlob.setSuperEncrypted(true);
1759 }
1760
1761 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(callingUid));
1762 };
1763
1764 // TODO b/70904859 sanitize params and forward to keymaster
1765 // forward rootSid and fingerprintSid
1766 (void)params;
1767 (void)rootSid;
1768 (void)fingerprintSid;
1769 rc = KS_HANDLE_HIDL_ERROR(
1770 dev->importWrappedKey(wrappedKey, hidlWrappingKey, maskingKey, hidlCb));
1771 // possible hidl error
1772 if (!rc.isOk()) {
1773 return AIDL_RETURN(rc);
1774 }
1775 // now check error from callback
1776 if (!error.isOk()) {
1777 return AIDL_RETURN(error);
1778 }
1779
1780 // Write the characteristics:
1781 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(wrappedKeyAlias8, callingUid,
1782 ::TYPE_KEY_CHARACTERISTICS));
1783
1784 AuthorizationSet opParams = params.getParameters();
1785 std::stringstream kcStream;
1786 opParams.Serialize(&kcStream);
1787 if (kcStream.bad()) {
1788 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
1789 }
1790 auto kcBuf = kcStream.str();
1791
1792 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
1793 ::TYPE_KEY_CHARACTERISTICS);
1794 charBlob.setSecurityLevel(securityLevel);
1795
1796 return AIDL_RETURN(mKeyStore->put(cFilename.string(), &charBlob, get_user_id(callingUid)));
1797}
1798
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001799/**
1800 * Prune the oldest pruneable operation.
1801 */
1802bool KeyStoreService::pruneOperation() {
1803 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1804 ALOGD("Trying to prune operation %p", oldest.get());
1805 size_t op_count_before_abort = mOperationMap.getOperationCount();
1806 // We mostly ignore errors from abort() because all we care about is whether at least
1807 // one operation has been removed.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001808 int32_t abort_error;
1809 abort(oldest, &abort_error);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001810 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1811 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1812 return false;
1813 }
1814 return true;
1815}
1816
1817/**
1818 * Get the effective target uid for a binder operation that takes an
1819 * optional uid as the target.
1820 */
1821uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1822 if (targetUid == UID_SELF) {
1823 return IPCThreadState::self()->getCallingUid();
1824 }
1825 return static_cast<uid_t>(targetUid);
1826}
1827
1828/**
1829 * Check if the caller of the current binder method has the required
1830 * permission and if acting on other uids the grants to do so.
1831 */
1832bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1833 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1834 pid_t spid = IPCThreadState::self()->getCallingPid();
1835 if (!has_permission(callingUid, permission, spid)) {
1836 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1837 return false;
1838 }
1839 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1840 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1841 return false;
1842 }
1843 return true;
1844}
1845
1846/**
1847 * Check if the caller of the current binder method has the required
1848 * permission and the target uid is the caller or the caller is system.
1849 */
1850bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1851 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1852 pid_t spid = IPCThreadState::self()->getCallingPid();
1853 if (!has_permission(callingUid, permission, spid)) {
1854 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1855 return false;
1856 }
1857 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1858}
1859
1860/**
1861 * Check if the caller of the current binder method has the required
1862 * permission or the target of the operation is the caller's uid. This is
1863 * for operation where the permission is only for cross-uid activity and all
1864 * uids are allowed to act on their own (ie: clearing all entries for a
1865 * given uid).
1866 */
1867bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1868 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1869 if (getEffectiveUid(targetUid) == callingUid) {
1870 return true;
1871 } else {
1872 return checkBinderPermission(permission, targetUid);
1873 }
1874}
1875
1876/**
1877 * Helper method to check that the caller has the required permission as
1878 * well as the keystore is in the unlocked state if checkUnlocked is true.
1879 *
1880 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1881 * otherwise the state of keystore when not unlocked and checkUnlocked is
1882 * true.
1883 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001884KeyStoreServiceReturnCode
1885KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1886 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001887 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001888 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001889 }
1890 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1891 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001892 // All State values coincide with ResponseCodes
1893 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001894 }
1895
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001896 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001897}
1898
1899bool KeyStoreService::isKeystoreUnlocked(State state) {
1900 switch (state) {
1901 case ::STATE_NO_ERROR:
1902 return true;
1903 case ::STATE_UNINITIALIZED:
1904 case ::STATE_LOCKED:
1905 return false;
1906 }
1907 return false;
1908}
1909
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001910/**
Shawn Willden0329a822017-12-04 13:55:14 -07001911 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1912 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001913 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001914bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1915 for (size_t i = 0; i < params.size(); ++i) {
1916 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001917 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001918 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001919 return false;
1920 default:
1921 break;
1922 }
1923 }
1924 return true;
1925}
1926
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001927ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
Shawn Willdenc67a8aa2017-12-03 17:51:29 -07001928 sp<Keymaster>* dev,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001929 const AuthorizationSet& params,
1930 KeyCharacteristics* out) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001931 ::std::vector<uint8_t> appId;
1932 ::std::vector<uint8_t> appData;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001933 for (auto param : params) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001934 if (param.tag == Tag::APPLICATION_ID) {
1935 appId = authorizationValue(TAG_APPLICATION_ID, param).value();
1936 } else if (param.tag == Tag::APPLICATION_DATA) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001937 appId = authorizationValue(TAG_APPLICATION_DATA, param).value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001938 }
1939 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001940 ErrorCode error = ErrorCode::OK;
1941
1942 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
1943 error = ret;
1944 if (error != ErrorCode::OK) {
1945 return;
1946 }
1947 if (out) *out = keyCharacteristics;
1948 };
1949
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001950 ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appId, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001951 if (rc != ErrorCode::OK) {
1952 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001953 }
1954 return error;
1955}
1956
1957/**
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001958 * Get the auth token for this operation from the auth token table.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001959 *
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001960 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
1961 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1962 * authorization token exists for that operation and
1963 * failOnTokenMissing is false.
1964 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1965 * token for the operation
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001966 */
Shawn Willden0329a822017-12-04 13:55:14 -07001967std::pair<KeyStoreServiceReturnCode, HardwareAuthToken>
1968KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics, uint64_t handle,
1969 KeyPurpose purpose, bool failOnTokenMissing) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001970
Shawn Willden0329a822017-12-04 13:55:14 -07001971 AuthorizationSet allCharacteristics(characteristics.softwareEnforced);
1972 allCharacteristics.append(characteristics.hardwareEnforced.begin(),
1973 characteristics.hardwareEnforced.end());
1974
1975 const HardwareAuthToken* authToken = nullptr;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001976 AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
Shawn Willden0329a822017-12-04 13:55:14 -07001977 allCharacteristics, static_cast<KeyPurpose>(purpose), handle, &authToken);
1978
1979 KeyStoreServiceReturnCode rc;
1980
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001981 switch (err) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001982 case AuthTokenTable::OK:
1983 case AuthTokenTable::AUTH_NOT_REQUIRED:
Shawn Willden0329a822017-12-04 13:55:14 -07001984 rc = ResponseCode::NO_ERROR;
1985 break;
1986
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001987 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1988 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
1989 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001990 ALOGE("getAuthToken failed: %d", err); // STOPSHIP: debug only, to be removed
Shawn Willden0329a822017-12-04 13:55:14 -07001991 rc = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1992 break;
1993
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001994 case AuthTokenTable::OP_HANDLE_REQUIRED:
Shawn Willden0329a822017-12-04 13:55:14 -07001995 rc = failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
1996 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
1997 break;
1998
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001999 default:
2000 ALOGE("Unexpected FindAuthorization return value %d", err);
Shawn Willden0329a822017-12-04 13:55:14 -07002001 rc = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002002 }
Shawn Willden0329a822017-12-04 13:55:14 -07002003
2004 return {rc, authToken ? std::move(*authToken) : HardwareAuthToken()};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002005}
2006
2007/**
2008 * Add the auth token for the operation to the param list if the operation
2009 * requires authorization. Uses the cached result in the OperationMap if available
2010 * otherwise gets the token from the AuthTokenTable and caches the result.
2011 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002012 * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002013 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2014 * authenticated.
2015 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2016 * operation token.
2017 */
Shawn Willden0329a822017-12-04 13:55:14 -07002018std::pair<KeyStoreServiceReturnCode, const HardwareAuthToken&>
2019KeyStoreService::getOperationAuthTokenIfNeeded(const sp<IBinder>& token) {
2020 static HardwareAuthToken emptyToken = {};
2021
Shawn Willdenda6dcc32017-12-03 14:56:05 -07002022 auto getOpResult = mOperationMap.getOperation(token);
Shawn Willden0329a822017-12-04 13:55:14 -07002023 if (!getOpResult.isOk()) return {ErrorCode::INVALID_OPERATION_HANDLE, emptyToken};
Shawn Willdenda6dcc32017-12-03 14:56:05 -07002024 const auto& op = getOpResult.value();
2025
Shawn Willden0329a822017-12-04 13:55:14 -07002026 if (!op.hasAuthToken()) {
2027 KeyStoreServiceReturnCode rc;
2028 HardwareAuthToken found;
2029 std::tie(rc, found) = getAuthToken(op.characteristics, op.handle, op.purpose);
2030 if (!rc.isOk()) return {rc, emptyToken};
2031 mOperationMap.setOperationAuthToken(token, std::move(found));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002032 }
Shawn Willden0329a822017-12-04 13:55:14 -07002033
2034 return {ResponseCode::NO_ERROR, op.authToken};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002035}
2036
2037/**
2038 * Translate a result value to a legacy return value. All keystore errors are
2039 * preserved and keymaster errors become SYSTEM_ERRORs
2040 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002041KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
Shawn Willden0329a822017-12-04 13:55:14 -07002042 if (result > 0) return static_cast<ResponseCode>(result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002043 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002044}
2045
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002046static NullOr<const Algorithm&> getKeyAlgoritmFromKeyCharacteristics(
2047 const ::android::security::keymaster::KeyCharacteristics& characteristics) {
Shawn Willden0329a822017-12-04 13:55:14 -07002048 for (const auto& param : characteristics.hardwareEnforced.getParameters()) {
2049 auto algo = authorizationValue(TAG_ALGORITHM, param);
2050 if (algo.isOk()) return algo;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002051 }
Shawn Willden0329a822017-12-04 13:55:14 -07002052 for (const auto& param : characteristics.softwareEnforced.getParameters()) {
2053 auto algo = authorizationValue(TAG_ALGORITHM, param);
2054 if (algo.isOk()) return algo;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002055 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002056 return {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002057}
2058
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002059void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002060 // All legacy keys are DIGEST_NONE/PAD_NONE.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002061 params->push_back(TAG_DIGEST, Digest::NONE);
2062 params->push_back(TAG_PADDING, PaddingMode::NONE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002063
2064 // Look up the algorithm of the key.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002065 ::android::security::keymaster::KeyCharacteristics characteristics;
2066 int32_t result;
2067 auto rc = getKeyCharacteristics(name, ::android::security::keymaster::KeymasterBlob(),
2068 ::android::security::keymaster::KeymasterBlob(), UID_SELF,
2069 &characteristics, &result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002070 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002071 ALOGE("Failed to get key characteristics");
2072 return;
2073 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002074 auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
2075 if (!algorithm.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002076 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
2077 return;
2078 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002079 params->push_back(TAG_ALGORITHM, algorithm.value());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002080}
2081
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002082KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
2083 const hidl_vec<uint8_t>& data,
2084 hidl_vec<uint8_t>* out,
2085 const hidl_vec<uint8_t>& signature,
2086 KeyPurpose purpose) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002087
2088 std::basic_stringstream<uint8_t> outBuffer;
2089 OperationResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002090 AuthorizationSet inArgs;
2091 addLegacyBeginParams(name, &inArgs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002092 sp<IBinder> appToken(new BBinder);
2093 sp<IBinder> token;
2094
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002095 begin(appToken, name, static_cast<int32_t>(purpose), true,
2096 KeymasterArguments(inArgs.hidl_data()), ::std::vector<uint8_t>(), UID_SELF, &result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002097 if (!result.resultCode.isOk()) {
2098 if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002099 ALOGW("Key not found");
2100 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002101 ALOGW("Error in begin: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002102 }
2103 return translateResultToLegacyResult(result.resultCode);
2104 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002105 inArgs.Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002106 token = result.token;
2107 size_t consumed = 0;
2108 size_t lastConsumed = 0;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002109 hidl_vec<uint8_t> data_view;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002110 do {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002111 data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002112 update(token, KeymasterArguments(inArgs.hidl_data()), data_view, &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002113 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002114 ALOGW("Error in update: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002115 return translateResultToLegacyResult(result.resultCode);
2116 }
2117 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002118 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002119 }
2120 lastConsumed = result.inputConsumed;
2121 consumed += lastConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002122 } while (consumed < data.size() && lastConsumed > 0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002123
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002124 if (consumed != data.size()) {
2125 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
2126 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002127 }
2128
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002129 finish(token, KeymasterArguments(inArgs.hidl_data()), signature, ::std::vector<uint8_t>(),
2130 &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002131 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002132 ALOGW("Error in finish: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002133 return translateResultToLegacyResult(result.resultCode);
2134 }
2135 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002136 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002137 }
2138
2139 if (out) {
2140 auto buf = outBuffer.str();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002141 out->resize(buf.size());
2142 memcpy(&(*out)[0], buf.data(), out->size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002143 }
2144
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002145 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002146}
2147
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002148KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
2149 const AuthorizationSet& params,
2150 Blob* blob) {
Shawn Willden98c59162016-03-20 09:10:18 -06002151 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
2152 String8 name8(name);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002153 KeyStoreServiceReturnCode responseCode =
2154 mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002155 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willden98c59162016-03-20 09:10:18 -06002156 return responseCode;
2157 }
Rubin Xu7675c9f2017-03-15 19:26:52 +00002158 ALOGI("upgradeKeyBlob %s %d", name8.string(), uid);
Shawn Willden98c59162016-03-20 09:10:18 -06002159
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002160 auto hidlKey = blob2hidlVec(*blob);
Janis Danisevskisc1460142017-12-18 16:48:46 -08002161 auto dev = mKeyStore->getDevice(*blob);
Shawn Willden98c59162016-03-20 09:10:18 -06002162
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002163 KeyStoreServiceReturnCode error;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002164 auto hidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& upgradedKeyBlob) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002165 error = ret;
2166 if (!error.isOk()) {
2167 return;
2168 }
2169
Janis Danisevskisaf7783f2017-09-21 11:29:47 -07002170 auto filename = mKeyStore->getBlobFileNameIfExists(name8, uid, ::TYPE_KEYMASTER_10);
2171 if (!filename.isOk()) {
2172 ALOGI("trying to upgrade a non existing blob");
2173 return;
2174 }
2175 error = mKeyStore->del(filename.value().string(), ::TYPE_ANY, get_user_id(uid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002176 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00002177 ALOGI("upgradeKeyBlob keystore->del failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002178 return;
2179 }
2180
2181 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
2182 0 /* infoLength */, ::TYPE_KEYMASTER_10);
Janis Danisevskisc1460142017-12-18 16:48:46 -08002183 newBlob.setSecurityLevel(blob->getSecurityLevel());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002184 newBlob.setEncrypted(blob->isEncrypted());
Rubin Xu67899de2017-04-21 19:15:13 +01002185 newBlob.setSuperEncrypted(blob->isSuperEncrypted());
2186 newBlob.setCriticalToDeviceEncryption(blob->isCriticalToDeviceEncryption());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002187
Janis Danisevskisaf7783f2017-09-21 11:29:47 -07002188 error = mKeyStore->put(filename.value().string(), &newBlob, get_user_id(uid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002189 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00002190 ALOGI("upgradeKeyBlob keystore->put failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002191 return;
2192 }
2193
2194 // Re-read blob for caller. We can't use newBlob because writing it modified it.
2195 error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
2196 };
2197
2198 KeyStoreServiceReturnCode rc =
2199 KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
2200 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06002201 return rc;
2202 }
2203
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002204 return error;
Shawn Willden98c59162016-03-20 09:10:18 -06002205}
2206
Shawn Willdene2a7b522017-04-11 09:27:40 -06002207} // namespace keystore