blob: d59966f4db95531aa3acbb6d6fa8381c30ec8a27 [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
Pavel Grafovff311b42018-01-24 20:34:37 +000028#include <android-base/scopeguard.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010029#include <binder/IInterface.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070030#include <binder/IPCThreadState.h>
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +010031#include <binder/IPermissionController.h>
32#include <binder/IServiceManager.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000033#include <log/log_event_list.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070034
35#include <private/android_filesystem_config.h>
Pavel Grafovff311b42018-01-24 20:34:37 +000036#include <private/android_logger.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070037
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010038#include <android/hardware/keymaster/3.0/IHwKeymasterDevice.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070039
40#include "defaults.h"
Janis Danisevskis18f27ad2016-06-01 13:57:40 -070041#include "keystore_attestation_id.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010042#include "keystore_keymaster_enforcement.h"
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070043#include "keystore_utils.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010044#include <keystore/keystore_hidl_support.h>
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070045
Janis Danisevskis8f737ad2017-11-21 12:30:15 -080046#include <hardware/hw_auth_token.h>
47
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010048namespace keystore {
Shawn Willdend5a24e62017-02-28 13:53:24 -070049
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010050using namespace android;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070051
Shawn Willdene2a7b522017-04-11 09:27:40 -060052namespace {
53
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070054using ::android::binder::Status;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070055using android::security::KeystoreArg;
56using android::security::keymaster::ExportResult;
57using android::security::keymaster::KeymasterArguments;
58using android::security::keymaster::KeymasterBlob;
59using android::security::keymaster::KeymasterCertificateChain;
60using android::security::keymaster::OperationResult;
David Zeuthenc6eb7cd2017-11-27 11:33:55 -050061using ConfirmationResponseCode = android::hardware::confirmationui::V1_0::ResponseCode;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070062
Shawn Willdene2a7b522017-04-11 09:27:40 -060063constexpr size_t kMaxOperations = 15;
64constexpr double kIdRotationPeriod = 30 * 24 * 60 * 60; /* Thirty days, in seconds */
65const char* kTimestampFilePath = "timestamp";
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070066
67struct BIGNUM_Delete {
68 void operator()(BIGNUM* p) const { BN_free(p); }
69};
Janis Danisevskisccfff102017-05-01 11:02:51 -070070typedef std::unique_ptr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070071
Shawn Willdene2a7b522017-04-11 09:27:40 -060072bool containsTag(const hidl_vec<KeyParameter>& params, Tag tag) {
73 return params.end() != std::find_if(params.begin(), params.end(),
74 [&](auto& param) { return param.tag == tag; });
75}
76
Shawn Willdend5a24e62017-02-28 13:53:24 -070077bool isAuthenticationBound(const hidl_vec<KeyParameter>& params) {
78 return !containsTag(params, Tag::NO_AUTH_REQUIRED);
79}
80
Shawn Willdene2a7b522017-04-11 09:27:40 -060081std::pair<KeyStoreServiceReturnCode, bool> hadFactoryResetSinceIdRotation() {
82 struct stat sbuf;
83 if (stat(kTimestampFilePath, &sbuf) == 0) {
84 double diff_secs = difftime(time(NULL), sbuf.st_ctime);
85 return {ResponseCode::NO_ERROR, diff_secs < kIdRotationPeriod};
86 }
87
88 if (errno != ENOENT) {
89 ALOGE("Failed to stat \"timestamp\" file, with error %d", errno);
90 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
91 }
92
93 int fd = creat(kTimestampFilePath, 0600);
94 if (fd < 0) {
95 ALOGE("Couldn't create \"timestamp\" file, with error %d", errno);
96 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
97 }
98
99 if (close(fd)) {
100 ALOGE("Couldn't close \"timestamp\" file, with error %d", errno);
101 return {ResponseCode::SYSTEM_ERROR, false /* don't care */};
102 }
103
104 return {ResponseCode::NO_ERROR, true};
105}
106
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +0200107constexpr size_t KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE = 1024;
108
109KeyStoreServiceReturnCode updateParamsForAttestation(uid_t callingUid, AuthorizationSet* params) {
110 KeyStoreServiceReturnCode responseCode;
111 bool factoryResetSinceIdRotation;
112 std::tie(responseCode, factoryResetSinceIdRotation) = hadFactoryResetSinceIdRotation();
113
114 if (!responseCode.isOk()) return responseCode;
115 if (factoryResetSinceIdRotation) params->push_back(TAG_RESET_SINCE_ID_ROTATION);
116
117 auto asn1_attestation_id_result = security::gather_attestation_application_id(callingUid);
118 if (!asn1_attestation_id_result.isOk()) {
119 ALOGE("failed to gather attestation_id");
120 return ErrorCode::ATTESTATION_APPLICATION_ID_MISSING;
121 }
122 std::vector<uint8_t>& asn1_attestation_id = asn1_attestation_id_result;
123
124 /*
125 * The attestation application ID cannot be longer than
126 * KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE, so we truncate if too long.
127 */
128 if (asn1_attestation_id.size() > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
129 asn1_attestation_id.resize(KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE);
130 }
131
132 params->push_back(TAG_ATTESTATION_APPLICATION_ID, asn1_attestation_id);
133
134 return ResponseCode::NO_ERROR;
135}
136
Shawn Willdene2a7b522017-04-11 09:27:40 -0600137} // anonymous namespace
138
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700139void KeyStoreService::binderDied(const wp<IBinder>& who) {
140 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700141 for (const auto& token : operations) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700142 int32_t unused_result;
143 abort(token, &unused_result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700144 }
David Zeuthenc6eb7cd2017-11-27 11:33:55 -0500145 mConfirmationManager->binderDied(who);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700146}
147
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700148Status KeyStoreService::getState(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700149 if (!checkBinderPermission(P_GET_STATE)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700150 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
151 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700152 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700153 *aidl_return = mKeyStore->getState(userId);
154 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700155}
156
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700157Status KeyStoreService::get(const String16& name, int32_t uid, ::std::vector<uint8_t>* item) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700158 uid_t targetUid = getEffectiveUid(uid);
159 if (!checkBinderPermission(P_GET, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700160 // see keystore/keystore.h
161 return Status::fromServiceSpecificError(
162 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700163 }
164
165 String8 name8(name);
166 Blob keyBlob;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100167 KeyStoreServiceReturnCode rc =
168 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_GENERIC);
169 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700170 *item = ::std::vector<uint8_t>();
171 // Return empty array if key is not found
172 // TODO: consider having returned value nullable or parse exception on the client.
173 return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700174 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100175 auto resultBlob = blob2hidlVec(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700176 // The static_cast here is needed to prevent a move, forcing a deep copy.
177 if (item) *item = static_cast<const hidl_vec<uint8_t>&>(blob2hidlVec(keyBlob));
178 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700179}
180
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700181Status KeyStoreService::insert(const String16& name, const ::std::vector<uint8_t>& item,
182 int targetUid, int32_t flags, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700183 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700184 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700185 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100186 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700187 *aidl_return = static_cast<int32_t>(result);
188 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700189 }
190
191 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400192 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_GENERIC));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700193
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100194 Blob keyBlob(&item[0], item.size(), NULL, 0, ::TYPE_GENERIC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700195 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
196
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700197 *aidl_return =
198 static_cast<int32_t>(mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid)));
199 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700200}
201
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700202Status KeyStoreService::del(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700203 targetUid = getEffectiveUid(targetUid);
204 if (!checkBinderPermission(P_DELETE, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700205 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
206 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700207 }
208 String8 name8(name);
Rubin Xu7675c9f2017-03-15 19:26:52 +0000209 ALOGI("del %s %d", name8.string(), targetUid);
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700210 auto filename = mKeyStore->getBlobFileNameIfExists(name8, targetUid, ::TYPE_ANY);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700211 if (!filename.isOk()) {
212 *aidl_return = static_cast<int32_t>(ResponseCode::KEY_NOT_FOUND);
213 return Status::ok();
214 }
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700215
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700216 ResponseCode result =
217 mKeyStore->del(filename.value().string(), ::TYPE_ANY, get_user_id(targetUid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100218 if (result != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700219 *aidl_return = static_cast<int32_t>(result);
220 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400221 }
222
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700223 filename = mKeyStore->getBlobFileNameIfExists(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS);
224 if (filename.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700225 *aidl_return = static_cast<int32_t>(mKeyStore->del(
226 filename.value().string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid)));
227 return Status::ok();
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700228 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700229 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
230 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700231}
232
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700233Status KeyStoreService::exist(const String16& name, int targetUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700234 targetUid = getEffectiveUid(targetUid);
235 if (!checkBinderPermission(P_EXIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700236 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
237 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700238 }
239
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700240 auto filename = mKeyStore->getBlobFileNameIfExists(String8(name), targetUid, ::TYPE_ANY);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700241 *aidl_return = static_cast<int32_t>(filename.isOk() ? ResponseCode::NO_ERROR
242 : ResponseCode::KEY_NOT_FOUND);
243 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700244}
245
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700246Status KeyStoreService::list(const String16& prefix, int targetUid,
247 ::std::vector<::android::String16>* matches) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700248 targetUid = getEffectiveUid(targetUid);
249 if (!checkBinderPermission(P_LIST, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700250 return Status::fromServiceSpecificError(
251 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700252 }
253 const String8 prefix8(prefix);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400254 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid, TYPE_ANY));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700255 android::Vector<android::String16> matches_internal;
256 if (mKeyStore->list(filename, &matches_internal, get_user_id(targetUid)) !=
257 ResponseCode::NO_ERROR) {
258 return Status::fromServiceSpecificError(static_cast<int32_t>(ResponseCode::SYSTEM_ERROR));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700259 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700260 matches->clear();
261 for (size_t i = 0; i < matches_internal.size(); ++i) {
262 matches->push_back(matches_internal[i]);
263 }
264 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700265}
266
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700267Status KeyStoreService::reset(int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700268 if (!checkBinderPermission(P_RESET)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700269 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
270 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700271 }
272
273 uid_t callingUid = IPCThreadState::self()->getCallingUid();
274 mKeyStore->resetUser(get_user_id(callingUid), false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700275 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
276 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700277}
278
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700279Status KeyStoreService::onUserPasswordChanged(int32_t userId, const String16& password,
280 int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700281 if (!checkBinderPermission(P_PASSWORD)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700282 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
283 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700284 }
285
286 const String8 password8(password);
287 // Flush the auth token table to prevent stale tokens from sticking
288 // around.
289 mAuthTokenTable.Clear();
290
291 if (password.size() == 0) {
292 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
293 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700294 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
295 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700296 } else {
297 switch (mKeyStore->getState(userId)) {
298 case ::STATE_UNINITIALIZED: {
299 // generate master key, encrypt with password, write to file,
300 // initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700301 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
302 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700303 }
304 case ::STATE_NO_ERROR: {
305 // rewrite master key with new password.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700306 *aidl_return = static_cast<int32_t>(mKeyStore->writeMasterKey(password8, userId));
307 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700308 }
309 case ::STATE_LOCKED: {
310 ALOGE("Changing user %d's password while locked, clearing old encryption", userId);
311 mKeyStore->resetUser(userId, true);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700312 *aidl_return = static_cast<int32_t>(mKeyStore->initializeUser(password8, userId));
313 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700314 }
315 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700316 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
317 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700318 }
319}
320
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700321Status KeyStoreService::onUserAdded(int32_t userId, int32_t parentId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700322 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700323 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
324 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700325 }
326
327 // Sanity check that the new user has an empty keystore.
328 if (!mKeyStore->isEmpty(userId)) {
329 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
330 }
331 // Unconditionally clear the keystore, just to be safe.
332 mKeyStore->resetUser(userId, false);
333 if (parentId != -1) {
334 // This profile must share the same master key password as the parent profile. Because the
335 // password of the parent profile is not known here, the best we can do is copy the parent's
336 // master key and master key file. This makes this profile use the same master key as the
337 // parent profile, forever.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700338 *aidl_return = static_cast<int32_t>(mKeyStore->copyMasterKey(parentId, userId));
339 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700340 } else {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700341 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
342 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700343 }
344}
345
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700346Status KeyStoreService::onUserRemoved(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700347 if (!checkBinderPermission(P_USER_CHANGED)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700348 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
349 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700350 }
351
352 mKeyStore->resetUser(userId, false);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700353 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
354 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700355}
356
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700357Status KeyStoreService::lock(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700358 if (!checkBinderPermission(P_LOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700359 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
360 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700361 }
362
363 State state = mKeyStore->getState(userId);
364 if (state != ::STATE_NO_ERROR) {
365 ALOGD("calling lock in state: %d", state);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700366 *aidl_return = static_cast<int32_t>(ResponseCode(state));
367 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700368 }
369
370 mKeyStore->lock(userId);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700371 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
372 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700373}
374
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700375Status KeyStoreService::unlock(int32_t userId, const String16& pw, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700376 if (!checkBinderPermission(P_UNLOCK)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700377 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
378 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700379 }
380
381 State state = mKeyStore->getState(userId);
382 if (state != ::STATE_LOCKED) {
383 switch (state) {
384 case ::STATE_NO_ERROR:
385 ALOGI("calling unlock when already unlocked, ignoring.");
386 break;
387 case ::STATE_UNINITIALIZED:
388 ALOGE("unlock called on uninitialized keystore.");
389 break;
390 default:
391 ALOGE("unlock called on keystore in unknown state: %d", state);
392 break;
393 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700394 *aidl_return = static_cast<int32_t>(ResponseCode(state));
395 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700396 }
397
398 const String8 password8(pw);
399 // read master key, decrypt with password, initialize mMasterKey*.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700400 *aidl_return = static_cast<int32_t>(mKeyStore->readMasterKey(password8, userId));
401 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700402}
403
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700404Status KeyStoreService::isEmpty(int32_t userId, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700405 if (!checkBinderPermission(P_IS_EMPTY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700406 *aidl_return = static_cast<int32_t>(false);
407 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700408 }
409
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700410 *aidl_return = static_cast<int32_t>(mKeyStore->isEmpty(userId));
411 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700412}
413
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700414Status KeyStoreService::generate(const String16& name, int32_t targetUid, int32_t keyType,
415 int32_t keySize, int32_t flags,
416 const ::android::security::KeystoreArguments& keystoreArgs,
417 int32_t* aidl_return) {
418 const Vector<sp<KeystoreArg>>* args = &(keystoreArgs.getArguments());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700419 targetUid = getEffectiveUid(targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700420 KeyStoreServiceReturnCode result =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700421 checkBinderPermissionAndKeystoreState(P_INSERT, targetUid, flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100422 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700423 *aidl_return = static_cast<int32_t>(result);
424 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700425 }
426
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100427 keystore::AuthorizationSet params;
428 add_legacy_key_authorizations(keyType, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700429
430 switch (keyType) {
431 case EVP_PKEY_EC: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100432 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700433 if (keySize == -1) {
434 keySize = EC_DEFAULT_KEY_SIZE;
435 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
436 ALOGI("invalid key size %d", keySize);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700437 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
438 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700439 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100440 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700441 break;
442 }
443 case EVP_PKEY_RSA: {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100444 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700445 if (keySize == -1) {
446 keySize = RSA_DEFAULT_KEY_SIZE;
447 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
448 ALOGI("invalid key size %d", keySize);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700449 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
450 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700451 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100452 params.push_back(TAG_KEY_SIZE, keySize);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700453 unsigned long exponent = RSA_DEFAULT_EXPONENT;
454 if (args->size() > 1) {
455 ALOGI("invalid number of arguments: %zu", args->size());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700456 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
457 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700458 } else if (args->size() == 1) {
Chih-Hung Hsieh24b2a392016-07-28 10:35:24 -0700459 const sp<KeystoreArg>& expArg = args->itemAt(0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700460 if (expArg != NULL) {
461 Unique_BIGNUM pubExpBn(BN_bin2bn(
462 reinterpret_cast<const unsigned char*>(expArg->data()), expArg->size(), NULL));
463 if (pubExpBn.get() == NULL) {
464 ALOGI("Could not convert public exponent to BN");
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700465 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
466 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700467 }
468 exponent = BN_get_word(pubExpBn.get());
469 if (exponent == 0xFFFFFFFFL) {
470 ALOGW("cannot represent public exponent as a long value");
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700471 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
472 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700473 }
474 } else {
475 ALOGW("public exponent not read");
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700476 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
477 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700478 }
479 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100480 params.push_back(TAG_RSA_PUBLIC_EXPONENT, exponent);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700481 break;
482 }
483 default: {
484 ALOGW("Unsupported key type %d", keyType);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700485 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
486 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700487 }
488 }
489
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700490 int32_t aidl_result;
491 android::security::keymaster::KeyCharacteristics unused_characteristics;
492 auto rc = generateKey(name, KeymasterArguments(params.hidl_data()), ::std::vector<uint8_t>(),
493 targetUid, flags, &unused_characteristics, &aidl_result);
494 if (!KeyStoreServiceReturnCode(aidl_result).isOk()) {
495 ALOGW("generate failed: %d", int32_t(aidl_result));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700496 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700497 *aidl_return = aidl_result;
498 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700499}
500
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700501Status KeyStoreService::import_key(const String16& name, const ::std::vector<uint8_t>& data,
502 int targetUid, int32_t flags, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700503
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100504 const uint8_t* ptr = &data[0];
505
506 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, data.size()));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700507 if (!pkcs8.get()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700508 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
509 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700510 }
511 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
512 if (!pkey.get()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700513 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
514 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700515 }
516 int type = EVP_PKEY_type(pkey->type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100517 AuthorizationSet params;
518 add_legacy_key_authorizations(type, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700519 switch (type) {
520 case EVP_PKEY_RSA:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100521 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700522 break;
523 case EVP_PKEY_EC:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100524 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700525 break;
526 default:
527 ALOGW("Unsupported key type %d", type);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700528 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
529 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700530 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100531
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700532 int import_result;
533 auto rc = importKey(name, KeymasterArguments(params.hidl_data()),
534 static_cast<int32_t>(KeyFormat::PKCS8), data, targetUid, flags,
535 /*outCharacteristics*/ NULL, &import_result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100536
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700537 if (!KeyStoreServiceReturnCode(import_result).isOk()) {
538 ALOGW("importKey failed: %d", int32_t(import_result));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700539 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700540 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
541 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700542}
543
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700544Status KeyStoreService::sign(const String16& name, const ::std::vector<uint8_t>& data,
545 ::std::vector<uint8_t>* out) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700546 if (!checkBinderPermission(P_SIGN)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700547 return Status::fromServiceSpecificError(
548 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700549 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700550 hidl_vec<uint8_t> legacy_out;
551 KeyStoreServiceReturnCode res =
552 doLegacySignVerify(name, data, &legacy_out, hidl_vec<uint8_t>(), KeyPurpose::SIGN);
553 *out = legacy_out;
554 return Status::fromServiceSpecificError((res));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700555}
556
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700557Status KeyStoreService::verify(const String16& name, const ::std::vector<uint8_t>& data,
558 const ::std::vector<uint8_t>& signature, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700559 if (!checkBinderPermission(P_VERIFY)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700560 return Status::fromServiceSpecificError(
561 static_cast<int32_t>(ResponseCode::PERMISSION_DENIED));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700562 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700563 *aidl_return = static_cast<int32_t>(
564 doLegacySignVerify(name, data, nullptr, signature, KeyPurpose::VERIFY));
565 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700566}
567
568/*
569 * TODO: The abstraction between things stored in hardware and regular blobs
570 * of data stored on the filesystem should be moved down to keystore itself.
571 * Unfortunately the Java code that calls this has naming conventions that it
572 * knows about. Ideally keystore shouldn't be used to store random blobs of
573 * data.
574 *
575 * Until that happens, it's necessary to have a separate "get_pubkey" and
576 * "del_key" since the Java code doesn't really communicate what it's
577 * intentions are.
578 */
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700579Status KeyStoreService::get_pubkey(const String16& name, ::std::vector<uint8_t>* pubKey) {
580 android::security::keymaster::ExportResult result;
581 KeymasterBlob clientId;
582 KeymasterBlob appId;
583 exportKey(name, static_cast<int32_t>(KeyFormat::X509), clientId, appId, UID_SELF, &result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100584 if (!result.resultCode.isOk()) {
585 ALOGW("export failed: %d", int32_t(result.resultCode));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700586 return Status::fromServiceSpecificError(static_cast<int32_t>(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700587 }
588
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100589 if (pubKey) *pubKey = std::move(result.exportData);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700590 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700591}
592
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700593Status KeyStoreService::grant(const String16& name, int32_t granteeUid,
594 ::android::String16* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700595 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100596 auto result = checkBinderPermissionAndKeystoreState(P_GRANT);
597 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700598 *aidl_return = String16();
599 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700600 }
601
602 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400603 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700604
605 if (access(filename.string(), R_OK) == -1) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700606 *aidl_return = String16();
607 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700608 }
609
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700610 *aidl_return =
611 String16(mKeyStore->addGrant(String8(name).string(), callingUid, granteeUid).c_str());
612 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700613}
614
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700615Status KeyStoreService::ungrant(const String16& name, int32_t granteeUid, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700616 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700617 KeyStoreServiceReturnCode result = checkBinderPermissionAndKeystoreState(P_GRANT);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100618 if (!result.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700619 *aidl_return = static_cast<int32_t>(result);
620 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700621 }
622
623 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400624 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid, ::TYPE_ANY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700625
626 if (access(filename.string(), R_OK) == -1) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700627 *aidl_return = static_cast<int32_t>((errno != ENOENT) ? ResponseCode::SYSTEM_ERROR
628 : ResponseCode::KEY_NOT_FOUND);
629 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700630 }
631
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700632 *aidl_return = static_cast<int32_t>(mKeyStore->removeGrant(name8, callingUid, granteeUid)
633 ? ResponseCode::NO_ERROR
634 : ResponseCode::KEY_NOT_FOUND);
635 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700636}
637
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700638Status KeyStoreService::getmtime(const String16& name, int32_t uid, int64_t* time) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700639 uid_t targetUid = getEffectiveUid(uid);
640 if (!checkBinderPermission(P_GET, targetUid)) {
641 ALOGW("permission denied for %d: getmtime", targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700642 *time = -1L;
643 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700644 }
645
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700646 auto filename = mKeyStore->getBlobFileNameIfExists(String8(name), targetUid, ::TYPE_ANY);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700647
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700648 if (!filename.isOk()) {
649 ALOGW("could not access %s for getmtime", filename.value().string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700650 *time = -1L;
651 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700652 }
653
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700654 int fd = TEMP_FAILURE_RETRY(open(filename.value().string(), O_NOFOLLOW, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700655 if (fd < 0) {
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700656 ALOGW("could not open %s for getmtime", filename.value().string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700657 *time = -1L;
658 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700659 }
660
661 struct stat s;
662 int ret = fstat(fd, &s);
663 close(fd);
664 if (ret == -1) {
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700665 ALOGW("could not stat %s for getmtime", filename.value().string());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700666 *time = -1L;
667 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700668 }
669
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700670 *time = static_cast<int64_t>(s.st_mtime);
671 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700672}
673
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700674Status KeyStoreService::is_hardware_backed(const String16& keyType, int32_t* aidl_return) {
675 *aidl_return = static_cast<int32_t>(mKeyStore->isHardwareBacked(keyType) ? 1 : 0);
676 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700677}
678
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700679Status KeyStoreService::clear_uid(int64_t targetUid64, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700680 uid_t targetUid = getEffectiveUid(targetUid64);
681 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700682 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
683 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700684 }
Rubin Xu7675c9f2017-03-15 19:26:52 +0000685 ALOGI("clear_uid %" PRId64, targetUid64);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700686
Janis Danisevskisaf7783f2017-09-21 11:29:47 -0700687 mKeyStore->removeAllGrantsToUid(targetUid);
688
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700689 String8 prefix = String8::format("%u_", targetUid);
690 Vector<String16> aliases;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100691 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ResponseCode::NO_ERROR) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700692 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
693 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700694 }
695
696 for (uint32_t i = 0; i < aliases.size(); i++) {
697 String8 name8(aliases[i]);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400698 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_ANY));
Rubin Xu85c85e92017-04-26 20:07:30 +0100699
700 if (get_app_id(targetUid) == AID_SYSTEM) {
701 Blob keyBlob;
702 ResponseCode responseCode =
703 mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, get_user_id(targetUid));
704 if (responseCode == ResponseCode::NO_ERROR && keyBlob.isCriticalToDeviceEncryption()) {
705 // Do not clear keys critical to device encryption under system uid.
706 continue;
707 }
708 }
709
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700710 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400711
712 // del() will fail silently if no cached characteristics are present for this alias.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100713 String8 chr_filename(
714 mKeyStore->getKeyNameForUidWithDir(name8, targetUid, ::TYPE_KEY_CHARACTERISTICS));
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400715 mKeyStore->del(chr_filename.string(), ::TYPE_KEY_CHARACTERISTICS, get_user_id(targetUid));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700716 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700717 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
718 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700719}
720
Janis Danisevskisc1460142017-12-18 16:48:46 -0800721Status KeyStoreService::addRngEntropy(const ::std::vector<uint8_t>& entropy, int32_t flags,
722 int32_t* aidl_return) {
723 auto device = mKeyStore->getDevice(flagsToSecurityLevel(flags));
724 if (!device) {
725 *aidl_return = static_cast<int32_t>(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
726 } else {
727 *aidl_return = static_cast<int32_t>(
728 KeyStoreServiceReturnCode(KS_HANDLE_HIDL_ERROR(device->addRngEntropy(entropy))));
729 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700730 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700731}
732
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700733Status
734KeyStoreService::generateKey(const String16& name, const KeymasterArguments& params,
735 const ::std::vector<uint8_t>& entropy, int uid, int flags,
736 android::security::keymaster::KeyCharacteristics* outCharacteristics,
737 int32_t* aidl_return) {
Max Biresef4f0672017-11-29 14:38:48 -0800738 // TODO(jbires): remove this getCallingUid call upon implementation of b/25646100
739 uid_t originalUid = IPCThreadState::self()->getCallingUid();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700740 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000741 auto logOnScopeExit = android::base::make_scope_guard([&] {
742 if (__android_log_security()) {
743 android_log_event_list(SEC_TAG_AUTH_KEY_GENERATED)
744 << int32_t(*aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
745 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
746 }
747 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100748 KeyStoreServiceReturnCode rc =
749 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
750 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700751 *aidl_return = static_cast<int32_t>(rc);
752 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700753 }
Rubin Xu67899de2017-04-21 19:15:13 +0100754 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
755 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700756 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
757 return Status::ok();
Rubin Xu67899de2017-04-21 19:15:13 +0100758 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700759
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700760 if (containsTag(params.getParameters(), Tag::INCLUDE_UNIQUE_ID)) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -0700761 // TODO(jbires): remove uid checking upon implementation of b/25646100
Max Bires670467d2017-12-12 11:16:43 -0800762 if (!checkBinderPermission(P_GEN_UNIQUE_ID) ||
Max Biresef4f0672017-11-29 14:38:48 -0800763 originalUid != IPCThreadState::self()->getCallingUid()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700764 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
765 return Status::ok();
766 }
Shawn Willdene2a7b522017-04-11 09:27:40 -0600767 }
768
Janis Danisevskisc1460142017-12-18 16:48:46 -0800769 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
770 auto dev = mKeyStore->getDevice(securityLevel);
771 if (!dev) {
772 *aidl_return = static_cast<int32_t>(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
773 return Status::ok();
774 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700775 AuthorizationSet keyCharacteristics = params.getParameters();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400776
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700777 // TODO: Seed from Linux RNG before this.
Janis Danisevskisc1460142017-12-18 16:48:46 -0800778 rc = KS_HANDLE_HIDL_ERROR(dev->addRngEntropy(entropy));
779 if (!rc.isOk()) {
780 *aidl_return = static_cast<int32_t>(rc);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700781 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700782 }
783
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100784 KeyStoreServiceReturnCode error;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700785 auto hidl_cb = [&](ErrorCode ret, const ::std::vector<uint8_t>& hidlKeyBlob,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100786 const KeyCharacteristics& keyCharacteristics) {
787 error = ret;
788 if (!error.isOk()) {
789 return;
790 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700791 if (outCharacteristics)
792 *outCharacteristics =
793 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700794
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100795 // Write the key
796 String8 name8(name);
797 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700798
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100799 Blob keyBlob(&hidlKeyBlob[0], hidlKeyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800800 keyBlob.setSecurityLevel(securityLevel);
Rubin Xu67899de2017-04-21 19:15:13 +0100801 keyBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700802 if (isAuthenticationBound(params.getParameters()) &&
803 !keyBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -0700804 keyBlob.setSuperEncrypted(true);
805 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100806 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700807
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100808 error = mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
809 };
810
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700811 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(params.getParameters(), hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100812 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700813 *aidl_return = static_cast<int32_t>(rc);
814 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400815 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100816 if (!error.isOk()) {
817 ALOGE("Failed to generate key -> falling back to software keymaster");
Janis Danisevskisc1460142017-12-18 16:48:46 -0800818 securityLevel = SecurityLevel::SOFTWARE;
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000819 auto fallback = mKeyStore->getFallbackDevice();
Janis Danisevskisc1460142017-12-18 16:48:46 -0800820 if (!fallback) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700821 *aidl_return = static_cast<int32_t>(error);
822 return Status::ok();
Janis Danisevskise8ba1802017-01-30 10:49:51 +0000823 }
Janis Danisevskisc1460142017-12-18 16:48:46 -0800824 rc = KS_HANDLE_HIDL_ERROR(fallback->generateKey(params.getParameters(), hidl_cb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100825 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700826 *aidl_return = static_cast<int32_t>(rc);
827 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100828 }
829 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700830 *aidl_return = static_cast<int32_t>(error);
831 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100832 }
833 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400834
835 // Write the characteristics:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100836 String8 name8(name);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400837 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
838
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100839 std::stringstream kc_stream;
840 keyCharacteristics.Serialize(&kc_stream);
841 if (kc_stream.bad()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700842 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
843 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100844 }
845 auto kc_buf = kc_stream.str();
846 Blob charBlob(reinterpret_cast<const uint8_t*>(kc_buf.data()), kc_buf.size(), NULL, 0,
847 ::TYPE_KEY_CHARACTERISTICS);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800848 charBlob.setSecurityLevel(securityLevel);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400849 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
850
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700851 *aidl_return =
852 static_cast<int32_t>(mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid)));
853 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700854}
855
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700856Status KeyStoreService::getKeyCharacteristics(
857 const String16& name, const ::android::security::keymaster::KeymasterBlob& clientId,
858 const ::android::security::keymaster::KeymasterBlob& appId, int32_t uid,
859 ::android::security::keymaster::KeyCharacteristics* outCharacteristics, int32_t* aidl_return) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700860 if (!outCharacteristics) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700861 *aidl_return =
862 static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::UNEXPECTED_NULL_POINTER));
863 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700864 }
865
866 uid_t targetUid = getEffectiveUid(uid);
867 uid_t callingUid = IPCThreadState::self()->getCallingUid();
868 if (!is_granted_to(callingUid, targetUid)) {
869 ALOGW("uid %d not permitted to act for uid %d in getKeyCharacteristics", callingUid,
870 targetUid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700871 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
872 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700873 }
874
875 Blob keyBlob;
876 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700877
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100878 KeyStoreServiceReturnCode rc =
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700879 mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Janis Danisevskisd714a672017-09-01 14:31:36 -0700880 if (rc == ResponseCode::UNINITIALIZED) {
881 /*
882 * If we fail reading the blob because the master key is missing we try to retrieve the
883 * key characteristics from the characteristics file. This happens when auth-bound
884 * keys are used after a screen lock has been removed by the user.
885 */
886 rc = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
887 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700888 *aidl_return = static_cast<int32_t>(rc);
889 return Status::ok();
Janis Danisevskisd714a672017-09-01 14:31:36 -0700890 }
891 AuthorizationSet keyCharacteristics;
892 // TODO write one shot stream buffer to avoid copying (twice here)
893 std::string charBuffer(reinterpret_cast<const char*>(keyBlob.getValue()),
894 keyBlob.getLength());
895 std::stringstream charStream(charBuffer);
896 keyCharacteristics.Deserialize(&charStream);
897
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700898 outCharacteristics->softwareEnforced = KeymasterArguments(keyCharacteristics.hidl_data());
899 *aidl_return = static_cast<int32_t>(rc);
900 return Status::ok();
Janis Danisevskisd714a672017-09-01 14:31:36 -0700901 } else if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700902 *aidl_return = static_cast<int32_t>(rc);
903 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700904 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100905
906 auto hidlKeyBlob = blob2hidlVec(keyBlob);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800907 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100908
909 KeyStoreServiceReturnCode error;
910
911 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
912 error = ret;
913 if (!error.isOk()) {
Pavel Grafovcef39472018-02-12 18:45:02 +0000914 if (error == ErrorCode::INVALID_KEY_BLOB) {
915 log_key_integrity_violation(name8, targetUid);
916 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100917 return;
Shawn Willden98c59162016-03-20 09:10:18 -0600918 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700919 *outCharacteristics =
920 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100921 };
922
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700923 rc = KS_HANDLE_HIDL_ERROR(
924 dev->getKeyCharacteristics(hidlKeyBlob, clientId.getData(), appId.getData(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100925 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700926 *aidl_return = static_cast<int32_t>(rc);
927 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100928 }
929
930 if (error == ErrorCode::KEY_REQUIRES_UPGRADE) {
931 AuthorizationSet upgradeParams;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700932 if (clientId.getData().size()) {
933 upgradeParams.push_back(TAG_APPLICATION_ID, clientId.getData());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100934 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700935 if (appId.getData().size()) {
936 upgradeParams.push_back(TAG_APPLICATION_DATA, appId.getData());
Shawn Willden98c59162016-03-20 09:10:18 -0600937 }
938 rc = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100939 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700940 *aidl_return = static_cast<int32_t>(rc);
941 return Status::ok();
Shawn Willden98c59162016-03-20 09:10:18 -0600942 }
Shawn Willden715d0232016-01-21 00:45:13 -0700943
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100944 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
945
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700946 rc = KS_HANDLE_HIDL_ERROR(dev->getKeyCharacteristics(
947 upgradedHidlKeyBlob, clientId.getData(), appId.getData(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100948 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700949 *aidl_return = static_cast<int32_t>(rc);
950 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100951 }
952 // Note that, on success, "error" will have been updated by the hidlCB callback.
953 // So it is fine to return "error" below.
954 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700955 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(error));
956 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700957}
958
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700959Status
960KeyStoreService::importKey(const String16& name, const KeymasterArguments& params, int32_t format,
961 const ::std::vector<uint8_t>& keyData, int uid, int flags,
962 ::android::security::keymaster::KeyCharacteristics* outCharacteristics,
963 int32_t* aidl_return) {
964
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700965 uid = getEffectiveUid(uid);
Pavel Grafovff311b42018-01-24 20:34:37 +0000966 auto logOnScopeExit = android::base::make_scope_guard([&] {
967 if (__android_log_security()) {
968 android_log_event_list(SEC_TAG_KEY_IMPORTED)
969 << int32_t(*aidl_return == static_cast<int32_t>(ResponseCode::NO_ERROR))
970 << String8(name) << int32_t(uid) << LOG_ID_SECURITY;
971 }
972 });
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100973 KeyStoreServiceReturnCode rc =
974 checkBinderPermissionAndKeystoreState(P_INSERT, uid, flags & KEYSTORE_FLAG_ENCRYPTED);
975 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700976 *aidl_return = static_cast<int32_t>(rc);
977 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700978 }
Rubin Xu67899de2017-04-21 19:15:13 +0100979 if ((flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION) && get_app_id(uid) != AID_SYSTEM) {
980 ALOGE("Non-system uid %d cannot set FLAG_CRITICAL_TO_DEVICE_ENCRYPTION", uid);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700981 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
982 return Status::ok();
Rubin Xu67899de2017-04-21 19:15:13 +0100983 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700984
Janis Danisevskisc1460142017-12-18 16:48:46 -0800985 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
986 auto dev = mKeyStore->getDevice(securityLevel);
987 if (!dev) {
988 *aidl_return = static_cast<int32_t>(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
989 return Status::ok();
990 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700991
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700992 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700993
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100994 KeyStoreServiceReturnCode error;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700995
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700996 auto hidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& keyBlob,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100997 const KeyCharacteristics& keyCharacteristics) {
998 error = ret;
999 if (!error.isOk()) {
1000 return;
1001 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001002 if (outCharacteristics)
1003 *outCharacteristics =
1004 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001005
1006 // Write the key:
1007 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEYMASTER_10));
1008
1009 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001010 ksBlob.setSecurityLevel(securityLevel);
Rubin Xu67899de2017-04-21 19:15:13 +01001011 ksBlob.setCriticalToDeviceEncryption(flags & KEYSTORE_FLAG_CRITICAL_TO_DEVICE_ENCRYPTION);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001012 if (isAuthenticationBound(params.getParameters()) &&
1013 !ksBlob.isCriticalToDeviceEncryption()) {
Shawn Willdend5a24e62017-02-28 13:53:24 -07001014 ksBlob.setSuperEncrypted(true);
1015 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001016 ksBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1017
1018 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(uid));
1019 };
1020
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001021 rc = KS_HANDLE_HIDL_ERROR(
1022 dev->importKey(params.getParameters(), KeyFormat(format), keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001023 // possible hidl error
1024 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001025 *aidl_return = static_cast<int32_t>(rc);
1026 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001027 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001028 // now check error from callback
1029 if (!error.isOk()) {
1030 ALOGE("Failed to import key -> falling back to software keymaster");
Janis Danisevskisc1460142017-12-18 16:48:46 -08001031 securityLevel = SecurityLevel::SOFTWARE;
Janis Danisevskise8ba1802017-01-30 10:49:51 +00001032 auto fallback = mKeyStore->getFallbackDevice();
Janis Danisevskisc1460142017-12-18 16:48:46 -08001033 if (!fallback) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001034 *aidl_return = static_cast<int32_t>(error);
1035 return Status::ok();
Janis Danisevskise8ba1802017-01-30 10:49:51 +00001036 }
Janis Danisevskisc1460142017-12-18 16:48:46 -08001037 rc = KS_HANDLE_HIDL_ERROR(
1038 fallback->importKey(params.getParameters(), KeyFormat(format), keyData, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001039 // possible hidl error
1040 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001041 *aidl_return = static_cast<int32_t>(rc);
1042 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001043 }
1044 // now check error from callback
1045 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001046 *aidl_return = static_cast<int32_t>(error);
1047 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001048 }
1049 }
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001050
1051 // Write the characteristics:
1052 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(name8, uid, ::TYPE_KEY_CHARACTERISTICS));
1053
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001054 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001055 std::stringstream kcStream;
1056 opParams.Serialize(&kcStream);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001057 if (kcStream.bad()) {
1058 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
1059 return Status::ok();
1060 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001061 auto kcBuf = kcStream.str();
1062
1063 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
1064 ::TYPE_KEY_CHARACTERISTICS);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001065 charBlob.setSecurityLevel(securityLevel);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001066 charBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1067
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001068 *aidl_return =
1069 static_cast<int32_t>(mKeyStore->put(cFilename.string(), &charBlob, get_user_id(uid)));
1070
1071 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001072}
1073
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001074Status KeyStoreService::exportKey(const String16& name, int32_t format,
1075 const ::android::security::keymaster::KeymasterBlob& clientId,
1076 const ::android::security::keymaster::KeymasterBlob& appId,
1077 int32_t uid, ExportResult* result) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001078
1079 uid_t targetUid = getEffectiveUid(uid);
1080 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1081 if (!is_granted_to(callingUid, targetUid)) {
1082 ALOGW("uid %d not permitted to act for uid %d in exportKey", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001083 result->resultCode = ResponseCode::PERMISSION_DENIED;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001084 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001085 }
1086
1087 Blob keyBlob;
1088 String8 name8(name);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001089
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001090 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
1091 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001092 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001093 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001094
1095 auto key = blob2hidlVec(keyBlob);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001096 auto dev = mKeyStore->getDevice(keyBlob);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001097
1098 auto hidlCb = [&](ErrorCode ret, const ::android::hardware::hidl_vec<uint8_t>& keyMaterial) {
1099 result->resultCode = ret;
1100 if (!result->resultCode.isOk()) {
Pavel Grafovcef39472018-02-12 18:45:02 +00001101 if (result->resultCode == ErrorCode::INVALID_KEY_BLOB) {
1102 log_key_integrity_violation(name8, targetUid);
1103 }
Ji Wang2c142312016-10-14 17:21:10 +08001104 return;
1105 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001106 result->exportData = keyMaterial;
1107 };
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001108 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
1109 dev->exportKey(KeyFormat(format), key, clientId.getData(), appId.getData(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001110 // Overwrite result->resultCode only on HIDL error. Otherwise we want the result set in the
1111 // callback hidlCb.
1112 if (!rc.isOk()) {
1113 result->resultCode = rc;
Ji Wang2c142312016-10-14 17:21:10 +08001114 }
1115
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001116 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1117 AuthorizationSet upgradeParams;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001118 if (clientId.getData().size()) {
1119 upgradeParams.push_back(TAG_APPLICATION_ID, clientId.getData());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001120 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001121 if (appId.getData().size()) {
1122 upgradeParams.push_back(TAG_APPLICATION_DATA, appId.getData());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001123 }
1124 result->resultCode = upgradeKeyBlob(name, targetUid, upgradeParams, &keyBlob);
1125 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001126 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001127 }
1128
1129 auto upgradedHidlKeyBlob = blob2hidlVec(keyBlob);
1130
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001131 result->resultCode = KS_HANDLE_HIDL_ERROR(dev->exportKey(
1132 KeyFormat(format), upgradedHidlKeyBlob, clientId.getData(), appId.getData(), hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001133 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001134 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001135 }
1136 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001137 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001138}
1139
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001140Status KeyStoreService::begin(const sp<IBinder>& appToken, const String16& name, int32_t purpose,
1141 bool pruneable, const KeymasterArguments& params,
1142 const ::std::vector<uint8_t>& entropy, int32_t uid,
1143 OperationResult* result) {
Shawn Willden0329a822017-12-04 13:55:14 -07001144 auto keyPurpose = static_cast<KeyPurpose>(purpose);
1145
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001146 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1147 uid_t targetUid = getEffectiveUid(uid);
1148 if (!is_granted_to(callingUid, targetUid)) {
1149 ALOGW("uid %d not permitted to act for uid %d in begin", callingUid, targetUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001150 result->resultCode = ResponseCode::PERMISSION_DENIED;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001151 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001152 }
1153 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
1154 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001155 result->resultCode = ResponseCode::PERMISSION_DENIED;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001156 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001157 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001158 if (!checkAllowedOperationParams(params.getParameters())) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001159 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001160 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001161 }
Shawn Willden0329a822017-12-04 13:55:14 -07001162
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001163 Blob keyBlob;
1164 String8 name8(name);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001165 result->resultCode = mKeyStore->getKeyForName(&keyBlob, name8, targetUid, TYPE_KEYMASTER_10);
Shawn Willdend5a24e62017-02-28 13:53:24 -07001166 if (result->resultCode == ResponseCode::LOCKED && keyBlob.isSuperEncrypted()) {
1167 result->resultCode = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1168 }
Shawn Willden0329a822017-12-04 13:55:14 -07001169 if (!result->resultCode.isOk()) return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001170
1171 auto key = blob2hidlVec(keyBlob);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001172 auto dev = mKeyStore->getDevice(keyBlob);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001173 AuthorizationSet opParams = params.getParameters();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001174 KeyCharacteristics characteristics;
1175 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
1176
1177 if (result->resultCode == ErrorCode::KEY_REQUIRES_UPGRADE) {
1178 result->resultCode = upgradeKeyBlob(name, targetUid, opParams, &keyBlob);
1179 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001180 return Status::ok();
Shawn Willden98c59162016-03-20 09:10:18 -06001181 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001182 key = blob2hidlVec(keyBlob);
1183 result->resultCode = getOperationCharacteristics(key, &dev, opParams, &characteristics);
Shawn Willden98c59162016-03-20 09:10:18 -06001184 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001185 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001186 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001187 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001188
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001189 // Merge these characteristics with the ones cached when the key was generated or imported
1190 Blob charBlob;
1191 AuthorizationSet persistedCharacteristics;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001192 result->resultCode =
1193 mKeyStore->getKeyForName(&charBlob, name8, targetUid, TYPE_KEY_CHARACTERISTICS);
1194 if (result->resultCode.isOk()) {
1195 // TODO write one shot stream buffer to avoid copying (twice here)
1196 std::string charBuffer(reinterpret_cast<const char*>(charBlob.getValue()),
1197 charBlob.getLength());
1198 std::stringstream charStream(charBuffer);
1199 persistedCharacteristics.Deserialize(&charStream);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001200 } else {
1201 ALOGD("Unable to read cached characteristics for key");
1202 }
1203
1204 // Replace the sw_enforced set with those persisted to disk, minus hw_enforced
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001205 AuthorizationSet softwareEnforced = characteristics.softwareEnforced;
Shawn Willden0329a822017-12-04 13:55:14 -07001206 AuthorizationSet hardwareEnforced = characteristics.hardwareEnforced;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001207 persistedCharacteristics.Union(softwareEnforced);
Shawn Willden0329a822017-12-04 13:55:14 -07001208 persistedCharacteristics.Subtract(hardwareEnforced);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001209 characteristics.softwareEnforced = persistedCharacteristics.hidl_data();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001210
Shawn Willden0329a822017-12-04 13:55:14 -07001211 KeyStoreServiceReturnCode authResult;
1212 HardwareAuthToken authToken;
1213 std::tie(authResult, authToken) =
1214 getAuthToken(characteristics, 0 /* no challenge */, keyPurpose,
1215 /*failOnTokenMissing*/ false);
1216
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001217 // If per-operation auth is needed we need to begin the operation and
1218 // the client will need to authorize that operation before calling
1219 // update. Any other auth issues stop here.
Shawn Willden827243a2017-09-12 05:41:33 -06001220 if (!authResult.isOk() && authResult != ResponseCode::OP_AUTH_NEEDED) {
1221 result->resultCode = authResult;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001222 return Status::ok();
Shawn Willden827243a2017-09-12 05:41:33 -06001223 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001224
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001225 // Add entropy to the device first.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001226 if (entropy.size()) {
Janis Danisevskisc1460142017-12-18 16:48:46 -08001227 result->resultCode = KS_HANDLE_HIDL_ERROR(dev->addRngEntropy(entropy));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001228 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001229 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001230 }
1231 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001232
1233 // Create a keyid for this key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001234 km_id_t keyid;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001235 if (!enforcement_policy.CreateKeyId(key, &keyid)) {
1236 ALOGE("Failed to create a key ID for authorization checking.");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001237 result->resultCode = ErrorCode::UNKNOWN_ERROR;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001238 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001239 }
1240
1241 // Check that all key authorization policy requirements are met.
Shawn Willden0329a822017-12-04 13:55:14 -07001242 AuthorizationSet key_auths = characteristics.hardwareEnforced;
1243 key_auths.append(characteristics.softwareEnforced.begin(),
1244 characteristics.softwareEnforced.end());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001245
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001246 result->resultCode =
Shawn Willden0329a822017-12-04 13:55:14 -07001247 enforcement_policy.AuthorizeOperation(keyPurpose, keyid, key_auths, opParams, authToken,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001248 0 /* op_handle */, true /* is_begin_operation */);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001249 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001250 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001251 }
1252
Shawn Willdene2a7b522017-04-11 09:27:40 -06001253 // If there are more than kMaxOperations, abort the oldest operation that was started as
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001254 // pruneable.
Shawn Willdene2a7b522017-04-11 09:27:40 -06001255 while (mOperationMap.getOperationCount() >= kMaxOperations) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001256 ALOGD("Reached or exceeded concurrent operations limit");
1257 if (!pruneOperation()) {
1258 break;
1259 }
1260 }
1261
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001262 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
1263 uint64_t operationHandle) {
1264 result->resultCode = ret;
1265 if (!result->resultCode.isOk()) {
Pavel Grafovcef39472018-02-12 18:45:02 +00001266 if (result->resultCode == ErrorCode::INVALID_KEY_BLOB) {
1267 log_key_integrity_violation(name8, targetUid);
1268 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001269 return;
1270 }
1271 result->handle = operationHandle;
1272 result->outParams = outParams;
1273 };
1274
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001275 ErrorCode rc =
Shawn Willden0329a822017-12-04 13:55:14 -07001276 KS_HANDLE_HIDL_ERROR(dev->begin(keyPurpose, key, opParams.hidl_data(), authToken, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001277 if (rc != ErrorCode::OK) {
1278 ALOGW("Got error %d from begin()", rc);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001279 }
1280
1281 // If there are too many operations abort the oldest operation that was
1282 // started as pruneable and try again.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001283 while (rc == ErrorCode::TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
1284 ALOGW("Ran out of operation handles");
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001285 if (!pruneOperation()) {
1286 break;
1287 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001288 rc = KS_HANDLE_HIDL_ERROR(
Shawn Willden0329a822017-12-04 13:55:14 -07001289 dev->begin(keyPurpose, key, opParams.hidl_data(), authToken, hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001290 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001291 if (rc != ErrorCode::OK) {
1292 result->resultCode = rc;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001293 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001294 }
1295
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001296 // Note: The operation map takes possession of the contents of "characteristics".
1297 // It is safe to use characteristics after the following line but it will be empty.
Shawn Willden0329a822017-12-04 13:55:14 -07001298 sp<IBinder> operationToken = mOperationMap.addOperation(
1299 result->handle, keyid, keyPurpose, dev, appToken, std::move(characteristics), pruneable);
1300 assert(characteristics.hardwareEnforced.size() == 0);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001301 assert(characteristics.softwareEnforced.size() == 0);
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001302 result->token = operationToken;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001303
Shawn Willden0329a822017-12-04 13:55:14 -07001304 mOperationMap.setOperationAuthToken(operationToken, std::move(authToken));
1305
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001306 // Return the authentication lookup result. If this is a per operation
1307 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
1308 // application should get an auth token using the handle before the
1309 // first call to update, which will fail if keystore hasn't received the
1310 // auth token.
Shawn Willden2f96c792017-09-07 23:59:08 -06001311 if (result->resultCode == ErrorCode::OK) {
1312 result->resultCode = authResult;
1313 }
Shawn Willdenc5e8f362017-08-31 09:23:06 -06001314
1315 // Other result fields were set in the begin operation's callback.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001316 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001317}
1318
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001319void KeyStoreService::appendConfirmationTokenIfNeeded(const KeyCharacteristics& keyCharacteristics,
1320 std::vector<KeyParameter>* params) {
1321 if (!(containsTag(keyCharacteristics.softwareEnforced, Tag::TRUSTED_CONFIRMATION_REQUIRED) ||
1322 containsTag(keyCharacteristics.hardwareEnforced, Tag::TRUSTED_CONFIRMATION_REQUIRED))) {
1323 return;
1324 }
1325
1326 hidl_vec<uint8_t> confirmationToken = mConfirmationManager->getLatestConfirmationToken();
1327 if (confirmationToken.size() == 0) {
1328 return;
1329 }
1330
1331 params->push_back(
1332 Authorization(keymaster::TAG_CONFIRMATION_TOKEN, std::move(confirmationToken)));
1333 ALOGD("Appending confirmation token\n");
1334}
1335
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001336Status KeyStoreService::update(const sp<IBinder>& token, const KeymasterArguments& params,
1337 const ::std::vector<uint8_t>& data, OperationResult* result) {
1338 if (!checkAllowedOperationParams(params.getParameters())) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001339 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001340 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001341 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001342
1343 auto getOpResult = mOperationMap.getOperation(token);
1344 if (!getOpResult.isOk()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001345 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001346 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001347 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001348 const auto& op = getOpResult.value();
1349
Shawn Willden0329a822017-12-04 13:55:14 -07001350 HardwareAuthToken authToken;
1351 std::tie(result->resultCode, authToken) = getOperationAuthTokenIfNeeded(token);
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001352 if (!result->resultCode.isOk()) return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001353
1354 // Check that all key authorization policy requirements are met.
Shawn Willden0329a822017-12-04 13:55:14 -07001355 AuthorizationSet key_auths(op.characteristics.hardwareEnforced);
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001356 key_auths.append(op.characteristics.softwareEnforced.begin(),
1357 op.characteristics.softwareEnforced.end());
1358
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001359 result->resultCode = enforcement_policy.AuthorizeOperation(
Shawn Willden0329a822017-12-04 13:55:14 -07001360 op.purpose, op.keyid, key_auths, params.getParameters(), authToken, op.handle,
1361 false /* is_begin_operation */);
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001362 if (!result->resultCode.isOk()) return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001363
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001364 std::vector<KeyParameter> inParams = params.getParameters();
1365 appendConfirmationTokenIfNeeded(op.characteristics, &inParams);
1366
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001367 auto hidlCb = [&](ErrorCode ret, uint32_t inputConsumed,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001368 const hidl_vec<KeyParameter>& outParams,
1369 const ::std::vector<uint8_t>& output) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001370 result->resultCode = ret;
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001371 if (result->resultCode.isOk()) {
1372 result->inputConsumed = inputConsumed;
1373 result->outParams = outParams;
1374 result->data = output;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001375 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001376 };
1377
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001378 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
1379 op.device->update(op.handle, inParams, data, authToken, VerificationToken(), hidlCb));
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001380
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001381 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1382 // it if there was a communication error indicated by the ErrorCode.
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001383 if (!rc.isOk()) result->resultCode = rc;
1384
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001385 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001386}
1387
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001388Status KeyStoreService::finish(const sp<IBinder>& token, const KeymasterArguments& params,
1389 const ::std::vector<uint8_t>& signature,
1390 const ::std::vector<uint8_t>& entropy, OperationResult* result) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001391 auto getOpResult = mOperationMap.getOperation(token);
1392 if (!getOpResult.isOk()) {
1393 result->resultCode = ErrorCode::INVALID_OPERATION_HANDLE;
1394 return Status::ok();
1395 }
1396 const auto& op = std::move(getOpResult.value());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001397 if (!checkAllowedOperationParams(params.getParameters())) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001398 result->resultCode = ErrorCode::INVALID_ARGUMENT;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001399 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001400 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001401
Shawn Willden0329a822017-12-04 13:55:14 -07001402 HardwareAuthToken authToken;
1403 std::tie(result->resultCode, authToken) = getOperationAuthTokenIfNeeded(token);
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001404 if (!result->resultCode.isOk()) return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001405
1406 if (entropy.size()) {
Janis Danisevskisc1460142017-12-18 16:48:46 -08001407 result->resultCode = KS_HANDLE_HIDL_ERROR(op.device->addRngEntropy(entropy));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001408 if (!result->resultCode.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001409 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001410 }
1411 }
1412
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001413 // Check that all key authorization policy requirements are met.
Shawn Willden0329a822017-12-04 13:55:14 -07001414 AuthorizationSet key_auths(op.characteristics.hardwareEnforced);
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001415 key_auths.append(op.characteristics.softwareEnforced.begin(),
1416 op.characteristics.softwareEnforced.end());
1417
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001418 std::vector<KeyParameter> inParams = params.getParameters();
1419 appendConfirmationTokenIfNeeded(op.characteristics, &inParams);
1420
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001421 result->resultCode = enforcement_policy.AuthorizeOperation(
Shawn Willden0329a822017-12-04 13:55:14 -07001422 op.purpose, op.keyid, key_auths, params.getParameters(), authToken, op.handle,
1423 false /* is_begin_operation */);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001424 if (!result->resultCode.isOk()) return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001425
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001426 auto hidlCb = [&](ErrorCode ret, const hidl_vec<KeyParameter>& outParams,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001427 const ::std::vector<uint8_t>& output) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001428 result->resultCode = ret;
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001429 if (result->resultCode.isOk()) {
1430 result->outParams = outParams;
1431 result->data = output;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001432 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001433 };
1434
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001435 KeyStoreServiceReturnCode rc = KS_HANDLE_HIDL_ERROR(
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001436 op.device->finish(op.handle, inParams,
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001437 ::std::vector<uint8_t>() /* TODO(swillden): wire up input to finish() */,
Shawn Willden0329a822017-12-04 13:55:14 -07001438 signature, authToken, VerificationToken(), hidlCb));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001439 mOperationMap.removeOperation(token);
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001440 mAuthTokenTable.MarkCompleted(op.handle);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001441
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001442 // just a reminder: on success result->resultCode was set in the callback. So we only overwrite
1443 // it if there was a communication error indicated by the ErrorCode.
1444 if (!rc.isOk()) {
1445 result->resultCode = rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001446 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001447 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001448}
1449
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001450Status KeyStoreService::abort(const sp<IBinder>& token, int32_t* aidl_return) {
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001451 auto getOpResult = mOperationMap.removeOperation(token);
1452 if (!getOpResult.isOk()) {
1453 *aidl_return = static_cast<int32_t>(ErrorCode::INVALID_OPERATION_HANDLE);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001454 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001455 }
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001456 auto op = std::move(getOpResult.value());
1457 mAuthTokenTable.MarkCompleted(op.handle);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001458
Shawn Willdenda6dcc32017-12-03 14:56:05 -07001459 ErrorCode error_code = KS_HANDLE_HIDL_ERROR(op.device->abort(op.handle));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001460 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(error_code));
1461 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001462}
1463
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001464Status KeyStoreService::isOperationAuthorized(const sp<IBinder>& token, bool* aidl_return) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001465 AuthorizationSet ignored;
Shawn Willden0329a822017-12-04 13:55:14 -07001466 KeyStoreServiceReturnCode rc;
1467 std::tie(rc, std::ignore) = getOperationAuthTokenIfNeeded(token);
1468 *aidl_return = rc.isOk();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001469 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001470}
1471
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001472Status KeyStoreService::addAuthToken(const ::std::vector<uint8_t>& authTokenAsVector,
Brian Youngccb492d2018-02-22 23:36:01 +00001473 int32_t* aidl_return) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001474
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001475 // TODO(swillden): When gatekeeper and fingerprint are ready, this should be updated to
1476 // receive a HardwareAuthToken, rather than an opaque byte array.
1477
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001478 if (!checkBinderPermission(P_ADD_AUTH)) {
1479 ALOGW("addAuthToken: permission denied for %d", IPCThreadState::self()->getCallingUid());
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001480 *aidl_return = static_cast<int32_t>(ResponseCode::PERMISSION_DENIED);
1481 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001482 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001483 if (authTokenAsVector.size() != sizeof(hw_auth_token_t)) {
1484 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1485 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001486 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001487
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001488 hw_auth_token_t authToken;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001489 memcpy(reinterpret_cast<void*>(&authToken), authTokenAsVector.data(), sizeof(hw_auth_token_t));
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001490 if (authToken.version != 0) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001491 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1492 return Status::ok();
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001493 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001494
Shawn Willden0329a822017-12-04 13:55:14 -07001495 mAuthTokenTable.AddAuthenticationToken(hidlVec2AuthToken(hidl_vec<uint8_t>(authTokenAsVector)));
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001496 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1497 return Status::ok();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001498}
1499
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001500bool isDeviceIdAttestationRequested(const KeymasterArguments& params) {
1501 const hardware::hidl_vec<KeyParameter> paramsVec = params.getParameters();
1502 for (size_t i = 0; i < paramsVec.size(); ++i) {
1503 switch (paramsVec[i].tag) {
Shawn Willdene2a7b522017-04-11 09:27:40 -06001504 case Tag::ATTESTATION_ID_BRAND:
1505 case Tag::ATTESTATION_ID_DEVICE:
1506 case Tag::ATTESTATION_ID_IMEI:
1507 case Tag::ATTESTATION_ID_MANUFACTURER:
1508 case Tag::ATTESTATION_ID_MEID:
1509 case Tag::ATTESTATION_ID_MODEL:
1510 case Tag::ATTESTATION_ID_PRODUCT:
1511 case Tag::ATTESTATION_ID_SERIAL:
1512 return true;
1513 default:
1514 break;
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001515 }
1516 }
1517 return false;
1518}
1519
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001520Status KeyStoreService::attestKey(const String16& name, const KeymasterArguments& params,
1521 ::android::security::keymaster::KeymasterCertificateChain* chain,
1522 int32_t* aidl_return) {
1523 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
1524 if (!checkAllowedOperationParams(params.getParameters())) {
1525 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1526 return Status::ok();
Shawn Willden50eb1b22016-01-21 12:41:23 -07001527 }
1528
Eran Messerie2c34152017-12-21 21:01:22 +00001529 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1530
1531 if (isDeviceIdAttestationRequested(params) && (callingUid != AID_SYSTEM)) {
1532 // Only the system context may request Device ID attestation combined with key attestation.
1533 // Otherwise, There is a dedicated attestDeviceIds() method for device ID attestation.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001534 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1535 return Status::ok();
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001536 }
1537
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001538 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001539 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1540 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001541 *aidl_return = static_cast<int32_t>(rc);
1542 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001543 }
Shawn Willdene2a7b522017-04-11 09:27:40 -06001544
Shawn Willden50eb1b22016-01-21 12:41:23 -07001545 Blob keyBlob;
1546 String8 name8(name);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001547 rc = mKeyStore->getKeyForName(&keyBlob, name8, callingUid, TYPE_KEYMASTER_10);
1548 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001549 *aidl_return = static_cast<int32_t>(rc);
1550 return Status::ok();
Shawn Willden50eb1b22016-01-21 12:41:23 -07001551 }
1552
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001553 KeyStoreServiceReturnCode error;
1554 auto hidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1555 error = ret;
1556 if (!error.isOk()) {
1557 return;
1558 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001559 if (chain) {
1560 *chain = KeymasterCertificateChain(certChain);
1561 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001562 };
1563
1564 auto hidlKey = blob2hidlVec(keyBlob);
Janis Danisevskisc1460142017-12-18 16:48:46 -08001565 auto dev = mKeyStore->getDevice(keyBlob);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001566 rc = KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), hidlCb));
1567 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001568 *aidl_return = static_cast<int32_t>(rc);
1569 return Status::ok();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001570 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001571 *aidl_return = static_cast<int32_t>(error);
1572 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001573}
1574
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001575Status
1576KeyStoreService::attestDeviceIds(const KeymasterArguments& params,
1577 ::android::security::keymaster::KeymasterCertificateChain* chain,
1578 int32_t* aidl_return) {
1579 // check null output if method signature is updated and return ErrorCode::OUTPUT_PARAMETER_NULL
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001580
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001581 if (!checkAllowedOperationParams(params.getParameters())) {
1582 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1583 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001584 }
1585
1586 if (!isDeviceIdAttestationRequested(params)) {
1587 // There is an attestKey() method for attesting keys without device ID attestation.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001588 *aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::INVALID_ARGUMENT));
1589 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001590 }
1591
1592 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1593 sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
1594 if (binder == 0) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001595 *aidl_return =
1596 static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::CANNOT_ATTEST_IDS));
1597 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001598 }
1599 if (!interface_cast<IPermissionController>(binder)->checkPermission(
1600 String16("android.permission.READ_PRIVILEGED_PHONE_STATE"),
1601 IPCThreadState::self()->getCallingPid(), callingUid)) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001602 *aidl_return =
1603 static_cast<int32_t>(KeyStoreServiceReturnCode(ErrorCode::CANNOT_ATTEST_IDS));
1604 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001605 }
1606
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001607 AuthorizationSet mutableParams = params.getParameters();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001608 KeyStoreServiceReturnCode rc = updateParamsForAttestation(callingUid, &mutableParams);
1609 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001610 *aidl_return = static_cast<int32_t>(rc);
1611 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001612 }
1613
1614 // Generate temporary key.
Janis Danisevskisc1460142017-12-18 16:48:46 -08001615 sp<Keymaster> dev;
1616 SecurityLevel securityLevel;
1617 std::tie(dev, securityLevel) = mKeyStore->getMostSecureDevice();
1618
1619 if (securityLevel == SecurityLevel::SOFTWARE) {
1620 *aidl_return = static_cast<int32_t>(ResponseCode::SYSTEM_ERROR);
1621 return Status::ok();
1622 }
1623
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001624 KeyStoreServiceReturnCode error;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001625 ::std::vector<uint8_t> hidlKey;
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001626
1627 AuthorizationSet keyCharacteristics;
1628 keyCharacteristics.push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
1629 keyCharacteristics.push_back(TAG_ALGORITHM, Algorithm::EC);
1630 keyCharacteristics.push_back(TAG_DIGEST, Digest::SHA_2_256);
1631 keyCharacteristics.push_back(TAG_NO_AUTH_REQUIRED);
1632 keyCharacteristics.push_back(TAG_EC_CURVE, EcCurve::P_256);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001633 auto generateHidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& hidlKeyBlob,
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001634 const KeyCharacteristics&) {
1635 error = ret;
1636 if (!error.isOk()) {
1637 return;
1638 }
1639 hidlKey = hidlKeyBlob;
1640 };
1641
1642 rc = KS_HANDLE_HIDL_ERROR(dev->generateKey(keyCharacteristics.hidl_data(), generateHidlCb));
1643 if (!rc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001644 *aidl_return = static_cast<int32_t>(rc);
1645 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001646 }
1647 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001648 *aidl_return = static_cast<int32_t>(error);
1649 return Status::ok();
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001650 }
1651
1652 // Attest key and device IDs.
1653 auto attestHidlCb = [&](ErrorCode ret, const hidl_vec<hidl_vec<uint8_t>>& certChain) {
1654 error = ret;
1655 if (!error.isOk()) {
1656 return;
1657 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001658 *chain = ::android::security::keymaster::KeymasterCertificateChain(certChain);
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001659 };
1660 KeyStoreServiceReturnCode attestationRc =
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001661 KS_HANDLE_HIDL_ERROR(dev->attestKey(hidlKey, mutableParams.hidl_data(), attestHidlCb));
Bartosz Fabianowski5aa93e02017-04-24 13:54:49 +02001662
1663 // Delete temporary key.
1664 KeyStoreServiceReturnCode deletionRc = KS_HANDLE_HIDL_ERROR(dev->deleteKey(hidlKey));
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001665
1666 if (!attestationRc.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001667 *aidl_return = static_cast<int32_t>(attestationRc);
1668 return Status::ok();
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001669 }
1670 if (!error.isOk()) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001671 *aidl_return = static_cast<int32_t>(error);
1672 return Status::ok();
Bartosz Fabianowskia9452d92017-01-23 22:21:11 +01001673 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001674 *aidl_return = static_cast<int32_t>(deletionRc);
1675 return Status::ok();
Shawn Willden50eb1b22016-01-21 12:41:23 -07001676}
1677
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001678Status KeyStoreService::onDeviceOffBody(int32_t* aidl_return) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001679 // TODO(tuckeris): add permission check. This should be callable from ClockworkHome only.
1680 mAuthTokenTable.onDeviceOffBody();
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001681 *aidl_return = static_cast<int32_t>(ResponseCode::NO_ERROR);
1682 return Status::ok();
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -04001683}
1684
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001685#define AIDL_RETURN(rc) \
1686 (*_aidl_return = static_cast<int32_t>(KeyStoreServiceReturnCode(rc)), Status::ok())
1687
1688Status KeyStoreService::importWrappedKey(
1689 const ::android::String16& wrappedKeyAlias, const ::std::vector<uint8_t>& wrappedKey,
1690 const ::android::String16& wrappingKeyAlias, const ::std::vector<uint8_t>& maskingKey,
1691 const KeymasterArguments& params, int64_t rootSid, int64_t fingerprintSid,
1692 ::android::security::keymaster::KeyCharacteristics* outCharacteristics, int32_t* _aidl_return) {
1693
1694 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1695
1696 if (!checkBinderPermission(P_INSERT, callingUid)) {
1697 return AIDL_RETURN(ResponseCode::PERMISSION_DENIED);
1698 }
1699
1700 Blob wrappingKeyBlob;
1701 String8 wrappingKeyName8(wrappingKeyAlias);
1702 KeyStoreServiceReturnCode rc =
1703 mKeyStore->getKeyForName(&wrappingKeyBlob, wrappingKeyName8, callingUid, TYPE_KEYMASTER_10);
1704 if (!rc.isOk()) {
1705 return AIDL_RETURN(rc);
1706 }
1707
1708 SecurityLevel securityLevel = wrappingKeyBlob.getSecurityLevel();
1709 auto dev = mKeyStore->getDevice(securityLevel);
1710 if (!dev) {
1711 return AIDL_RETURN(ErrorCode::HARDWARE_TYPE_UNAVAILABLE);
1712 }
1713
1714 auto hidlWrappingKey = blob2hidlVec(wrappingKeyBlob);
1715 String8 wrappedKeyAlias8(wrappedKeyAlias);
1716
1717 KeyStoreServiceReturnCode error;
1718
1719 auto hidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& keyBlob,
1720 const KeyCharacteristics& keyCharacteristics) {
1721 error = ret;
1722 if (!error.isOk()) {
1723 return;
1724 }
1725 if (outCharacteristics) {
1726 *outCharacteristics =
1727 ::android::security::keymaster::KeyCharacteristics(keyCharacteristics);
1728 }
1729
1730 // Write the key:
1731 String8 filename(
1732 mKeyStore->getKeyNameForUidWithDir(wrappedKeyAlias8, callingUid, ::TYPE_KEYMASTER_10));
1733
1734 Blob ksBlob(&keyBlob[0], keyBlob.size(), NULL, 0, ::TYPE_KEYMASTER_10);
1735 ksBlob.setSecurityLevel(securityLevel);
1736
1737 if (containsTag(keyCharacteristics.hardwareEnforced, Tag::USER_SECURE_ID)) {
1738 ksBlob.setSuperEncrypted(true);
1739 }
1740
1741 error = mKeyStore->put(filename.string(), &ksBlob, get_user_id(callingUid));
1742 };
1743
Shawn Willden0a198a02018-01-19 13:36:31 -07001744 rc = KS_HANDLE_HIDL_ERROR(dev->importWrappedKey(wrappedKey, hidlWrappingKey, maskingKey,
1745 params.getParameters(), rootSid, fingerprintSid,
1746 hidlCb));
1747
Janis Danisevskiscb9267d2017-12-19 16:27:52 -08001748 // possible hidl error
1749 if (!rc.isOk()) {
1750 return AIDL_RETURN(rc);
1751 }
1752 // now check error from callback
1753 if (!error.isOk()) {
1754 return AIDL_RETURN(error);
1755 }
1756
1757 // Write the characteristics:
1758 String8 cFilename(mKeyStore->getKeyNameForUidWithDir(wrappedKeyAlias8, callingUid,
1759 ::TYPE_KEY_CHARACTERISTICS));
1760
1761 AuthorizationSet opParams = params.getParameters();
1762 std::stringstream kcStream;
1763 opParams.Serialize(&kcStream);
1764 if (kcStream.bad()) {
1765 return AIDL_RETURN(ResponseCode::SYSTEM_ERROR);
1766 }
1767 auto kcBuf = kcStream.str();
1768
1769 Blob charBlob(reinterpret_cast<const uint8_t*>(kcBuf.data()), kcBuf.size(), NULL, 0,
1770 ::TYPE_KEY_CHARACTERISTICS);
1771 charBlob.setSecurityLevel(securityLevel);
1772
1773 return AIDL_RETURN(mKeyStore->put(cFilename.string(), &charBlob, get_user_id(callingUid)));
1774}
1775
David Zeuthenc6eb7cd2017-11-27 11:33:55 -05001776Status KeyStoreService::presentConfirmationPrompt(const sp<IBinder>& listener,
1777 const String16& promptText,
1778 const ::std::vector<uint8_t>& extraData,
1779 const String16& locale, int32_t uiOptionsAsFlags,
1780 int32_t* aidl_return) {
1781 return mConfirmationManager->presentConfirmationPrompt(listener, promptText, extraData, locale,
1782 uiOptionsAsFlags, aidl_return);
1783}
1784
1785Status KeyStoreService::cancelConfirmationPrompt(const sp<IBinder>& listener,
1786 int32_t* aidl_return) {
1787 return mConfirmationManager->cancelConfirmationPrompt(listener, aidl_return);
1788}
1789
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001790/**
1791 * Prune the oldest pruneable operation.
1792 */
1793bool KeyStoreService::pruneOperation() {
1794 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
1795 ALOGD("Trying to prune operation %p", oldest.get());
1796 size_t op_count_before_abort = mOperationMap.getOperationCount();
1797 // We mostly ignore errors from abort() because all we care about is whether at least
1798 // one operation has been removed.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001799 int32_t abort_error;
1800 abort(oldest, &abort_error);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001801 if (mOperationMap.getOperationCount() >= op_count_before_abort) {
1802 ALOGE("Failed to abort pruneable operation %p, error: %d", oldest.get(), abort_error);
1803 return false;
1804 }
1805 return true;
1806}
1807
1808/**
1809 * Get the effective target uid for a binder operation that takes an
1810 * optional uid as the target.
1811 */
1812uid_t KeyStoreService::getEffectiveUid(int32_t targetUid) {
1813 if (targetUid == UID_SELF) {
1814 return IPCThreadState::self()->getCallingUid();
1815 }
1816 return static_cast<uid_t>(targetUid);
1817}
1818
1819/**
1820 * Check if the caller of the current binder method has the required
1821 * permission and if acting on other uids the grants to do so.
1822 */
1823bool KeyStoreService::checkBinderPermission(perm_t permission, int32_t targetUid) {
1824 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1825 pid_t spid = IPCThreadState::self()->getCallingPid();
1826 if (!has_permission(callingUid, permission, spid)) {
1827 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1828 return false;
1829 }
1830 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
1831 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
1832 return false;
1833 }
1834 return true;
1835}
1836
1837/**
1838 * Check if the caller of the current binder method has the required
1839 * permission and the target uid is the caller or the caller is system.
1840 */
1841bool KeyStoreService::checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
1842 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1843 pid_t spid = IPCThreadState::self()->getCallingPid();
1844 if (!has_permission(callingUid, permission, spid)) {
1845 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
1846 return false;
1847 }
1848 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
1849}
1850
1851/**
1852 * Check if the caller of the current binder method has the required
1853 * permission or the target of the operation is the caller's uid. This is
1854 * for operation where the permission is only for cross-uid activity and all
1855 * uids are allowed to act on their own (ie: clearing all entries for a
1856 * given uid).
1857 */
1858bool KeyStoreService::checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
1859 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1860 if (getEffectiveUid(targetUid) == callingUid) {
1861 return true;
1862 } else {
1863 return checkBinderPermission(permission, targetUid);
1864 }
1865}
1866
1867/**
1868 * Helper method to check that the caller has the required permission as
1869 * well as the keystore is in the unlocked state if checkUnlocked is true.
1870 *
1871 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
1872 * otherwise the state of keystore when not unlocked and checkUnlocked is
1873 * true.
1874 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001875KeyStoreServiceReturnCode
1876KeyStoreService::checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid,
1877 bool checkUnlocked) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001878 if (!checkBinderPermission(permission, targetUid)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001879 return ResponseCode::PERMISSION_DENIED;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001880 }
1881 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
1882 if (checkUnlocked && !isKeystoreUnlocked(state)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001883 // All State values coincide with ResponseCodes
1884 return static_cast<ResponseCode>(state);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001885 }
1886
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001887 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001888}
1889
1890bool KeyStoreService::isKeystoreUnlocked(State state) {
1891 switch (state) {
1892 case ::STATE_NO_ERROR:
1893 return true;
1894 case ::STATE_UNINITIALIZED:
1895 case ::STATE_LOCKED:
1896 return false;
1897 }
1898 return false;
1899}
1900
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001901/**
Shawn Willden0329a822017-12-04 13:55:14 -07001902 * Check that all KeyParameters provided by the application are allowed. Any parameter that keystore
1903 * adds itself should be disallowed here.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001904 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001905bool KeyStoreService::checkAllowedOperationParams(const hidl_vec<KeyParameter>& params) {
1906 for (size_t i = 0; i < params.size(); ++i) {
1907 switch (params[i].tag) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001908 case Tag::ATTESTATION_APPLICATION_ID:
Shawn Willdene2a7b522017-04-11 09:27:40 -06001909 case Tag::RESET_SINCE_ID_ROTATION:
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001910 return false;
1911 default:
1912 break;
1913 }
1914 }
1915 return true;
1916}
1917
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001918ErrorCode KeyStoreService::getOperationCharacteristics(const hidl_vec<uint8_t>& key,
Shawn Willdenc67a8aa2017-12-03 17:51:29 -07001919 sp<Keymaster>* dev,
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001920 const AuthorizationSet& params,
1921 KeyCharacteristics* out) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001922 ::std::vector<uint8_t> appId;
1923 ::std::vector<uint8_t> appData;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001924 for (auto param : params) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001925 if (param.tag == Tag::APPLICATION_ID) {
1926 appId = authorizationValue(TAG_APPLICATION_ID, param).value();
1927 } else if (param.tag == Tag::APPLICATION_DATA) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001928 appId = authorizationValue(TAG_APPLICATION_DATA, param).value();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001929 }
1930 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001931 ErrorCode error = ErrorCode::OK;
1932
1933 auto hidlCb = [&](ErrorCode ret, const KeyCharacteristics& keyCharacteristics) {
1934 error = ret;
1935 if (error != ErrorCode::OK) {
1936 return;
1937 }
1938 if (out) *out = keyCharacteristics;
1939 };
1940
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001941 ErrorCode rc = KS_HANDLE_HIDL_ERROR((*dev)->getKeyCharacteristics(key, appId, appId, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001942 if (rc != ErrorCode::OK) {
1943 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001944 }
1945 return error;
1946}
1947
1948/**
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001949 * Get the auth token for this operation from the auth token table.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001950 *
Shawn Willdend3ed3a22017-03-28 00:39:16 +00001951 * Returns ResponseCode::NO_ERROR if the auth token was set or none was required.
1952 * ::OP_AUTH_NEEDED if it is a per op authorization, no
1953 * authorization token exists for that operation and
1954 * failOnTokenMissing is false.
1955 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
1956 * token for the operation
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001957 */
Shawn Willden0329a822017-12-04 13:55:14 -07001958std::pair<KeyStoreServiceReturnCode, HardwareAuthToken>
1959KeyStoreService::getAuthToken(const KeyCharacteristics& characteristics, uint64_t handle,
1960 KeyPurpose purpose, bool failOnTokenMissing) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001961
Shawn Willden0329a822017-12-04 13:55:14 -07001962 AuthorizationSet allCharacteristics(characteristics.softwareEnforced);
1963 allCharacteristics.append(characteristics.hardwareEnforced.begin(),
1964 characteristics.hardwareEnforced.end());
1965
1966 const HardwareAuthToken* authToken = nullptr;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001967 AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
Shawn Willden0329a822017-12-04 13:55:14 -07001968 allCharacteristics, static_cast<KeyPurpose>(purpose), handle, &authToken);
1969
1970 KeyStoreServiceReturnCode rc;
1971
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001972 switch (err) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001973 case AuthTokenTable::OK:
1974 case AuthTokenTable::AUTH_NOT_REQUIRED:
Shawn Willden0329a822017-12-04 13:55:14 -07001975 rc = ResponseCode::NO_ERROR;
1976 break;
1977
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001978 case AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
1979 case AuthTokenTable::AUTH_TOKEN_EXPIRED:
1980 case AuthTokenTable::AUTH_TOKEN_WRONG_SID:
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07001981 ALOGE("getAuthToken failed: %d", err); // STOPSHIP: debug only, to be removed
Shawn Willden0329a822017-12-04 13:55:14 -07001982 rc = ErrorCode::KEY_USER_NOT_AUTHENTICATED;
1983 break;
1984
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01001985 case AuthTokenTable::OP_HANDLE_REQUIRED:
Shawn Willden0329a822017-12-04 13:55:14 -07001986 rc = failOnTokenMissing ? KeyStoreServiceReturnCode(ErrorCode::KEY_USER_NOT_AUTHENTICATED)
1987 : KeyStoreServiceReturnCode(ResponseCode::OP_AUTH_NEEDED);
1988 break;
1989
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001990 default:
1991 ALOGE("Unexpected FindAuthorization return value %d", err);
Shawn Willden0329a822017-12-04 13:55:14 -07001992 rc = ErrorCode::INVALID_ARGUMENT;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001993 }
Shawn Willden0329a822017-12-04 13:55:14 -07001994
1995 return {rc, authToken ? std::move(*authToken) : HardwareAuthToken()};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07001996}
1997
1998/**
1999 * Add the auth token for the operation to the param list if the operation
2000 * requires authorization. Uses the cached result in the OperationMap if available
2001 * otherwise gets the token from the AuthTokenTable and caches the result.
2002 *
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002003 * Returns ResponseCode::NO_ERROR if the auth token was added or not needed.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002004 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2005 * authenticated.
2006 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2007 * operation token.
2008 */
Shawn Willden0329a822017-12-04 13:55:14 -07002009std::pair<KeyStoreServiceReturnCode, const HardwareAuthToken&>
2010KeyStoreService::getOperationAuthTokenIfNeeded(const sp<IBinder>& token) {
2011 static HardwareAuthToken emptyToken = {};
2012
Shawn Willdenda6dcc32017-12-03 14:56:05 -07002013 auto getOpResult = mOperationMap.getOperation(token);
Shawn Willden0329a822017-12-04 13:55:14 -07002014 if (!getOpResult.isOk()) return {ErrorCode::INVALID_OPERATION_HANDLE, emptyToken};
Shawn Willdenda6dcc32017-12-03 14:56:05 -07002015 const auto& op = getOpResult.value();
2016
Shawn Willden0329a822017-12-04 13:55:14 -07002017 if (!op.hasAuthToken()) {
2018 KeyStoreServiceReturnCode rc;
2019 HardwareAuthToken found;
2020 std::tie(rc, found) = getAuthToken(op.characteristics, op.handle, op.purpose);
2021 if (!rc.isOk()) return {rc, emptyToken};
2022 mOperationMap.setOperationAuthToken(token, std::move(found));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002023 }
Shawn Willden0329a822017-12-04 13:55:14 -07002024
2025 return {ResponseCode::NO_ERROR, op.authToken};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002026}
2027
2028/**
2029 * Translate a result value to a legacy return value. All keystore errors are
2030 * preserved and keymaster errors become SYSTEM_ERRORs
2031 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002032KeyStoreServiceReturnCode KeyStoreService::translateResultToLegacyResult(int32_t result) {
Shawn Willden0329a822017-12-04 13:55:14 -07002033 if (result > 0) return static_cast<ResponseCode>(result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002034 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002035}
2036
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002037static NullOr<const Algorithm&> getKeyAlgoritmFromKeyCharacteristics(
2038 const ::android::security::keymaster::KeyCharacteristics& characteristics) {
Shawn Willden0329a822017-12-04 13:55:14 -07002039 for (const auto& param : characteristics.hardwareEnforced.getParameters()) {
2040 auto algo = authorizationValue(TAG_ALGORITHM, param);
2041 if (algo.isOk()) return algo;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002042 }
Shawn Willden0329a822017-12-04 13:55:14 -07002043 for (const auto& param : characteristics.softwareEnforced.getParameters()) {
2044 auto algo = authorizationValue(TAG_ALGORITHM, param);
2045 if (algo.isOk()) return algo;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002046 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002047 return {};
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002048}
2049
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002050void KeyStoreService::addLegacyBeginParams(const String16& name, AuthorizationSet* params) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002051 // All legacy keys are DIGEST_NONE/PAD_NONE.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002052 params->push_back(TAG_DIGEST, Digest::NONE);
2053 params->push_back(TAG_PADDING, PaddingMode::NONE);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002054
2055 // Look up the algorithm of the key.
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002056 ::android::security::keymaster::KeyCharacteristics characteristics;
2057 int32_t result;
2058 auto rc = getKeyCharacteristics(name, ::android::security::keymaster::KeymasterBlob(),
2059 ::android::security::keymaster::KeymasterBlob(), UID_SELF,
2060 &characteristics, &result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002061 if (!rc.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002062 ALOGE("Failed to get key characteristics");
2063 return;
2064 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002065 auto algorithm = getKeyAlgoritmFromKeyCharacteristics(characteristics);
2066 if (!algorithm.isOk()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002067 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
2068 return;
2069 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002070 params->push_back(TAG_ALGORITHM, algorithm.value());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002071}
2072
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002073KeyStoreServiceReturnCode KeyStoreService::doLegacySignVerify(const String16& name,
2074 const hidl_vec<uint8_t>& data,
2075 hidl_vec<uint8_t>* out,
2076 const hidl_vec<uint8_t>& signature,
2077 KeyPurpose purpose) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002078
2079 std::basic_stringstream<uint8_t> outBuffer;
2080 OperationResult result;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002081 AuthorizationSet inArgs;
2082 addLegacyBeginParams(name, &inArgs);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002083 sp<IBinder> appToken(new BBinder);
2084 sp<IBinder> token;
2085
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002086 begin(appToken, name, static_cast<int32_t>(purpose), true,
2087 KeymasterArguments(inArgs.hidl_data()), ::std::vector<uint8_t>(), UID_SELF, &result);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002088 if (!result.resultCode.isOk()) {
2089 if (result.resultCode == ResponseCode::KEY_NOT_FOUND) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002090 ALOGW("Key not found");
2091 } else {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002092 ALOGW("Error in begin: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002093 }
2094 return translateResultToLegacyResult(result.resultCode);
2095 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002096 inArgs.Clear();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002097 token = result.token;
2098 size_t consumed = 0;
2099 size_t lastConsumed = 0;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002100 hidl_vec<uint8_t> data_view;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002101 do {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002102 data_view.setToExternal(const_cast<uint8_t*>(&data[consumed]), data.size() - consumed);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002103 update(token, KeymasterArguments(inArgs.hidl_data()), data_view, &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002104 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002105 ALOGW("Error in update: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002106 return translateResultToLegacyResult(result.resultCode);
2107 }
2108 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002109 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002110 }
2111 lastConsumed = result.inputConsumed;
2112 consumed += lastConsumed;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002113 } while (consumed < data.size() && lastConsumed > 0);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002114
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002115 if (consumed != data.size()) {
2116 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, data.size());
2117 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002118 }
2119
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002120 finish(token, KeymasterArguments(inArgs.hidl_data()), signature, ::std::vector<uint8_t>(),
2121 &result);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002122 if (result.resultCode != ResponseCode::NO_ERROR) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002123 ALOGW("Error in finish: %d", int32_t(result.resultCode));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002124 return translateResultToLegacyResult(result.resultCode);
2125 }
2126 if (out) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002127 outBuffer.write(&result.data[0], result.data.size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002128 }
2129
2130 if (out) {
2131 auto buf = outBuffer.str();
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002132 out->resize(buf.size());
2133 memcpy(&(*out)[0], buf.data(), out->size());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002134 }
2135
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002136 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002137}
2138
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002139KeyStoreServiceReturnCode KeyStoreService::upgradeKeyBlob(const String16& name, uid_t uid,
2140 const AuthorizationSet& params,
2141 Blob* blob) {
Shawn Willden98c59162016-03-20 09:10:18 -06002142 // Read the blob rather than assuming the caller provided the right name/uid/blob triplet.
2143 String8 name8(name);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002144 KeyStoreServiceReturnCode responseCode =
2145 mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002146 if (responseCode != ResponseCode::NO_ERROR) {
Shawn Willden98c59162016-03-20 09:10:18 -06002147 return responseCode;
2148 }
Rubin Xu7675c9f2017-03-15 19:26:52 +00002149 ALOGI("upgradeKeyBlob %s %d", name8.string(), uid);
Shawn Willden98c59162016-03-20 09:10:18 -06002150
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002151 auto hidlKey = blob2hidlVec(*blob);
Janis Danisevskisc1460142017-12-18 16:48:46 -08002152 auto dev = mKeyStore->getDevice(*blob);
Shawn Willden98c59162016-03-20 09:10:18 -06002153
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002154 KeyStoreServiceReturnCode error;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -07002155 auto hidlCb = [&](ErrorCode ret, const ::std::vector<uint8_t>& upgradedKeyBlob) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002156 error = ret;
2157 if (!error.isOk()) {
Pavel Grafovcef39472018-02-12 18:45:02 +00002158 if (error == ErrorCode::INVALID_KEY_BLOB) {
2159 log_key_integrity_violation(name8, uid);
2160 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002161 return;
2162 }
2163
Janis Danisevskisaf7783f2017-09-21 11:29:47 -07002164 auto filename = mKeyStore->getBlobFileNameIfExists(name8, uid, ::TYPE_KEYMASTER_10);
2165 if (!filename.isOk()) {
2166 ALOGI("trying to upgrade a non existing blob");
2167 return;
2168 }
2169 error = mKeyStore->del(filename.value().string(), ::TYPE_ANY, get_user_id(uid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002170 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00002171 ALOGI("upgradeKeyBlob keystore->del failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002172 return;
2173 }
2174
2175 Blob newBlob(&upgradedKeyBlob[0], upgradedKeyBlob.size(), nullptr /* info */,
2176 0 /* infoLength */, ::TYPE_KEYMASTER_10);
Janis Danisevskisc1460142017-12-18 16:48:46 -08002177 newBlob.setSecurityLevel(blob->getSecurityLevel());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002178 newBlob.setEncrypted(blob->isEncrypted());
Rubin Xu67899de2017-04-21 19:15:13 +01002179 newBlob.setSuperEncrypted(blob->isSuperEncrypted());
2180 newBlob.setCriticalToDeviceEncryption(blob->isCriticalToDeviceEncryption());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002181
Janis Danisevskisaf7783f2017-09-21 11:29:47 -07002182 error = mKeyStore->put(filename.value().string(), &newBlob, get_user_id(uid));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002183 if (!error.isOk()) {
Rubin Xu7675c9f2017-03-15 19:26:52 +00002184 ALOGI("upgradeKeyBlob keystore->put failed %d", (int)error);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002185 return;
2186 }
2187
2188 // Re-read blob for caller. We can't use newBlob because writing it modified it.
2189 error = mKeyStore->getKeyForName(blob, name8, uid, TYPE_KEYMASTER_10);
2190 };
2191
2192 KeyStoreServiceReturnCode rc =
2193 KS_HANDLE_HIDL_ERROR(dev->upgradeKey(hidlKey, params.hidl_data(), hidlCb));
2194 if (!rc.isOk()) {
Shawn Willden98c59162016-03-20 09:10:18 -06002195 return rc;
2196 }
2197
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +01002198 return error;
Shawn Willden98c59162016-03-20 09:10:18 -06002199}
2200
Shawn Willdene2a7b522017-04-11 09:27:40 -06002201} // namespace keystore