blob: d9355b9c0c28cde4409fa081e63a3aee7af973e5 [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
Shawn Willdenc1d1fee2016-01-26 22:44:56 -07002 * Copyright (C) 2016 The Android Open Source Project
Kenny Roota91203b2012-02-15 15:00:46 -08003 *
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 Danisevskisc7a9fa22016-10-13 18:43:45 +010017#define LOG_TAG "keystore"
18
Shawn Willdenfa5702f2017-12-03 15:14:58 -070019#include "KeyStore.h"
Kenny Root07438c82012-11-02 15:41:02 -070020
Kenny Roota91203b2012-02-15 15:00:46 -080021#include <dirent.h>
22#include <fcntl.h>
Kenny Roota91203b2012-02-15 15:00:46 -080023
Kenny Root822c3a92012-03-23 16:34:39 -070024#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080025
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070026#include <utils/String16.h>
Janis Danisevskis6905c332017-09-01 13:24:23 -070027#include <utils/String8.h>
Kenny Root70e3a862012-02-15 17:20:23 -080028
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010029#include <android/hardware/keymaster/3.0/IKeymasterDevice.h>
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -070030#include <android/security/IKeystoreService.h>
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010031
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070032#include "keystore_utils.h"
33#include "permissions.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010034#include <keystore/keystore_hidl_support.h>
Kenny Roota91203b2012-02-15 15:00:46 -080035
Shawn Willdenc67a8aa2017-12-03 17:51:29 -070036namespace keystore {
37
Shawn Willden0329a822017-12-04 13:55:14 -070038const char* KeyStore::kOldMasterKey = ".masterkey";
39const char* KeyStore::kMetaDataFile = ".metadata";
Kenny Roota91203b2012-02-15 15:00:46 -080040
Shawn Willden0329a822017-12-04 13:55:14 -070041const android::String16 KeyStore::kRsaKeyType("RSA");
42const android::String16 KeyStore::kEcKeyType("EC");
Riley Spahneaabae92014-06-30 12:39:52 -070043
Janis Danisevskis6905c332017-09-01 13:24:23 -070044using android::String8;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010045
Janis Danisevskisc1460142017-12-18 16:48:46 -080046sp<Keymaster>& KeymasterDevices::operator[](SecurityLevel secLevel) {
47 static_assert(uint32_t(SecurityLevel::SOFTWARE) == 0 &&
48 uint32_t(SecurityLevel::TRUSTED_ENVIRONMENT) == 1 &&
49 uint32_t(SecurityLevel::STRONGBOX) == 2,
50 "Numeric values of security levels have changed");
51 return at(static_cast<uint32_t>(secLevel));
52}
53
54sp<Keymaster> KeymasterDevices::operator[](SecurityLevel secLevel) const {
55 if (static_cast<uint32_t>(secLevel) > static_cast<uint32_t>(SecurityLevel::STRONGBOX)) {
56 LOG(ERROR) << "Invalid security level requested";
57 return nullptr;
58 }
59 return (*const_cast<KeymasterDevices*>(this))[secLevel];
60}
61
62KeyStore::KeyStore(Entropy* entropy, const KeymasterDevices& kmDevices,
63 SecurityLevel minimalAllowedSecurityLevelForNewKeys)
64 : mEntropy(entropy), mKmDevices(kmDevices),
65 mAllowNewFallback(minimalAllowedSecurityLevelForNewKeys == SecurityLevel::SOFTWARE) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070066 memset(&mMetaData, '\0', sizeof(mMetaData));
Kenny Root70e3a862012-02-15 17:20:23 -080067}
68
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070069KeyStore::~KeyStore() {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070070 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
71 it++) {
72 delete *it;
Shawn Willden55268b52015-07-28 11:06:00 -060073 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070074 mMasterKeys.clear();
Shawn Willden55268b52015-07-28 11:06:00 -060075}
76
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070077ResponseCode KeyStore::initialize() {
78 readMetaData();
79 if (upgradeKeystore()) {
80 writeMetaData();
Shawn Willden55268b52015-07-28 11:06:00 -060081 }
82
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010083 return ResponseCode::NO_ERROR;
Shawn Willden55268b52015-07-28 11:06:00 -060084}
85
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070086ResponseCode KeyStore::initializeUser(const android::String8& pw, uid_t userId) {
87 UserState* userState = getUserState(userId);
88 return userState->initialize(pw, mEntropy);
Chad Brubakerfc18edc2015-01-12 15:17:18 -080089}
90
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070091ResponseCode KeyStore::copyMasterKey(uid_t srcUser, uid_t dstUser) {
92 UserState* userState = getUserState(dstUser);
93 UserState* initState = getUserState(srcUser);
94 return userState->copyMasterKey(initState);
Kenny Root70e3a862012-02-15 17:20:23 -080095}
96
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070097ResponseCode KeyStore::writeMasterKey(const android::String8& pw, uid_t userId) {
98 UserState* userState = getUserState(userId);
99 return userState->writeMasterKey(pw, mEntropy);
Shawn Willden55268b52015-07-28 11:06:00 -0600100}
101
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700102ResponseCode KeyStore::readMasterKey(const android::String8& pw, uid_t userId) {
103 UserState* userState = getUserState(userId);
104 return userState->readMasterKey(pw, mEntropy);
Kenny Root49468902013-03-19 13:41:33 -0700105}
106
Kenny Roota91203b2012-02-15 15:00:46 -0800107/* Here is the encoding of keys. This is necessary in order to allow arbitrary
108 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
109 * into two bytes. The first byte is one of [+-.] which represents the first
110 * two bits of the character. The second byte encodes the rest of the bits into
111 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
112 * that Base64 cannot be used here due to the need of prefix match on keys. */
113
Kenny Root655b9582013-04-04 08:37:42 -0700114static size_t encode_key_length(const android::String8& keyName) {
115 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
116 size_t length = keyName.length();
117 for (int i = length; i > 0; --i, ++in) {
118 if (*in < '0' || *in > '~') {
119 ++length;
120 }
121 }
122 return length;
123}
124
Kenny Root07438c82012-11-02 15:41:02 -0700125static int encode_key(char* out, const android::String8& keyName) {
126 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
127 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800128 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700129 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800130 *out = '+' + (*in >> 6);
131 *++out = '0' + (*in & 0x3F);
132 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700133 } else {
134 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800135 }
136 }
137 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800138 return length;
139}
140
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400141android::String8 KeyStore::getKeyName(const android::String8& keyName, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000142 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
143 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400144 if (type == TYPE_KEY_CHARACTERISTICS) {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400145 return android::String8::format(".chr_%s", encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400146 } else {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400147 return android::String8(encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400148 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700149}
150
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700151android::String8 KeyStore::getKeyNameForUid(const android::String8& keyName, uid_t uid,
152 const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000153 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
154 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400155 if (type == TYPE_KEY_CHARACTERISTICS) {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400156 return android::String8::format(".%u_chr_%s", uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400157 } else {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400158 return android::String8::format("%u_%s", uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400159 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700160}
161
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700162android::String8 KeyStore::getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid,
163 const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000164 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
165 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400166
167 if (type == TYPE_KEY_CHARACTERISTICS) {
168 return android::String8::format("%s/.%u_chr_%s", getUserStateByUid(uid)->getUserDirName(),
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400169 uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400170 } else {
171 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400172 encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400173 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700174}
175
Janis Danisevskis31b44f22017-09-21 11:29:47 -0700176NullOr<android::String8> KeyStore::getBlobFileNameIfExists(const android::String8& alias, uid_t uid,
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700177 const BlobType type) {
Janis Danisevskis31b44f22017-09-21 11:29:47 -0700178 android::String8 filepath8(getKeyNameForUidWithDir(alias, uid, type));
179
180 if (!access(filepath8.string(), R_OK | W_OK)) return filepath8;
181
182 // If this is one of the legacy UID->UID mappings, use it.
183 uid_t euid = get_keystore_euid(uid);
184 if (euid != uid) {
185 filepath8 = getKeyNameForUidWithDir(alias, euid, type);
186 if (!access(filepath8.string(), R_OK | W_OK)) return filepath8;
187 }
188
189 // They might be using a granted key.
190 auto grant = mGrants.get(uid, alias.string());
191 if (grant) {
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700192 filepath8 = String8::format(
193 "%s/%s", grant->owner_dir_name_.c_str(),
194 getKeyNameForUid(String8(grant->alias_.c_str()), grant->owner_uid_, type).c_str());
Janis Danisevskis31b44f22017-09-21 11:29:47 -0700195 if (!access(filepath8.string(), R_OK | W_OK)) return filepath8;
196 }
197 return {};
198}
199
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700200void KeyStore::resetUser(uid_t userId, bool keepUnenryptedEntries) {
201 android::String8 prefix("");
202 android::Vector<android::String16> aliases;
203 UserState* userState = getUserState(userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100204 if (list(prefix, &aliases, userId) != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700205 return;
206 }
207 for (uint32_t i = 0; i < aliases.size(); i++) {
208 android::String8 filename(aliases[i]);
209 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400210 getKeyName(filename, TYPE_ANY).string());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700211 bool shouldDelete = true;
212 if (keepUnenryptedEntries) {
213 Blob blob;
214 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
215
Shawn Willden07aebe72017-02-28 13:53:24 -0700216 switch (rc) {
217 case ResponseCode::SYSTEM_ERROR:
218 case ResponseCode::VALUE_CORRUPTED:
219 // If we can't read blobs, delete them.
220 shouldDelete = true;
221 break;
222
223 case ResponseCode::NO_ERROR:
224 case ResponseCode::LOCKED:
225 // Delete encrypted blobs but keep unencrypted blobs and super-encrypted blobs. We
226 // need to keep super-encrypted blobs so we can report that the user is
227 // unauthenticated if a caller tries to use them, rather than reporting that they
228 // don't exist.
229 shouldDelete = blob.isEncrypted();
230 break;
231
232 default:
233 ALOGE("Got unexpected return code %d from KeyStore::get()", rc);
234 // This shouldn't happen. To be on the safe side, delete it.
235 shouldDelete = true;
236 break;
237 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700238 }
239 if (shouldDelete) {
240 del(filename, ::TYPE_ANY, userId);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400241
242 // del() will fail silently if no cached characteristics are present for this alias.
243 android::String8 chr_filename(aliases[i]);
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700244 chr_filename = android::String8::format(
245 "%s/%s", userState->getUserDirName(),
246 getKeyName(chr_filename, TYPE_KEY_CHARACTERISTICS).string());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400247 del(chr_filename, ::TYPE_KEY_CHARACTERISTICS, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700248 }
249 }
250 if (!userState->deleteMasterKey()) {
251 ALOGE("Failed to delete user %d's master key", userId);
252 }
253 if (!keepUnenryptedEntries) {
254 if (!userState->reset()) {
255 ALOGE("Failed to remove user %d's directory", userId);
256 }
257 }
258}
259
260bool KeyStore::isEmpty(uid_t userId) const {
261 const UserState* userState = getUserState(userId);
262 if (userState == NULL) {
263 return true;
264 }
265
266 DIR* dir = opendir(userState->getUserDirName());
267 if (!dir) {
268 return true;
269 }
270
271 bool result = true;
272 struct dirent* file;
273 while ((file = readdir(dir)) != NULL) {
274 // We only care about files.
275 if (file->d_type != DT_REG) {
276 continue;
277 }
278
279 // Skip anything that starts with a "."
280 if (file->d_name[0] == '.') {
281 continue;
282 }
283
284 result = false;
285 break;
286 }
287 closedir(dir);
288 return result;
289}
290
291void KeyStore::lock(uid_t userId) {
292 UserState* userState = getUserState(userId);
293 userState->zeroizeMasterKeysInMemory();
294 userState->setState(STATE_LOCKED);
295}
296
297ResponseCode KeyStore::get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
298 UserState* userState = getUserState(userId);
299 ResponseCode rc =
Shawn Willdene9830582017-04-18 10:47:57 -0600300 keyBlob->readBlob(filename, userState->getEncryptionKey(), userState->getState());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100301 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700302 return rc;
303 }
304
305 const uint8_t version = keyBlob->getVersion();
306 if (version < CURRENT_BLOB_VERSION) {
307 /* If we upgrade the key, we need to write it to disk again. Then
308 * it must be read it again since the blob is encrypted each time
309 * it's written.
310 */
311 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100312 if ((rc = this->put(filename, keyBlob, userId)) != ResponseCode::NO_ERROR ||
Shawn Willdene9830582017-04-18 10:47:57 -0600313 (rc = keyBlob->readBlob(filename, userState->getEncryptionKey(),
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100314 userState->getState())) != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700315 return rc;
316 }
317 }
318 }
319
320 /*
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100321 * This will upgrade software-backed keys to hardware-backed keys.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700322 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100323 if (rc == ResponseCode::NO_ERROR && type == TYPE_KEY_PAIR && keyBlob->isFallback()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700324 ResponseCode imported =
325 importKey(keyBlob->getValue(), keyBlob->getLength(), filename, userId,
326 keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
327
Shawn Willden07aebe72017-02-28 13:53:24 -0700328 // The HAL allowed the import, reget the key to have the "fresh" version.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100329 if (imported == ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700330 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
331 }
332 }
333
334 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
335 if (keyBlob->getType() == TYPE_KEY_PAIR) {
336 keyBlob->setType(TYPE_KEYMASTER_10);
337 rc = this->put(filename, keyBlob, userId);
338 }
339
340 if (type != TYPE_ANY && keyBlob->getType() != type) {
341 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100342 return ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700343 }
344
345 return rc;
346}
347
348ResponseCode KeyStore::put(const char* filename, Blob* keyBlob, uid_t userId) {
349 UserState* userState = getUserState(userId);
350 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
351 mEntropy);
352}
353
Janis Danisevskis31b44f22017-09-21 11:29:47 -0700354static NullOr<std::tuple<uid_t, std::string>> filename2UidAlias(const std::string& filename);
355
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700356ResponseCode KeyStore::del(const char* filename, const BlobType type, uid_t userId) {
357 Blob keyBlob;
Janis Danisevskis31b44f22017-09-21 11:29:47 -0700358 auto uidAlias = filename2UidAlias(filename);
359 uid_t uid;
360 std::string alias;
361 if (uidAlias.isOk()) {
362 std::tie(uid, alias) = std::move(uidAlias).value();
363 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700364 ResponseCode rc = get(filename, &keyBlob, type, userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100365 if (rc == ResponseCode::VALUE_CORRUPTED) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700366 // The file is corrupt, the best we can do is rm it.
Janis Danisevskis31b44f22017-09-21 11:29:47 -0700367 if (uidAlias.isOk()) {
368 // remove possible grants
369 mGrants.removeAllGrantsToKey(uid, alias);
370 }
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700371 return (unlink(filename) && errno != ENOENT) ? ResponseCode::SYSTEM_ERROR
372 : ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700373 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100374 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700375 return rc;
376 }
377
Janis Danisevskisc1460142017-12-18 16:48:46 -0800378 auto dev = getDevice(keyBlob);
Janis Danisevskis69c434a2017-01-30 10:27:10 +0000379
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100380 if (keyBlob.getType() == ::TYPE_KEY_PAIR || keyBlob.getType() == ::TYPE_KEYMASTER_10) {
Janis Danisevskis69c434a2017-01-30 10:27:10 +0000381 auto ret = KS_HANDLE_HIDL_ERROR(dev->deleteKey(blob2hidlVec(keyBlob)));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100382
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700383 // A device doesn't have to implement delete_key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100384 if (ret != ErrorCode::OK && ret != ErrorCode::UNIMPLEMENTED)
385 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700386 }
387
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700388 rc =
389 (unlink(filename) && errno != ENOENT) ? ResponseCode::SYSTEM_ERROR : ResponseCode::NO_ERROR;
Janis Danisevskis31b44f22017-09-21 11:29:47 -0700390
391 if (rc == ResponseCode::NO_ERROR && keyBlob.getType() != ::TYPE_KEY_CHARACTERISTICS) {
392 // now that we have successfully deleted a key, let's make sure there are no stale grants
393 if (uidAlias.isOk()) {
394 mGrants.removeAllGrantsToKey(uid, alias);
395 }
396 }
397 return rc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700398}
399
Kenny Root07438c82012-11-02 15:41:02 -0700400/*
401 * Converts from the "escaped" format on disk to actual name.
402 * This will be smaller than the input string.
403 *
404 * Characters that should combine with the next at the end will be truncated.
405 */
406static size_t decode_key_length(const char* in, size_t length) {
407 size_t outLength = 0;
408
409 for (const char* end = in + length; in < end; in++) {
410 /* This combines with the next character. */
411 if (*in < '0' || *in > '~') {
412 continue;
413 }
414
415 outLength++;
416 }
417 return outLength;
418}
419
420static void decode_key(char* out, const char* in, size_t length) {
421 for (const char* end = in + length; in < end; in++) {
422 if (*in < '0' || *in > '~') {
423 /* Truncate combining characters at the end. */
424 if (in + 1 >= end) {
425 break;
426 }
427
428 *out = (*in++ - '+') << 6;
429 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800430 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700431 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800432 }
433 }
434 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800435}
436
Janis Danisevskis31b44f22017-09-21 11:29:47 -0700437static NullOr<std::tuple<uid_t, std::string>> filename2UidAlias(const std::string& filepath) {
438 auto filenamebase = filepath.find_last_of('/');
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700439 std::string filename =
440 filenamebase == std::string::npos ? filepath : filepath.substr(filenamebase + 1);
Janis Danisevskis31b44f22017-09-21 11:29:47 -0700441
442 if (filename[0] == '.') return {};
443
444 auto sep = filename.find('_');
445 if (sep == std::string::npos) return {};
446
447 std::stringstream s(filename.substr(0, sep));
448 uid_t uid;
449 s >> uid;
450 if (!s) return {};
451
452 auto alias = filename.substr(sep + 1);
453
454 std::vector<char> alias_buffer(decode_key_length(alias.c_str(), alias.size()) + 1);
455
456 decode_key(alias_buffer.data(), alias.c_str(), alias.size());
457 return std::tuple<uid_t, std::string>(uid, alias_buffer.data());
458}
459
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700460ResponseCode KeyStore::list(const android::String8& prefix,
461 android::Vector<android::String16>* matches, uid_t userId) {
Kenny Roota91203b2012-02-15 15:00:46 -0800462
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700463 UserState* userState = getUserState(userId);
464 size_t n = prefix.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800465
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700466 DIR* dir = opendir(userState->getUserDirName());
467 if (!dir) {
468 ALOGW("can't open directory for user: %s", strerror(errno));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100469 return ResponseCode::SYSTEM_ERROR;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700470 }
471
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700472 struct dirent* file;
473 while ((file = readdir(dir)) != NULL) {
474 // We only care about files.
475 if (file->d_type != DT_REG) {
476 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700477 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700478
479 // Skip anything that starts with a "."
480 if (file->d_name[0] == '.') {
481 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700482 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700483
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700484 if (!strncmp(prefix.string(), file->d_name, n)) {
485 const char* p = &file->d_name[n];
486 size_t plen = strlen(p);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700487
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700488 size_t extra = decode_key_length(p, plen);
489 char* match = (char*)malloc(extra + 1);
490 if (match != NULL) {
491 decode_key(match, p, plen);
492 matches->push(android::String16(match, extra));
493 free(match);
Chad Brubakerdf705172015-06-17 20:17:51 -0700494 } else {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700495 ALOGW("could not allocate match of size %zd", extra);
Chad Brubakerdf705172015-06-17 20:17:51 -0700496 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700497 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700498 }
499 closedir(dir);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100500 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700501}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700502
Janis Danisevskis6905c332017-09-01 13:24:23 -0700503std::string KeyStore::addGrant(const char* alias, uid_t granterUid, uid_t granteeUid) {
504 return mGrants.put(granteeUid, alias, getUserStateByUid(granterUid)->getUserDirName(),
505 granterUid);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700506}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700507
Janis Danisevskis31b44f22017-09-21 11:29:47 -0700508bool KeyStore::removeGrant(const char* alias, const uid_t granterUid, const uid_t granteeUid) {
509 return mGrants.removeByFileAlias(granteeUid, granterUid, alias);
510}
511void KeyStore::removeAllGrantsToUid(const uid_t granteeUid) {
512 mGrants.removeAllGrantsToUid(granteeUid);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700513}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700514
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700515ResponseCode KeyStore::importKey(const uint8_t* key, size_t keyLen, const char* filename,
516 uid_t userId, int32_t flags) {
517 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
518 if (!pkcs8.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100519 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700520 }
521 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
522 if (!pkey.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100523 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700524 }
525 int type = EVP_PKEY_type(pkey->type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100526 AuthorizationSet params;
527 add_legacy_key_authorizations(type, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700528 switch (type) {
529 case EVP_PKEY_RSA:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100530 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700531 break;
532 case EVP_PKEY_EC:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100533 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700534 break;
535 default:
536 ALOGW("Unsupported key type %d", type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100537 return ResponseCode::SYSTEM_ERROR;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700538 }
539
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100540 AuthorizationSet opParams(params);
541 hidl_vec<uint8_t> blob;
Kenny Root07438c82012-11-02 15:41:02 -0700542
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100543 ErrorCode error;
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700544 auto hidlCb = [&](ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
545 const KeyCharacteristics& /* ignored */) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100546 error = ret;
547 if (error != ErrorCode::OK) return;
548 blob = keyBlob;
549 };
550 auto input = blob2hidlVec(key, keyLen);
Kenny Roota91203b2012-02-15 15:00:46 -0800551
Janis Danisevskisc1460142017-12-18 16:48:46 -0800552 SecurityLevel securityLevel = flagsToSecurityLevel(flags);
553 auto kmDevice = getDevice(securityLevel);
554 if (!kmDevice) {
555 // As of this writing the only caller is KeyStore::get in an attempt to import legacy
556 // software keys. It only ever requests TEE as target which must always be present.
557 // If we see this error, we probably have a new and unanticipated caller.
558 ALOGE("No implementation for security level %d. Cannot import key.", securityLevel);
559 return ResponseCode::SYSTEM_ERROR;
560 }
561
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100562 ErrorCode rc = KS_HANDLE_HIDL_ERROR(
Janis Danisevskisc1460142017-12-18 16:48:46 -0800563 kmDevice->importKey(params.hidl_data(), KeyFormat::PKCS8, input, hidlCb));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100564 if (rc != ErrorCode::OK) return ResponseCode::SYSTEM_ERROR;
565 if (error != ErrorCode::OK) {
566 ALOGE("Keymaster error %d importing key pair", error);
567 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700568 }
569
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100570 Blob keyBlob(&blob[0], blob.size(), NULL, 0, TYPE_KEYMASTER_10);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700571
572 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc1460142017-12-18 16:48:46 -0800573 keyBlob.setSecurityLevel(securityLevel);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700574
575 return put(filename, &keyBlob, userId);
576}
577
Shawn Willden0329a822017-12-04 13:55:14 -0700578bool KeyStore::isHardwareBacked(const android::String16& keyType) const {
Janis Danisevskisc1460142017-12-18 16:48:46 -0800579 // if strongbox device is present TEE must also be present and of sufficiently high version
580 // to support all keys in hardware
581 if (getDevice(SecurityLevel::STRONGBOX)) return true;
582 if (!getDevice(SecurityLevel::TRUSTED_ENVIRONMENT)) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700583 ALOGW("can't get keymaster device");
584 return false;
585 }
Janis Danisevskise2b6caf2017-03-02 16:37:10 -0800586
Janis Danisevskisc1460142017-12-18 16:48:46 -0800587 auto version = getDevice(SecurityLevel::TRUSTED_ENVIRONMENT)->halVersion();
Shawn Willden0329a822017-12-04 13:55:14 -0700588 if (version.error != ErrorCode::OK) {
589 ALOGE("Failed to get HAL version info");
Janis Danisevskise2b6caf2017-03-02 16:37:10 -0800590 return false;
591 }
Shawn Willden0329a822017-12-04 13:55:14 -0700592
Shawn Willden0329a822017-12-04 13:55:14 -0700593 if (keyType == kRsaKeyType) return true; // All versions support RSA
594 return keyType == kEcKeyType && version.supportsEc;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700595}
596
597ResponseCode KeyStore::getKeyForName(Blob* keyBlob, const android::String8& keyName,
598 const uid_t uid, const BlobType type) {
Janis Danisevskis31b44f22017-09-21 11:29:47 -0700599 auto filepath8 = getBlobFileNameIfExists(keyName, uid, type);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700600 uid_t userId = get_user_id(uid);
601
Dmitry Dementyeva447b3c2017-10-27 23:09:53 -0700602 if (filepath8.isOk()) return get(filepath8.value().string(), keyBlob, type, userId);
Riley Spahneaabae92014-06-30 12:39:52 -0700603
Janis Danisevskis31b44f22017-09-21 11:29:47 -0700604 return ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700605}
606
607UserState* KeyStore::getUserState(uid_t userId) {
608 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
609 it++) {
610 UserState* state = *it;
611 if (state->getUserId() == userId) {
612 return state;
613 }
614 }
615
616 UserState* userState = new UserState(userId);
617 if (!userState->initialize()) {
618 /* There's not much we can do if initialization fails. Trying to
619 * unlock the keystore for that user will fail as well, so any
620 * subsequent request for this user will just return SYSTEM_ERROR.
621 */
622 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
623 }
624 mMasterKeys.add(userState);
625 return userState;
626}
627
628UserState* KeyStore::getUserStateByUid(uid_t uid) {
629 uid_t userId = get_user_id(uid);
630 return getUserState(userId);
631}
632
633const UserState* KeyStore::getUserState(uid_t userId) const {
634 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
635 it != mMasterKeys.end(); it++) {
636 UserState* state = *it;
637 if (state->getUserId() == userId) {
638 return state;
639 }
640 }
641
642 return NULL;
643}
644
645const UserState* KeyStore::getUserStateByUid(uid_t uid) const {
646 uid_t userId = get_user_id(uid);
647 return getUserState(userId);
648}
649
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700650bool KeyStore::upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
Janis Danisevskis26b0c372017-09-20 15:08:49 -0700651 const BlobType type, uid_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700652 bool updated = false;
653 uint8_t version = oldVersion;
654
655 /* From V0 -> V1: All old types were unknown */
656 if (version == 0) {
657 ALOGV("upgrading to version 1 and setting type %d", type);
658
659 blob->setType(type);
660 if (type == TYPE_KEY_PAIR) {
Janis Danisevskis26b0c372017-09-20 15:08:49 -0700661 importBlobAsKey(blob, filename, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700662 }
663 version = 1;
664 updated = true;
665 }
666
667 /* From V1 -> V2: All old keys were encrypted */
668 if (version == 1) {
669 ALOGV("upgrading to version 2");
670
671 blob->setEncrypted(true);
672 version = 2;
673 updated = true;
Kenny Roota91203b2012-02-15 15:00:46 -0800674 }
Kenny Root07438c82012-11-02 15:41:02 -0700675
676 /*
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700677 * If we've updated, set the key blob to the right version
678 * and write it.
Kenny Root07438c82012-11-02 15:41:02 -0700679 */
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700680 if (updated) {
681 ALOGV("updated and writing file %s", filename);
682 blob->setVersion(version);
683 }
Kenny Root70e3a862012-02-15 17:20:23 -0800684
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700685 return updated;
686}
687
688struct BIO_Delete {
689 void operator()(BIO* p) const { BIO_free(p); }
690};
Janis Danisevskisccfff102017-05-01 11:02:51 -0700691typedef std::unique_ptr<BIO, BIO_Delete> Unique_BIO;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700692
Janis Danisevskis26b0c372017-09-20 15:08:49 -0700693ResponseCode KeyStore::importBlobAsKey(Blob* blob, const char* filename, uid_t userId) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700694 // We won't even write to the blob directly with this BIO, so const_cast is okay.
695 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
696 if (b.get() == NULL) {
697 ALOGE("Problem instantiating BIO");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100698 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700699 }
700
701 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
702 if (pkey.get() == NULL) {
703 ALOGE("Couldn't read old PEM file");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100704 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700705 }
706
707 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
708 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
709 if (len < 0) {
710 ALOGE("Couldn't measure PKCS#8 length");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100711 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700712 }
713
Janis Danisevskisccfff102017-05-01 11:02:51 -0700714 std::unique_ptr<unsigned char[]> pkcs8key(new unsigned char[len]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700715 uint8_t* tmp = pkcs8key.get();
716 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
717 ALOGE("Couldn't convert to PKCS#8");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100718 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700719 }
720
Janis Danisevskis26b0c372017-09-20 15:08:49 -0700721 ResponseCode rc = importKey(pkcs8key.get(), len, filename, userId,
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700722 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100723 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700724 return rc;
725 }
726
Janis Danisevskis26b0c372017-09-20 15:08:49 -0700727 return get(filename, blob, TYPE_KEY_PAIR, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700728}
729
730void KeyStore::readMetaData() {
Shawn Willden0329a822017-12-04 13:55:14 -0700731 int in = TEMP_FAILURE_RETRY(open(kMetaDataFile, O_RDONLY));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700732 if (in < 0) {
733 return;
734 }
735 size_t fileLength = readFully(in, (uint8_t*)&mMetaData, sizeof(mMetaData));
736 if (fileLength != sizeof(mMetaData)) {
737 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength, sizeof(mMetaData));
738 }
739 close(in);
740}
741
742void KeyStore::writeMetaData() {
743 const char* tmpFileName = ".metadata.tmp";
744 int out =
745 TEMP_FAILURE_RETRY(open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
746 if (out < 0) {
747 ALOGE("couldn't write metadata file: %s", strerror(errno));
748 return;
749 }
750 size_t fileLength = writeFully(out, (uint8_t*)&mMetaData, sizeof(mMetaData));
751 if (fileLength != sizeof(mMetaData)) {
752 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
753 sizeof(mMetaData));
754 }
755 close(out);
Shawn Willden0329a822017-12-04 13:55:14 -0700756 rename(tmpFileName, kMetaDataFile);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700757}
758
759bool KeyStore::upgradeKeystore() {
760 bool upgraded = false;
761
762 if (mMetaData.version == 0) {
763 UserState* userState = getUserStateByUid(0);
764
765 // Initialize first so the directory is made.
766 userState->initialize();
767
768 // Migrate the old .masterkey file to user 0.
Shawn Willden0329a822017-12-04 13:55:14 -0700769 if (access(kOldMasterKey, R_OK) == 0) {
770 if (rename(kOldMasterKey, userState->getMasterKeyFileName()) < 0) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700771 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
772 return false;
773 }
774 }
775
776 // Initialize again in case we had a key.
777 userState->initialize();
778
779 // Try to migrate existing keys.
780 DIR* dir = opendir(".");
781 if (!dir) {
782 // Give up now; maybe we can upgrade later.
783 ALOGE("couldn't open keystore's directory; something is wrong");
784 return false;
785 }
786
787 struct dirent* file;
788 while ((file = readdir(dir)) != NULL) {
789 // We only care about files.
790 if (file->d_type != DT_REG) {
791 continue;
792 }
793
794 // Skip anything that starts with a "."
795 if (file->d_name[0] == '.') {
796 continue;
797 }
798
799 // Find the current file's user.
800 char* end;
801 unsigned long thisUid = strtoul(file->d_name, &end, 10);
802 if (end[0] != '_' || end[1] == 0) {
803 continue;
804 }
805 UserState* otherUser = getUserStateByUid(thisUid);
806 if (otherUser->getUserId() != 0) {
807 unlinkat(dirfd(dir), file->d_name, 0);
808 }
809
810 // Rename the file into user directory.
811 DIR* otherdir = opendir(otherUser->getUserDirName());
812 if (otherdir == NULL) {
813 ALOGW("couldn't open user directory for rename");
814 continue;
815 }
816 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
817 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
818 }
819 closedir(otherdir);
820 }
821 closedir(dir);
822
823 mMetaData.version = 1;
824 upgraded = true;
825 }
826
827 return upgraded;
Kenny Roota91203b2012-02-15 15:00:46 -0800828}
Shawn Willdenc67a8aa2017-12-03 17:51:29 -0700829
830} // namespace keystore