blob: c2879c8f333e417a5cb16d5b014c5afaa678f1fc [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
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700788Status KeyStoreService::addRngEntropy(const ::std::vector<uint8_t>& entropy, int32_t* aidl_return) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100789 const auto& device = mKeyStore->getDevice();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700790 *aidl_return = static_cast<int32_t>(
791 KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device->addRngEntropy(entropy))));
792 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700793}
794
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700795Status
796KeyStoreService::generateKey(const String16& name, const KeymasterArguments& params,
797 const ::std::vector<uint8_t>& entropy, int uid, int flags,
798 android::security::keymaster::KeyCharacteristics* outCharacteristics,
799 int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700800 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100801 KeyStoreServiceReturnCode rc =
802 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
803 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700804 *aidl_return = static_cast<int32_t>(rc);
805 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700806 }
Rubin Xu67899de2017-04-21 19:15:13 +0100807 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
808 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700809 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
810 return Status::ok();
Rubin Xu67899de2017-04-21 19:15:13 +0100811 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700812
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700813 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
814 if (!checkBinderPermission(P_GEN_UNIQUE_ID)) {
815 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
816 return Status::ok();
817 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600818 }
819
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100820 bool usingFallback = false;
821 auto& dev = mKeyStore->getDevice();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700822 AuthorizationSet keyCharacteristics = params.getParameters();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400823
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700824 // TODO: Seed from Linux RNG before this.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700825 int32_t result;
826 addRngEntropy(entropy, &result); // binder error is not possible.
827 if (!KeyStoreServiceReturnCode(result).isOk()) {
828 *aidl_return = static_cast<int32_t>(result);
829 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700830 }
831
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100832 KeyStoreServiceReturnCode error;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700833 auto hidl_cb = [&](ErrorCode ret, const ::std::vector<uint8_t>& hidlKeyBlob,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100834 const KeyCharacteristics& keyCharacteristics) {
835 error = ret;
836 if (!error.isOk()) {
837 return;
838 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700839 if (outCharacteristics)
840 *outCharacteristics =
841 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700842
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100843 // Write the key
844 String8 name8(name);
845 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700846
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100847 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
848 keyBlob.setFallback(usingFallback);
Rubin Xu67899de2017-04-21 19:15:13 +0100849 keyBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700850 if (isAuthenticationBound(params.getParameters()) &&
851 !keyBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -0700852 keyBlob.setSuperEncrypted(true);
853 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100854 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700855
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100856 error = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
857 };
858
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700859 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(params.getParameters(), hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100860 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700861 *aidl_return = static_cast<int32_t>(rc);
862 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400863 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100864 if (!error.isOk()) {
865 ALOGE("Failed to generate key -> falling back to software keymaster");
866 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000867 auto fallback = mKeyStore->getFallbackDevice();
868 if (!fallback.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700869 *aidl_return = static_cast<int32_t>(error);
870 return Status::ok();
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000871 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700872 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->generateKey(params.getParameters(), hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100873 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700874 *aidl_return = static_cast<int32_t>(rc);
875 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100876 }
877 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700878 *aidl_return = static_cast<int32_t>(error);
879 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100880 }
881 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400882
883 // Write the characteristics:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100884 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400885 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
886
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100887 std::stringstream kc_stream;
888 keyCharacteristics.Serialize(&kc_stream);
889 if (kc_stream.bad()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700890 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
891 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100892 }
893 auto kc_buf = kc_stream.str();
894 Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
895 ::TYPE_KEY_CHARACTERISTICS);
896 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400897 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
898
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700899 *aidl_return =
900 static_cast<int32_t>(mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid)));
901 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700902}
903
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700904Status KeyStoreService::getKeyCharacteristics(
905 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
906 const ::android::security::keymaster::KeymasterBlob& appId, int32_t uid,
907 ::android::security::keymaster::KeyCharacteristics* outCharacteristics, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700908 if (!outCharacteristics) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700909 *aidl_return =
910 static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::UNEXPECTED_NULL_POINTER));
911 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700912 }
913
914 uid_t targetUid = getEffectiveUid(uid);
915 uid_t callingUid = IPCThreadState::self()->getCallingUid();
916 if (!is_granted_to(callingUid, targetUid)) {
917 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
918 targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700919 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
920 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700921 }
922
923 Blob keyBlob;
924 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700925
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100926 KeyStoreServiceReturnCode rc =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700927 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskisd714a672017-09-01 14:31:36 -0700928 if (rc == ResponseCode::UNINITIALIZED) {
929 /*
930 * If we fail reading the blob because the master key is missing we try to retrieve the
931 * key characteristics from the characteristics file. This happens when auth-bound
932 * keys are used after a screen lock has been removed by the user.
933 */
934 rc = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
935 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700936 *aidl_return = static_cast<int32_t>(rc);
937 return Status::ok();
Janis Danisevskisd714a672017-09-01 14:31:36 -0700938 }
939 AuthorizationSet keyCharacteristics;
940 // TODO write one shot stream buffer to avoid copying (twice here)
941 std::string charBuffer(reinterpret_cast<const char*>(keyBlob.getValue()),
942 keyBlob.getLength());
943 std::stringstream charStream(charBuffer);
944 keyCharacteristics.Deserialize(&charStream);
945
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700946 outCharacteristics->softwareEnforced = KeymasterArguments(keyCharacteristics.hidl_data());
947 *aidl_return = static_cast<int32_t>(rc);
948 return Status::ok();
Janis Danisevskisd714a672017-09-01 14:31:36 -0700949 } else if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700950 *aidl_return = static_cast<int32_t>(rc);
951 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700952 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100953
954 auto hidlKeyBlob = blob2hidlVec(keyBlob);
955 auto& dev = mKeyStore->getDevice(keyBlob);
956
957 KeyStoreServiceReturnCode error;
958
959 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
960 error = ret;
961 if (!error.isOk()) {
962 return;
Shawn Willden98c59162016-03-20 09:10:18 -0600963 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700964 *outCharacteristics =
965 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100966 };
967
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700968 rc = KS_HANDLE_HIDL_ERROR(
969 dev->getKeyCharacteristics(hidlKeyBlob, clientId.getData(), appId.getData(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100970 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700971 *aidl_return = static_cast<int32_t>(rc);
972 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100973 }
974
975 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
976 AuthorizationSet upgradeParams;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700977 if (clientId.getData().size()) {
978 upgradeParams.push_back(TAG_APPLICATION_ID, clientId.getData());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100979 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700980 if (appId.getData().size()) {
981 upgradeParams.push_back(TAG_APPLICATION_DATA, appId.getData());
Shawn Willden98c59162016-03-20 09:10:18 -0600982 }
983 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100984 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700985 *aidl_return = static_cast<int32_t>(rc);
986 return Status::ok();
Shawn Willden98c59162016-03-20 09:10:18 -0600987 }
Shawn Willden715d0232016-01-21 00:45:13 -0700988
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100989 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
990
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700991 rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(
992 upgradedHidlKeyBlob, clientId.getData(), appId.getData(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100993 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700994 *aidl_return = static_cast<int32_t>(rc);
995 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100996 }
997 // Note that, on success, "error" will have been updated by the hidlCB callback.
998 // So it is fine to return "error" below.
999 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001000 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(error));
1001 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001002}
1003
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001004Status
1005KeyStoreService::importKey(const String16& name, const KeymasterArguments& params, int32_t format,
1006 const ::std::vector<uint8_t>& keyData, int uid, int flags,
1007 ::android::security::keymaster::KeyCharacteristics* outCharacteristics,
1008 int32_t* aidl_return) {
1009
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001010 uid = getEffectiveUid(uid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001011 KeyStoreServiceReturnCode rc =
1012 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
1013 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001014 *aidl_return = static_cast<int32_t>(rc);
1015 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001016 }
Rubin Xu67899de2017-04-21 19:15:13 +01001017 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
1018 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001019 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
1020 return Status::ok();
Rubin Xu67899de2017-04-21 19:15:13 +01001021 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001022
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001023 bool usingFallback = false;
1024 auto& dev = mKeyStore->getDevice();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001025
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001026 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001027
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001028 KeyStoreServiceReturnCode error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001029
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001030 auto hidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& keyBlob,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001031 const KeyCharacteristics& keyCharacteristics) {
1032 error = ret;
1033 if (!error.isOk()) {
1034 return;
1035 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001036 if (outCharacteristics)
1037 *outCharacteristics =
1038 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001039
1040 // Write the key:
1041 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1042
1043 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
1044 ksBlob.setFallback(usingFallback);
Rubin Xu67899de2017-04-21 19:15:13 +01001045 ksBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001046 if (isAuthenticationBound(params.getParameters()) &&
1047 !ksBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -07001048 ksBlob.setSuperEncrypted(true);
1049 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001050 ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1051
1052 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
1053 };
1054
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001055 rc = KS_HANDLE_HIDL_ERROR(
1056 dev->importKey(params.getParameters(), KeyFormat(format), keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001057 // possible hidl error
1058 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001059 *aidl_return = static_cast<int32_t>(rc);
1060 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001061 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001062 // now check error from callback
1063 if (!error.isOk()) {
1064 ALOGE("Failed to import key -> falling back to software keymaster");
1065 usingFallback = true;
Janis Danisevskise8ba1802017-01-30 10:49:51 +00001066 auto fallback = mKeyStore->getFallbackDevice();
1067 if (!fallback.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001068 *aidl_return = static_cast<int32_t>(error);
1069 return Status::ok();
Janis Danisevskise8ba1802017-01-30 10:49:51 +00001070 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001071 rc = KS_HANDLE_HIDL_ERROR(fallback.value()->importKey(params.getParameters(),
1072 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();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001077 }
1078 // now check error from callback
1079 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001080 *aidl_return = static_cast<int32_t>(error);
1081 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001082 }
1083 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001084
1085 // Write the characteristics:
1086 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
1087
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001088 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001089 std::stringstream kcStream;
1090 opParams.Serialize(&kcStream);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001091 if (kcStream.bad()) {
1092 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
1093 return Status::ok();
1094 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001095 auto kcBuf = kcStream.str();
1096
1097 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
1098 ::TYPE_KEY_CHARACTERISTICS);
1099 charBlob.setFallback(usingFallback);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001100 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1101
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001102 *aidl_return =
1103 static_cast<int32_t>(mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid)));
1104
1105 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001106}
1107
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001108Status KeyStoreService::exportKey(const String16& name, int32_t format,
1109 const ::android::security::keymaster::KeymasterBlob& clientId,
1110 const ::android::security::keymaster::KeymasterBlob& appId,
1111 int32_t uid, ExportResult* result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001112
1113 uid_t targetUid = getEffectiveUid(uid);
1114 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1115 if (!is_granted_to(callingUid, targetUid)) {
1116 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001117 result->resultCode = ResponseCode::PERMISSION_DENIED;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001118 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001119 }
1120
1121 Blob keyBlob;
1122 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001123
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001124 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
1125 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001126 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001127 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001128
1129 auto key = blob2hidlVec(keyBlob);
1130 auto& dev = mKeyStore->getDevice(keyBlob);
1131
1132 auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
1133 result->resultCode = ret;
1134 if (!result->resultCode.isOk()) {
Ji Wang2c142312016-10-14 17:21:10 +08001135 return;
1136 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001137 result->exportData = keyMaterial;
1138 };
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001139 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
1140 dev->exportKey(KeyFormat(format), key, clientId.getData(), appId.getData(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001141 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
1142 // callback hidlCb.
1143 if (!rc.isOk()) {
1144 result->resultCode = rc;
Ji Wang2c142312016-10-14 17:21:10 +08001145 }
1146
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001147 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1148 AuthorizationSet upgradeParams;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001149 if (clientId.getData().size()) {
1150 upgradeParams.push_back(TAG_APPLICATION_ID, clientId.getData());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001151 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001152 if (appId.getData().size()) {
1153 upgradeParams.push_back(TAG_APPLICATION_DATA, appId.getData());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001154 }
1155 result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
1156 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001157 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001158 }
1159
1160 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
1161
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001162 result->resultCode = KS_HANDLE_HIDL_ERROR(dev->exportKey(
1163 KeyFormat(format), upgradedHidlKeyBlob, clientId.getData(), appId.getData(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001164 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001165 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001166 }
1167 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001168 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001169}
1170
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001171static inline void addAuthTokenToParams(AuthorizationSet* params, const HardwareAuthToken* token) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001172 if (token) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001173 params->push_back(TAG_AUTH_TOKEN, authToken2HidlVec(*token));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001174 }
1175}
1176
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001177Status KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, int32_t purpose,
1178 bool pruneable, const KeymasterArguments& params,
1179 const ::std::vector<uint8_t>& entropy, int32_t uid,
1180 OperationResult* result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001181 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1182 uid_t targetUid = getEffectiveUid(uid);
1183 if (!is_granted_to(callingUid, targetUid)) {
1184 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001185 result->resultCode = ResponseCode::PERMISSION_DENIED;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001186 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001187 }
1188 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
1189 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001190 result->resultCode = ResponseCode::PERMISSION_DENIED;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001191 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001192 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001193 if (!checkAllowedOperationParams(params.getParameters())) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001194 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001195 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001196 }
1197 Blob keyBlob;
1198 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001199 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Shawn Willdend5a24e62017-02-28 13:53:24 -07001200 if (result->resultCode == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
1201 result->resultCode = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1202 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001203 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001204 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001205 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001206
1207 auto key = blob2hidlVec(keyBlob);
1208 auto& dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001209 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001210 KeyCharacteristics characteristics;
1211 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
1212
1213 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1214 result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
1215 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001216 return Status::ok();
Shawn Willden98c59162016-03-20 09:10:18 -06001217 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001218 key = blob2hidlVec(keyBlob);
1219 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
Shawn Willden98c59162016-03-20 09:10:18 -06001220 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001221 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001222 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001223 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001224
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001225 const HardwareAuthToken* authToken = NULL;
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001226
1227 // Merge these characteristics with the ones cached when the key was generated or imported
1228 Blob charBlob;
1229 AuthorizationSet persistedCharacteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001230 result->resultCode =
1231 mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
1232 if (result->resultCode.isOk()) {
1233 // TODO write one shot stream buffer to avoid copying (twice here)
1234 std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
1235 charBlob.getLength());
1236 std::stringstream charStream(charBuffer);
1237 persistedCharacteristics.Deserialize(&charStream);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001238 } else {
1239 ALOGD("Unable to read cached characteristics for key");
1240 }
1241
1242 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001243 AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
1244 AuthorizationSet teeEnforced = characteristics.teeEnforced;
1245 persistedCharacteristics.Union(softwareEnforced);
1246 persistedCharacteristics.Subtract(teeEnforced);
1247 characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001248
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001249 auto authResult = getAuthToken(characteristics, 0, KeyPurpose(purpose), &authToken,
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001250 /*failOnTokenMissing*/ false);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001251 // If per-operation auth is needed we need to begin the operation and
1252 // the client will need to authorize that operation before calling
1253 // update. Any other auth issues stop here.
Shawn Willden827243a2017-09-12 05:41:33 -06001254 if (!authResult.isOk() && authResult != ResponseCode::OP_AUTH_NEEDED) {
1255 result->resultCode = authResult;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001256 return Status::ok();
Shawn Willden827243a2017-09-12 05:41:33 -06001257 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001258
1259 addAuthTokenToParams(&opParams, authToken);
1260
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001261 // Add entropy to the device first.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001262 if (entropy.size()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001263 int32_t resultCode;
1264 addRngEntropy(entropy, &resultCode); // binder error is not possible
1265 result->resultCode = KeyStoreServiceReturnCode(resultCode);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001266 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001267 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001268 }
1269 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001270
1271 // Create a keyid for this key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001272 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001273 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
1274 ALOGE("Failed to create a key ID for authorization checking.");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001275 result->resultCode = ErrorCode::UNKNOWN_ERROR;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001276 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001277 }
1278
1279 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001280 AuthorizationSet key_auths = characteristics.teeEnforced;
1281 key_auths.append(&characteristics.softwareEnforced[0],
1282 &characteristics.softwareEnforced[characteristics.softwareEnforced.size()]);
1283
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001284 result->resultCode =
1285 enforcement_policy.AuthorizeOperation(KeyPurpose(purpose), keyid, key_auths, opParams,
1286 0 /* op_handle */, true /* is_begin_operation */);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001287 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001288 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001289 }
1290
Shawn Willdene2a7b522017-04-11 09:27:40 -06001291 // If there are more than kMaxOperations, abort the oldest operation that was started as
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001292 // pruneable.
Shawn Willdene2a7b522017-04-11 09:27:40 -06001293 while (mOperationMap.getOperationCount() >= kMaxOperations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001294 ALOGD("Reached or exceeded concurrent operations limit");
1295 if (!pruneOperation()) {
1296 break;
1297 }
1298 }
1299
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001300 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1301 uint64_t operationHandle) {
1302 result->resultCode = ret;
1303 if (!result->resultCode.isOk()) {
1304 return;
1305 }
1306 result->handle = operationHandle;
1307 result->outParams = outParams;
1308 };
1309
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001310 ErrorCode rc =
1311 KS_HANDLE_HIDL_ERROR(dev->begin(KeyPurpose(purpose), key, opParams.hidl_data(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001312 if (rc != ErrorCode::OK) {
1313 ALOGW("Got error %d from begin()", rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001314 }
1315
1316 // If there are too many operations abort the oldest operation that was
1317 // started as pruneable and try again.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001318 while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1319 ALOGW("Ran out of operation handles");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001320 if (!pruneOperation()) {
1321 break;
1322 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001323 rc = KS_HANDLE_HIDL_ERROR(
1324 dev->begin(KeyPurpose(purpose), key, opParams.hidl_data(), hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001325 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001326 if (rc != ErrorCode::OK) {
1327 result->resultCode = rc;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001328 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001329 }
1330
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001331 // Note: The operation map takes possession of the contents of "characteristics".
1332 // It is safe to use characteristics after the following line but it will be empty.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001333 sp<IBinder> operationToken =
1334 mOperationMap.addOperation(result->handle, keyid, KeyPurpose(purpose), dev, appToken,
1335 std::move(characteristics), pruneable);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001336 assert(characteristics.teeEnforced.size() == 0);
1337 assert(characteristics.softwareEnforced.size() == 0);
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001338 result->token = operationToken;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001339
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001340 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001341 mOperationMap.setOperationAuthToken(operationToken, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001342 }
1343 // Return the authentication lookup result. If this is a per operation
1344 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1345 // application should get an auth token using the handle before the
1346 // first call to update, which will fail if keystore hasn't received the
1347 // auth token.
Shawn Willden2f96c792017-09-07 23:59:08 -06001348 if (result->resultCode == ErrorCode::OK) {
1349 result->resultCode = authResult;
1350 }
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001351
1352 // Other result fields were set in the begin operation's callback.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001353 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001354}
1355
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001356Status KeyStoreService::update(const sp<IBinder>& token, const KeymasterArguments& params,
1357 const ::std::vector<uint8_t>& data, OperationResult* result) {
1358 if (!checkAllowedOperationParams(params.getParameters())) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001359 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001360 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001361 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001362 km_device_t dev;
1363 uint64_t handle;
1364 KeyPurpose purpose;
1365 km_id_t keyid;
1366 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001367 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001368 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001369 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001370 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001371 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001372 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1373 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001374 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001375 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001376
1377 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001378 AuthorizationSet key_auths(characteristics->teeEnforced);
1379 key_auths.append(&characteristics->softwareEnforced[0],
1380 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001381 result->resultCode = enforcement_policy.AuthorizeOperation(
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001382 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
1383 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001384 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001385 }
1386
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001387 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001388 const hidl_vec<KeyParameter>& outParams,
1389 const ::std::vector<uint8_t>& output) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001390 result->resultCode = ret;
1391 if (!result->resultCode.isOk()) {
1392 return;
1393 }
1394 result->inputConsumed = inputConsumed;
1395 result->outParams = outParams;
1396 result->data = output;
1397 };
1398
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001399 KeyStoreServiceReturnCode rc =
1400 KS_HANDLE_HIDL_ERROR(dev->update(handle, opParams.hidl_data(), data, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001401 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1402 // it if there was a communication error indicated by the ErrorCode.
1403 if (!rc.isOk()) {
1404 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001405 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001406 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001407}
1408
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001409Status KeyStoreService::finish(const sp<IBinder>& token, const KeymasterArguments& params,
1410 const ::std::vector<uint8_t>& signature,
1411 const ::std::vector<uint8_t>& entropy, OperationResult* result) {
1412 if (!checkAllowedOperationParams(params.getParameters())) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001413 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001414 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001415 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001416 km_device_t dev;
1417 uint64_t handle;
1418 KeyPurpose purpose;
1419 km_id_t keyid;
1420 const KeyCharacteristics* characteristics;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001421 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001422 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001423 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001424 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001425 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001426 result->resultCode = addOperationAuthTokenIfNeeded(token, &opParams);
1427 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001428 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001429 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001430
1431 if (entropy.size()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001432 int resultCode;
1433 addRngEntropy(entropy, &resultCode); // binder error is not possible
1434 result->resultCode = KeyStoreServiceReturnCode(resultCode);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001435 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001436 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001437 }
1438 }
1439
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001440 // Check that all key authorization policy requirements are met.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001441 AuthorizationSet key_auths(characteristics->teeEnforced);
1442 key_auths.append(&characteristics->softwareEnforced[0],
1443 &characteristics->softwareEnforced[characteristics->softwareEnforced.size()]);
1444 result->resultCode = enforcement_policy.AuthorizeOperation(
1445 purpose, keyid, key_auths, opParams, handle, false /* is_begin_operation */);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001446 if (!result->resultCode.isOk()) return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001447
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001448 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001449 const ::std::vector<uint8_t>& output) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001450 result->resultCode = ret;
1451 if (!result->resultCode.isOk()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001452 }
1453 result->outParams = outParams;
1454 result->data = output;
1455 };
1456
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001457 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
1458 dev->finish(handle, opParams.hidl_data(),
1459 ::std::vector<uint8_t>() /* TODO(swillden): wire up input to finish() */,
1460 signature, hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001461 // Remove the operation regardless of the result
1462 mOperationMap.removeOperation(token);
1463 mAuthTokenTable.MarkCompleted(handle);
1464
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001465 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1466 // it if there was a communication error indicated by the ErrorCode.
1467 if (!rc.isOk()) {
1468 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001469 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001470 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001471}
1472
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001473Status KeyStoreService::abort(const sp<IBinder>& token, int32_t* aidl_return) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001474 km_device_t dev;
1475 uint64_t handle;
1476 KeyPurpose purpose;
1477 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001478 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, NULL)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001479 *aidl_return =
1480 static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_OPERATION_HANDLE));
1481 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001482 }
1483 mOperationMap.removeOperation(token);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001484
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001485 ErrorCode error_code = KS_HANDLE_HIDL_ERROR(dev->abort(handle));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001486 mAuthTokenTable.MarkCompleted(handle);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001487 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(error_code));
1488 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001489}
1490
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001491Status KeyStoreService::isOperationAuthorized(const sp<IBinder>& token, bool* aidl_return) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001492 km_device_t dev;
1493 uint64_t handle;
1494 const KeyCharacteristics* characteristics;
1495 KeyPurpose purpose;
1496 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001497 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001498 *aidl_return = false;
1499 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001500 }
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001501 const HardwareAuthToken* authToken = NULL;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001502 mOperationMap.getOperationAuthToken(token, &authToken);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001503 AuthorizationSet ignored;
1504 auto authResult = addOperationAuthTokenIfNeeded(token, &ignored);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001505 *aidl_return = authResult.isOk();
1506 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001507}
1508
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001509Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
1510 int32_t* aidl_return) {
1511
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001512 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1513 // receive a HardwareAuthToken, rather than an opaque byte array.
1514
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001515 if (!checkBinderPermission(P_ADD_AUTH)) {
1516 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001517 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
1518 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001519 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001520 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
1521 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1522 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001523 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001524
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001525 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001526 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001527 if (authToken.version != 0) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001528 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1529 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001530 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001531
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001532 std::unique_ptr<HardwareAuthToken> hidlAuthToken(new HardwareAuthToken);
1533 hidlAuthToken->challenge = authToken.challenge;
1534 hidlAuthToken->userId = authToken.user_id;
1535 hidlAuthToken->authenticatorId = authToken.authenticator_id;
1536 hidlAuthToken->authenticatorType = authToken.authenticator_type;
1537 hidlAuthToken->timestamp = authToken.timestamp;
1538 static_assert(
1539 std::is_same<decltype(hidlAuthToken->hmac),
1540 ::android::hardware::hidl_array<uint8_t, sizeof(authToken.hmac)>>::value,
1541 "This function assumes token HMAC is 32 bytes, but it might not be.");
1542 std::copy(authToken.hmac, authToken.hmac + sizeof(authToken.hmac), hidlAuthToken->hmac.data());
1543
Janis Danisevskis8f737ad2017-11-21 12:30:15 -08001544 mAuthTokenTable.AddAuthenticationToken(std::move(hidlAuthToken));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001545 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1546 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001547}
1548
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001549bool isDeviceIdAttestationRequested(const KeymasterArguments& params) {
1550 const hardware::hidl_vec<KeyParameter> paramsVec = params.getParameters();
1551 for (size_t i = 0; i < paramsVec.size(); ++i) {
1552 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -06001553 case Tag::ATTESTATION_ID_BRAND:
1554 case Tag::ATTESTATION_ID_DEVICE:
1555 case Tag::ATTESTATION_ID_IMEI:
1556 case Tag::ATTESTATION_ID_MANUFACTURER:
1557 case Tag::ATTESTATION_ID_MEID:
1558 case Tag::ATTESTATION_ID_MODEL:
1559 case Tag::ATTESTATION_ID_PRODUCT:
1560 case Tag::ATTESTATION_ID_SERIAL:
1561 return true;
1562 default:
1563 break;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001564 }
1565 }
1566 return false;
1567}
1568
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001569Status KeyStoreService::attestKey(const String16& name, const KeymasterArguments& params,
1570 ::android::security::keymaster::KeymasterCertificateChain* chain,
1571 int32_t* aidl_return) {
1572 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1573 if (!checkAllowedOperationParams(params.getParameters())) {
1574 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1575 return Status::ok();
Shawn Willden50eb1b22016-01-21 12:41:23 -07001576 }
1577
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001578 if (isDeviceIdAttestationRequested(params)) {
1579 // There is a dedicated attestDeviceIds() method for device ID attestation.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001580 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1581 return Status::ok();
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001582 }
1583
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001584 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1585
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001586 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001587 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1588 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001589 *aidl_return = static_cast<int32_t>(rc);
1590 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001591 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001592
Shawn Willden50eb1b22016-01-21 12:41:23 -07001593 Blob keyBlob;
1594 String8 name8(name);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001595 rc = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
1596 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001597 *aidl_return = static_cast<int32_t>(rc);
1598 return Status::ok();
Shawn Willden50eb1b22016-01-21 12:41:23 -07001599 }
1600
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001601 KeyStoreServiceReturnCode error;
1602 auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1603 error = ret;
1604 if (!error.isOk()) {
1605 return;
1606 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001607 if (chain) {
1608 *chain = KeymasterCertificateChain(certChain);
1609 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001610 };
1611
1612 auto hidlKey = blob2hidlVec(keyBlob);
1613 auto& dev = mKeyStore->getDevice(keyBlob);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001614 rc = KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
1615 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001616 *aidl_return = static_cast<int32_t>(rc);
1617 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001618 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001619 *aidl_return = static_cast<int32_t>(error);
1620 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001621}
1622
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001623Status
1624KeyStoreService::attestDeviceIds(const KeymasterArguments& params,
1625 ::android::security::keymaster::KeymasterCertificateChain* chain,
1626 int32_t* aidl_return) {
1627 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001628
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001629 if (!checkAllowedOperationParams(params.getParameters())) {
1630 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1631 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001632 }
1633
1634 if (!isDeviceIdAttestationRequested(params)) {
1635 // There is an attestKey() method for attesting keys without device ID attestation.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001636 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1637 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001638 }
1639
1640 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1641 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1642 if (binder == 0) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001643 *aidl_return =
1644 static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::CANNOT_ATTEST_IDS));
1645 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001646 }
1647 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1648 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1649 IPCThreadState::self()->getCallingPid(), callingUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001650 *aidl_return =
1651 static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::CANNOT_ATTEST_IDS));
1652 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001653 }
1654
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001655 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001656 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1657 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001658 *aidl_return = static_cast<int32_t>(rc);
1659 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001660 }
1661
1662 // Generate temporary key.
1663 auto& dev = mKeyStore->getDevice();
1664 KeyStoreServiceReturnCode error;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001665 ::std::vector<uint8_t> hidlKey;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001666
1667 AuthorizationSet keyCharacteristics;
1668 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1669 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1670 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1671 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1672 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001673 auto generateHidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& hidlKeyBlob,
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001674 const KeyCharacteristics&) {
1675 error = ret;
1676 if (!error.isOk()) {
1677 return;
1678 }
1679 hidlKey = hidlKeyBlob;
1680 };
1681
1682 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(keyCharacteristics.hidl_data(), generateHidlCb));
1683 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001684 *aidl_return = static_cast<int32_t>(rc);
1685 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001686 }
1687 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001688 *aidl_return = static_cast<int32_t>(error);
1689 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001690 }
1691
1692 // Attest key and device IDs.
1693 auto attestHidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1694 error = ret;
1695 if (!error.isOk()) {
1696 return;
1697 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001698 *chain = ::android::security::keymaster::KeymasterCertificateChain(certChain);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001699 };
1700 KeyStoreServiceReturnCode attestationRc =
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001701 KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), attestHidlCb));
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001702
1703 // Delete temporary key.
1704 KeyStoreServiceReturnCode deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001705
1706 if (!attestationRc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001707 *aidl_return = static_cast<int32_t>(attestationRc);
1708 return Status::ok();
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001709 }
1710 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001711 *aidl_return = static_cast<int32_t>(error);
1712 return Status::ok();
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001713 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001714 *aidl_return = static_cast<int32_t>(deletionRc);
1715 return Status::ok();
Shawn Willden50eb1b22016-01-21 12:41:23 -07001716}
1717
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001718Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001719 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1720 mAuthTokenTable.onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001721 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1722 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001723}
1724
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001725/**
1726 * Prune the oldest pruneable operation.
1727 */
1728bool KeyStoreService::pruneOperation() {
1729 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1730 ALOGD("Trying to prune operation %p", oldest.get());
1731 size_t op_count_before_abort = mOperationMap.getOperationCount();
1732 // We mostly ignore errors from abort() because all we care about is whether at least
1733 // one operation has been removed.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001734 int32_t abort_error;
1735 abort(oldest, &abort_error);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001736 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1737 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1738 return false;
1739 }
1740 return true;
1741}
1742
1743/**
1744 * Get the effective target uid for a binder operation that takes an
1745 * optional uid as the target.
1746 */
1747uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1748 if (targetUid == UID_SELF) {
1749 return IPCThreadState::self()->getCallingUid();
1750 }
1751 return static_cast<uid_t>(targetUid);
1752}
1753
1754/**
1755 * Check if the caller of the current binder method has the required
1756 * permission and if acting on other uids the grants to do so.
1757 */
1758bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1759 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1760 pid_t spid = IPCThreadState::self()->getCallingPid();
1761 if (!has_permission(callingUid, permission, spid)) {
1762 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1763 return false;
1764 }
1765 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1766 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1767 return false;
1768 }
1769 return true;
1770}
1771
1772/**
1773 * Check if the caller of the current binder method has the required
1774 * permission and the target uid is the caller or the caller is system.
1775 */
1776bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1777 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1778 pid_t spid = IPCThreadState::self()->getCallingPid();
1779 if (!has_permission(callingUid, permission, spid)) {
1780 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1781 return false;
1782 }
1783 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1784}
1785
1786/**
1787 * Check if the caller of the current binder method has the required
1788 * permission or the target of the operation is the caller's uid. This is
1789 * for operation where the permission is only for cross-uid activity and all
1790 * uids are allowed to act on their own (ie: clearing all entries for a
1791 * given uid).
1792 */
1793bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1794 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1795 if (getEffectiveUid(targetUid) == callingUid) {
1796 return true;
1797 } else {
1798 return checkBinderPermission(permission, targetUid);
1799 }
1800}
1801
1802/**
1803 * Helper method to check that the caller has the required permission as
1804 * well as the keystore is in the unlocked state if checkUnlocked is true.
1805 *
1806 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1807 * otherwise the state of keystore when not unlocked and checkUnlocked is
1808 * true.
1809 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001810KeyStoreServiceReturnCode
1811KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1812 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001813 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001814 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001815 }
1816 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1817 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001818 // All State values coincide with ResponseCodes
1819 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001820 }
1821
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001822 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001823}
1824
1825bool KeyStoreService::isKeystoreUnlocked(State state) {
1826 switch (state) {
1827 case ::STATE_NO_ERROR:
1828 return true;
1829 case ::STATE_UNINITIALIZED:
1830 case ::STATE_LOCKED:
1831 return false;
1832 }
1833 return false;
1834}
1835
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001836/**
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001837 * Check that all KeyParameter's provided by the application are
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001838 * allowed. Any parameter that keystore adds itself should be disallowed here.
1839 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001840bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1841 for (size_t i = 0; i < params.size(); ++i) {
1842 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001843 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001844 case Tag::AUTH_TOKEN:
1845 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001846 return false;
1847 default:
1848 break;
1849 }
1850 }
1851 return true;
1852}
1853
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001854ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
1855 km_device_t* dev,
1856 const AuthorizationSet& params,
1857 KeyCharacteristics* out) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001858 ::std::vector<uint8_t> appId;
1859 ::std::vector<uint8_t> appData;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001860 for (auto param : params) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001861 if (param.tag == Tag::APPLICATION_ID) {
1862 appId = authorizationValue(TAG_APPLICATION_ID, param).value();
1863 } else if (param.tag == Tag::APPLICATION_DATA) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001864 appId = authorizationValue(TAG_APPLICATION_DATA, param).value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001865 }
1866 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001867 ErrorCode error = ErrorCode::OK;
1868
1869 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
1870 error = ret;
1871 if (error != ErrorCode::OK) {
1872 return;
1873 }
1874 if (out) *out = keyCharacteristics;
1875 };
1876
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001877 ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appId, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001878 if (rc != ErrorCode::OK) {
1879 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001880 }
1881 return error;
1882}
1883
1884/**
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001885 * Get the auth token for this operation from the auth token table.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001886 *
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001887 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
1888 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1889 * authorization token exists for that operation and
1890 * failOnTokenMissing is false.
1891 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1892 * token for the operation
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001893 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001894KeyStoreServiceReturnCode KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics,
1895 uint64_t handle, KeyPurpose purpose,
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001896 const HardwareAuthToken** authToken,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001897 bool failOnTokenMissing) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001898
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001899 AuthorizationSet allCharacteristics;
1900 for (size_t i = 0; i < characteristics.softwareEnforced.size(); i++) {
1901 allCharacteristics.push_back(characteristics.softwareEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001902 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001903 for (size_t i = 0; i < characteristics.teeEnforced.size(); i++) {
1904 allCharacteristics.push_back(characteristics.teeEnforced[i]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001905 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001906 AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
1907 allCharacteristics, KeyPurpose(purpose), handle, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001908 switch (err) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001909 case AuthTokenTable::OK:
1910 case AuthTokenTable::AUTH_NOT_REQUIRED:
1911 return ResponseCode::NO_ERROR;
1912 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1913 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
1914 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001915 ALOGE("getAuthToken failed: %d", err); // STOPSHIP: debug only, to be removed
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001916 return ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1917 case AuthTokenTable::OP_HANDLE_REQUIRED:
1918 return failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
1919 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001920 default:
1921 ALOGE("Unexpected FindAuthorization return value %d", err);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001922 return ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001923 }
1924}
1925
1926/**
1927 * Add the auth token for the operation to the param list if the operation
1928 * requires authorization. Uses the cached result in the OperationMap if available
1929 * otherwise gets the token from the AuthTokenTable and caches the result.
1930 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001931 * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001932 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
1933 * authenticated.
1934 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
1935 * operation token.
1936 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001937KeyStoreServiceReturnCode KeyStoreService::addOperationAuthTokenIfNeeded(const sp<IBinder>& token,
1938 AuthorizationSet* params) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001939 const HardwareAuthToken* authToken = nullptr;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001940 mOperationMap.getOperationAuthToken(token, &authToken);
1941 if (!authToken) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001942 km_device_t dev;
1943 uint64_t handle;
1944 const KeyCharacteristics* characteristics = nullptr;
1945 KeyPurpose purpose;
1946 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001947 if (!mOperationMap.getOperation(token, &handle, &keyid, &purpose, &dev, &characteristics)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001948 return ErrorCode::INVALID_OPERATION_HANDLE;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001949 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001950 auto result = getAuthToken(*characteristics, handle, purpose, &authToken);
1951 if (!result.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001952 return result;
1953 }
1954 if (authToken) {
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001955 mOperationMap.setOperationAuthToken(token, authToken);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001956 }
1957 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001958 addAuthTokenToParams(params, authToken);
1959 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001960}
1961
1962/**
1963 * Translate a result value to a legacy return value. All keystore errors are
1964 * preserved and keymaster errors become SYSTEM_ERRORs
1965 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001966KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001967 if (result > 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001968 return static_cast<ResponseCode>(result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001969 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001970 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001971}
1972
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001973static NullOr<const Algorithm&> getKeyAlgoritmFromKeyCharacteristics(
1974 const ::android::security::keymaster::KeyCharacteristics& characteristics) {
1975 for (size_t i = 0; i < characteristics.teeEnforced.getParameters().size(); ++i) {
1976 auto algo =
1977 authorizationValue(TAG_ALGORITHM, characteristics.teeEnforced.getParameters()[i]);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001978 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001979 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001980 for (size_t i = 0; i < characteristics.softwareEnforced.getParameters().size(); ++i) {
1981 auto algo =
1982 authorizationValue(TAG_ALGORITHM, characteristics.softwareEnforced.getParameters()[i]);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001983 if (algo.isOk()) return algo.value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001984 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001985 return {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001986}
1987
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001988void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001989 // All legacy keys are DIGEST_NONE/PAD_NONE.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001990 params->push_back(TAG_DIGEST, Digest::NONE);
1991 params->push_back(TAG_PADDING, PaddingMode::NONE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001992
1993 // Look up the algorithm of the key.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001994 ::android::security::keymaster::KeyCharacteristics characteristics;
1995 int32_t result;
1996 auto rc = getKeyCharacteristics(name, ::android::security::keymaster::KeymasterBlob(),
1997 ::android::security::keymaster::KeymasterBlob(), UID_SELF,
1998 &characteristics, &result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001999 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002000 ALOGE("Failed to get key characteristics");
2001 return;
2002 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002003 auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
2004 if (!algorithm.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002005 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
2006 return;
2007 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002008 params->push_back(TAG_ALGORITHM, algorithm.value());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002009}
2010
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002011KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
2012 const hidl_vec<uint8_t>& data,
2013 hidl_vec<uint8_t>* out,
2014 const hidl_vec<uint8_t>& signature,
2015 KeyPurpose purpose) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002016
2017 std::basic_stringstream<uint8_t> outBuffer;
2018 OperationResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002019 AuthorizationSet inArgs;
2020 addLegacyBeginParams(name, &inArgs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002021 sp<IBinder> appToken(new BBinder);
2022 sp<IBinder> token;
2023
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002024 begin(appToken, name, static_cast<int32_t>(purpose), true,
2025 KeymasterArguments(inArgs.hidl_data()), ::std::vector<uint8_t>(), UID_SELF, &result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002026 if (!result.resultCode.isOk()) {
2027 if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002028 ALOGW("Key not found");
2029 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002030 ALOGW("Error in begin: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002031 }
2032 return translateResultToLegacyResult(result.resultCode);
2033 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002034 inArgs.Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002035 token = result.token;
2036 size_t consumed = 0;
2037 size_t lastConsumed = 0;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002038 hidl_vec<uint8_t> data_view;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002039 do {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002040 data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002041 update(token, KeymasterArguments(inArgs.hidl_data()), data_view, &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002042 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002043 ALOGW("Error in update: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002044 return translateResultToLegacyResult(result.resultCode);
2045 }
2046 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002047 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002048 }
2049 lastConsumed = result.inputConsumed;
2050 consumed += lastConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002051 } while (consumed < data.size() && lastConsumed > 0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002052
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002053 if (consumed != data.size()) {
2054 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
2055 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002056 }
2057
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002058 finish(token, KeymasterArguments(inArgs.hidl_data()), signature, ::std::vector<uint8_t>(),
2059 &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002060 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002061 ALOGW("Error in finish: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002062 return translateResultToLegacyResult(result.resultCode);
2063 }
2064 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002065 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002066 }
2067
2068 if (out) {
2069 auto buf = outBuffer.str();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002070 out->resize(buf.size());
2071 memcpy(&(*out)[0], buf.data(), out->size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002072 }
2073
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002074 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002075}
2076
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002077KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
2078 const AuthorizationSet& params,
2079 Blob* blob) {
Shawn Willden98c59162016-03-20 09:10:18 -06002080 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
2081 String8 name8(name);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002082 KeyStoreServiceReturnCode responseCode =
2083 mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002084 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willden98c59162016-03-20 09:10:18 -06002085 return responseCode;
2086 }
Rubin Xu7675c9f2017-03-15 19:26:52 +00002087 ALOGI("upgradeKeyBlob %s %d", name8.string(), uid);
Shawn Willden98c59162016-03-20 09:10:18 -06002088
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002089 auto hidlKey = blob2hidlVec(*blob);
2090 auto& dev = mKeyStore->getDevice(*blob);
Shawn Willden98c59162016-03-20 09:10:18 -06002091
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002092 KeyStoreServiceReturnCode error;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002093 auto hidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& upgradedKeyBlob) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002094 error = ret;
2095 if (!error.isOk()) {
2096 return;
2097 }
2098
Janis Danisevskisaf7783f2017-09-21 11:29:47 -07002099 auto filename = mKeyStore->getBlobFileNameIfExists(name8, uid, ::TYPE_KEYMASTER_10);
2100 if (!filename.isOk()) {
2101 ALOGI("trying to upgrade a non existing blob");
2102 return;
2103 }
2104 error = mKeyStore->del(filename.value().string(), ::TYPE_ANY, get_user_id(uid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002105 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00002106 ALOGI("upgradeKeyBlob keystore->del failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002107 return;
2108 }
2109
2110 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
2111 0 /* infoLength */, ::TYPE_KEYMASTER_10);
2112 newBlob.setFallback(blob->isFallback());
2113 newBlob.setEncrypted(blob->isEncrypted());
Rubin Xu67899de2017-04-21 19:15:13 +01002114 newBlob.setSuperEncrypted(blob->isSuperEncrypted());
2115 newBlob.setCriticalToDeviceEncryption(blob->isCriticalToDeviceEncryption());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002116
Janis Danisevskisaf7783f2017-09-21 11:29:47 -07002117 error = mKeyStore->put(filename.value().string(), &newBlob, get_user_id(uid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002118 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00002119 ALOGI("upgradeKeyBlob keystore->put failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002120 return;
2121 }
2122
2123 // Re-read blob for caller. We can't use newBlob because writing it modified it.
2124 error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
2125 };
2126
2127 KeyStoreServiceReturnCode rc =
2128 KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
2129 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06002130 return rc;
2131 }
2132
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002133 return error;
Shawn Willden98c59162016-03-20 09:10:18 -06002134}
2135
Shawn Willdene2a7b522017-04-11 09:27:40 -06002136} // namespace keystore