blob: f7695c50bb99b1f294e7b1ea254be59c3eab8d2a [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 Willdenc1d1fee2016-01-26 22:44:56 -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>
Kenny Root70e3a862012-02-15 17:20:23 -080027
Kenny Root07438c82012-11-02 15:41:02 -070028#include <keystore/IKeystoreService.h>
Kenny Root07438c82012-11-02 15:41:02 -070029
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010030#include <android/hardware/keymaster/3.0/IKeymasterDevice.h>
31
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 Willdenc1d1fee2016-01-26 22:44:56 -070036const char* KeyStore::sOldMasterKey = ".masterkey";
37const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Roota91203b2012-02-15 15:00:46 -080038
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070039const android::String16 KeyStore::sRSAKeyType("RSA");
Riley Spahneaabae92014-06-30 12:39:52 -070040
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010041using namespace keystore;
42
Janis Danisevskise8ba1802017-01-30 10:49:51 +000043KeyStore::KeyStore(Entropy* entropy, const km_device_t& device, const km_device_t& fallback,
44 bool allowNewFallback)
45 : mEntropy(entropy), mDevice(device), mFallbackDevice(fallback),
46 mAllowNewFallback(allowNewFallback) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070047 memset(&mMetaData, '\0', sizeof(mMetaData));
Kenny Root70e3a862012-02-15 17:20:23 -080048}
49
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070050KeyStore::~KeyStore() {
51 for (android::Vector<grant_t*>::iterator it(mGrants.begin()); it != mGrants.end(); it++) {
52 delete *it;
Shawn Willden55268b52015-07-28 11:06:00 -060053 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070054 mGrants.clear();
Shawn Willden55268b52015-07-28 11:06:00 -060055
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070056 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
57 it++) {
58 delete *it;
Shawn Willden55268b52015-07-28 11:06:00 -060059 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070060 mMasterKeys.clear();
Shawn Willden55268b52015-07-28 11:06:00 -060061}
62
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070063ResponseCode KeyStore::initialize() {
64 readMetaData();
65 if (upgradeKeystore()) {
66 writeMetaData();
Shawn Willden55268b52015-07-28 11:06:00 -060067 }
68
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010069 return ResponseCode::NO_ERROR;
Shawn Willden55268b52015-07-28 11:06:00 -060070}
71
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070072ResponseCode KeyStore::initializeUser(const android::String8& pw, uid_t userId) {
73 UserState* userState = getUserState(userId);
74 return userState->initialize(pw, mEntropy);
Chad Brubakerfc18edc2015-01-12 15:17:18 -080075}
76
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070077ResponseCode KeyStore::copyMasterKey(uid_t srcUser, uid_t dstUser) {
78 UserState* userState = getUserState(dstUser);
79 UserState* initState = getUserState(srcUser);
80 return userState->copyMasterKey(initState);
Kenny Root70e3a862012-02-15 17:20:23 -080081}
82
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070083ResponseCode KeyStore::writeMasterKey(const android::String8& pw, uid_t userId) {
84 UserState* userState = getUserState(userId);
85 return userState->writeMasterKey(pw, mEntropy);
Shawn Willden55268b52015-07-28 11:06:00 -060086}
87
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070088ResponseCode KeyStore::readMasterKey(const android::String8& pw, uid_t userId) {
89 UserState* userState = getUserState(userId);
90 return userState->readMasterKey(pw, mEntropy);
Kenny Root49468902013-03-19 13:41:33 -070091}
92
Kenny Roota91203b2012-02-15 15:00:46 -080093/* Here is the encoding of keys. This is necessary in order to allow arbitrary
94 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
95 * into two bytes. The first byte is one of [+-.] which represents the first
96 * two bits of the character. The second byte encodes the rest of the bits into
97 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
98 * that Base64 cannot be used here due to the need of prefix match on keys. */
99
Kenny Root655b9582013-04-04 08:37:42 -0700100static size_t encode_key_length(const android::String8& keyName) {
101 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
102 size_t length = keyName.length();
103 for (int i = length; i > 0; --i, ++in) {
104 if (*in < '0' || *in > '~') {
105 ++length;
106 }
107 }
108 return length;
109}
110
Kenny Root07438c82012-11-02 15:41:02 -0700111static int encode_key(char* out, const android::String8& keyName) {
112 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
113 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800114 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700115 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800116 *out = '+' + (*in >> 6);
117 *++out = '0' + (*in & 0x3F);
118 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700119 } else {
120 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800121 }
122 }
123 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800124 return length;
125}
126
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400127android::String8 KeyStore::getKeyName(const android::String8& keyName, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000128 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
129 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400130 if (type == TYPE_KEY_CHARACTERISTICS) {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400131 return android::String8::format(".chr_%s", encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400132 } else {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400133 return android::String8(encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400134 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700135}
136
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400137android::String8 KeyStore::getKeyNameForUid(
138 const android::String8& keyName, uid_t uid, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000139 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
140 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400141 if (type == TYPE_KEY_CHARACTERISTICS) {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400142 return android::String8::format(".%u_chr_%s", uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400143 } else {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400144 return android::String8::format("%u_%s", uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400145 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700146}
147
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400148android::String8 KeyStore::getKeyNameForUidWithDir(
149 const android::String8& keyName, uid_t uid, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000150 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
151 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400152
153 if (type == TYPE_KEY_CHARACTERISTICS) {
154 return android::String8::format("%s/.%u_chr_%s", getUserStateByUid(uid)->getUserDirName(),
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400155 uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400156 } else {
157 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400158 encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400159 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700160}
161
162void KeyStore::resetUser(uid_t userId, bool keepUnenryptedEntries) {
163 android::String8 prefix("");
164 android::Vector<android::String16> aliases;
165 UserState* userState = getUserState(userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100166 if (list(prefix, &aliases, userId) != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700167 return;
168 }
169 for (uint32_t i = 0; i < aliases.size(); i++) {
170 android::String8 filename(aliases[i]);
171 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400172 getKeyName(filename, TYPE_ANY).string());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700173 bool shouldDelete = true;
174 if (keepUnenryptedEntries) {
175 Blob blob;
176 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
177
178 /* get can fail if the blob is encrypted and the state is
179 * not unlocked, only skip deleting blobs that were loaded and
180 * who are not encrypted. If there are blobs we fail to read for
181 * other reasons err on the safe side and delete them since we
182 * can't tell if they're encrypted.
183 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100184 shouldDelete = !(rc == ResponseCode::NO_ERROR && !blob.isEncrypted());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700185 }
186 if (shouldDelete) {
187 del(filename, ::TYPE_ANY, userId);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400188
189 // del() will fail silently if no cached characteristics are present for this alias.
190 android::String8 chr_filename(aliases[i]);
191 chr_filename = android::String8::format("%s/%s", userState->getUserDirName(),
192 getKeyName(chr_filename,
193 TYPE_KEY_CHARACTERISTICS).string());
194 del(chr_filename, ::TYPE_KEY_CHARACTERISTICS, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700195 }
196 }
197 if (!userState->deleteMasterKey()) {
198 ALOGE("Failed to delete user %d's master key", userId);
199 }
200 if (!keepUnenryptedEntries) {
201 if (!userState->reset()) {
202 ALOGE("Failed to remove user %d's directory", userId);
203 }
204 }
205}
206
207bool KeyStore::isEmpty(uid_t userId) const {
208 const UserState* userState = getUserState(userId);
209 if (userState == NULL) {
210 return true;
211 }
212
213 DIR* dir = opendir(userState->getUserDirName());
214 if (!dir) {
215 return true;
216 }
217
218 bool result = true;
219 struct dirent* file;
220 while ((file = readdir(dir)) != NULL) {
221 // We only care about files.
222 if (file->d_type != DT_REG) {
223 continue;
224 }
225
226 // Skip anything that starts with a "."
227 if (file->d_name[0] == '.') {
228 continue;
229 }
230
231 result = false;
232 break;
233 }
234 closedir(dir);
235 return result;
236}
237
238void KeyStore::lock(uid_t userId) {
239 UserState* userState = getUserState(userId);
240 userState->zeroizeMasterKeysInMemory();
241 userState->setState(STATE_LOCKED);
242}
243
244ResponseCode KeyStore::get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
245 UserState* userState = getUserState(userId);
246 ResponseCode rc =
247 keyBlob->readBlob(filename, userState->getDecryptionKey(), userState->getState());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100248 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700249 return rc;
250 }
251
252 const uint8_t version = keyBlob->getVersion();
253 if (version < CURRENT_BLOB_VERSION) {
254 /* If we upgrade the key, we need to write it to disk again. Then
255 * it must be read it again since the blob is encrypted each time
256 * it's written.
257 */
258 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100259 if ((rc = this->put(filename, keyBlob, userId)) != ResponseCode::NO_ERROR ||
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700260 (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100261 userState->getState())) != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700262 return rc;
263 }
264 }
265 }
266
267 /*
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100268 * This will upgrade software-backed keys to hardware-backed keys.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700269 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100270 if (rc == ResponseCode::NO_ERROR && type == TYPE_KEY_PAIR && keyBlob->isFallback()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700271 ResponseCode imported =
272 importKey(keyBlob->getValue(), keyBlob->getLength(), filename, userId,
273 keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
274
275 // The HAL allowed the import, reget the key to have the "fresh"
276 // version.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100277 if (imported == ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700278 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
279 }
280 }
281
282 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
283 if (keyBlob->getType() == TYPE_KEY_PAIR) {
284 keyBlob->setType(TYPE_KEYMASTER_10);
285 rc = this->put(filename, keyBlob, userId);
286 }
287
288 if (type != TYPE_ANY && keyBlob->getType() != type) {
289 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100290 return ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700291 }
292
293 return rc;
294}
295
296ResponseCode KeyStore::put(const char* filename, Blob* keyBlob, uid_t userId) {
297 UserState* userState = getUserState(userId);
298 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
299 mEntropy);
300}
301
302ResponseCode KeyStore::del(const char* filename, const BlobType type, uid_t userId) {
303 Blob keyBlob;
304 ResponseCode rc = get(filename, &keyBlob, type, userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100305 if (rc == ResponseCode::VALUE_CORRUPTED) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700306 // The file is corrupt, the best we can do is rm it.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100307 return (unlink(filename) && errno != ENOENT) ?
308 ResponseCode::SYSTEM_ERROR : ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700309 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100310 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700311 return rc;
312 }
313
Janis Danisevskis69c434a2017-01-30 10:27:10 +0000314 auto& dev = getDevice(keyBlob);
315
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100316 if (keyBlob.getType() == ::TYPE_KEY_PAIR || keyBlob.getType() == ::TYPE_KEYMASTER_10) {
Janis Danisevskis69c434a2017-01-30 10:27:10 +0000317 auto ret = KS_HANDLE_HIDL_ERROR(dev->deleteKey(blob2hidlVec(keyBlob)));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100318
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700319 // A device doesn't have to implement delete_key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100320 if (ret != ErrorCode::OK && ret != ErrorCode::UNIMPLEMENTED)
321 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700322 }
323
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100324 return (unlink(filename) && errno != ENOENT) ?
325 ResponseCode::SYSTEM_ERROR : ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700326}
327
Kenny Root07438c82012-11-02 15:41:02 -0700328/*
329 * Converts from the "escaped" format on disk to actual name.
330 * This will be smaller than the input string.
331 *
332 * Characters that should combine with the next at the end will be truncated.
333 */
334static size_t decode_key_length(const char* in, size_t length) {
335 size_t outLength = 0;
336
337 for (const char* end = in + length; in < end; in++) {
338 /* This combines with the next character. */
339 if (*in < '0' || *in > '~') {
340 continue;
341 }
342
343 outLength++;
344 }
345 return outLength;
346}
347
348static void decode_key(char* out, const char* in, size_t length) {
349 for (const char* end = in + length; in < end; in++) {
350 if (*in < '0' || *in > '~') {
351 /* Truncate combining characters at the end. */
352 if (in + 1 >= end) {
353 break;
354 }
355
356 *out = (*in++ - '+') << 6;
357 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800358 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700359 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800360 }
361 }
362 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800363}
364
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700365ResponseCode KeyStore::list(const android::String8& prefix,
366 android::Vector<android::String16>* matches, uid_t userId) {
Kenny Roota91203b2012-02-15 15:00:46 -0800367
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700368 UserState* userState = getUserState(userId);
369 size_t n = prefix.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800370
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700371 DIR* dir = opendir(userState->getUserDirName());
372 if (!dir) {
373 ALOGW("can't open directory for user: %s", strerror(errno));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100374 return ResponseCode::SYSTEM_ERROR;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700375 }
376
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700377 struct dirent* file;
378 while ((file = readdir(dir)) != NULL) {
379 // We only care about files.
380 if (file->d_type != DT_REG) {
381 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700382 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700383
384 // Skip anything that starts with a "."
385 if (file->d_name[0] == '.') {
386 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700387 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700388
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700389 if (!strncmp(prefix.string(), file->d_name, n)) {
390 const char* p = &file->d_name[n];
391 size_t plen = strlen(p);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700392
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700393 size_t extra = decode_key_length(p, plen);
394 char* match = (char*)malloc(extra + 1);
395 if (match != NULL) {
396 decode_key(match, p, plen);
397 matches->push(android::String16(match, extra));
398 free(match);
Chad Brubakerdf705172015-06-17 20:17:51 -0700399 } else {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700400 ALOGW("could not allocate match of size %zd", extra);
Chad Brubakerdf705172015-06-17 20:17:51 -0700401 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700402 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700403 }
404 closedir(dir);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100405 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700406}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700407
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700408void KeyStore::addGrant(const char* filename, uid_t granteeUid) {
409 const grant_t* existing = getGrant(filename, granteeUid);
410 if (existing == NULL) {
411 grant_t* grant = new grant_t;
412 grant->uid = granteeUid;
413 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
414 mGrants.add(grant);
415 }
416}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700417
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700418bool KeyStore::removeGrant(const char* filename, uid_t granteeUid) {
419 for (android::Vector<grant_t*>::iterator it(mGrants.begin()); it != mGrants.end(); it++) {
420 grant_t* grant = *it;
421 if (grant->uid == granteeUid &&
422 !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
423 mGrants.erase(it);
424 return true;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700425 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700426 }
427 return false;
428}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700429
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700430ResponseCode KeyStore::importKey(const uint8_t* key, size_t keyLen, const char* filename,
431 uid_t userId, int32_t flags) {
432 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
433 if (!pkcs8.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100434 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700435 }
436 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
437 if (!pkey.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100438 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700439 }
440 int type = EVP_PKEY_type(pkey->type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100441 AuthorizationSet params;
442 add_legacy_key_authorizations(type, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700443 switch (type) {
444 case EVP_PKEY_RSA:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100445 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700446 break;
447 case EVP_PKEY_EC:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100448 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700449 break;
450 default:
451 ALOGW("Unsupported key type %d", type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100452 return ResponseCode::SYSTEM_ERROR;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700453 }
454
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100455 AuthorizationSet opParams(params);
456 hidl_vec<uint8_t> blob;
Kenny Root07438c82012-11-02 15:41:02 -0700457
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100458 ErrorCode error;
459 auto hidlCb = [&] (ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
460 const KeyCharacteristics& /* ignored */) {
461 error = ret;
462 if (error != ErrorCode::OK) return;
463 blob = keyBlob;
464 };
465 auto input = blob2hidlVec(key, keyLen);
Kenny Roota91203b2012-02-15 15:00:46 -0800466
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100467 ErrorCode rc = KS_HANDLE_HIDL_ERROR(
468 mDevice->importKey(params.hidl_data(), KeyFormat::PKCS8, input, hidlCb));
469 if (rc != ErrorCode::OK) return ResponseCode::SYSTEM_ERROR;
470 if (error != ErrorCode::OK) {
471 ALOGE("Keymaster error %d importing key pair", error);
472 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700473 }
474
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100475 Blob keyBlob(&blob[0], blob.size(), NULL, 0, TYPE_KEYMASTER_10);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700476
477 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100478 keyBlob.setFallback(false);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700479
480 return put(filename, &keyBlob, userId);
481}
482
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100483bool KeyStore::isHardwareBacked(const android::String16& /*keyType*/) const {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700484 if (mDevice == NULL) {
485 ALOGW("can't get keymaster device");
486 return false;
487 }
Janis Danisevskise2b6caf2017-03-02 16:37:10 -0800488
489 bool isSecure = false;
490 auto hidlcb = [&] (bool _isSecure, bool, bool, bool) {
491 isSecure = _isSecure;
492 };
493 auto rc = mDevice->getHardwareFeatures(hidlcb);
494 if (!rc.isOk()) {
495 ALOGE("Communication with keymaster HAL failed while retrieving hardware features (%s)",
496 rc.description().c_str());
497 return false;
498 }
499 return isSecure;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700500}
501
502ResponseCode KeyStore::getKeyForName(Blob* keyBlob, const android::String8& keyName,
503 const uid_t uid, const BlobType type) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400504 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid, type));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700505 uid_t userId = get_user_id(uid);
506
507 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100508 if (responseCode == ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700509 return responseCode;
Riley Spahneaabae92014-06-30 12:39:52 -0700510 }
511
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700512 // If this is one of the legacy UID->UID mappings, use it.
513 uid_t euid = get_keystore_euid(uid);
514 if (euid != uid) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400515 filepath8 = getKeyNameForUidWithDir(keyName, euid, type);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700516 responseCode = get(filepath8.string(), keyBlob, type, userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100517 if (responseCode == ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700518 return responseCode;
519 }
520 }
521
522 // They might be using a granted key.
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400523 android::String8 filename8 = getKeyName(keyName, type);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700524 char* end;
525 strtoul(filename8.string(), &end, 10);
526 if (end[0] != '_' || end[1] == 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100527 return ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700528 }
529 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
530 filename8.string());
531 if (!hasGrant(filepath8.string(), uid)) {
532 return responseCode;
533 }
534
535 // It is a granted key. Try to load it.
536 return get(filepath8.string(), keyBlob, type, userId);
537}
538
539UserState* KeyStore::getUserState(uid_t userId) {
540 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
541 it++) {
542 UserState* state = *it;
543 if (state->getUserId() == userId) {
544 return state;
545 }
546 }
547
548 UserState* userState = new UserState(userId);
549 if (!userState->initialize()) {
550 /* There's not much we can do if initialization fails. Trying to
551 * unlock the keystore for that user will fail as well, so any
552 * subsequent request for this user will just return SYSTEM_ERROR.
553 */
554 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
555 }
556 mMasterKeys.add(userState);
557 return userState;
558}
559
560UserState* KeyStore::getUserStateByUid(uid_t uid) {
561 uid_t userId = get_user_id(uid);
562 return getUserState(userId);
563}
564
565const UserState* KeyStore::getUserState(uid_t userId) const {
566 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
567 it != mMasterKeys.end(); it++) {
568 UserState* state = *it;
569 if (state->getUserId() == userId) {
570 return state;
571 }
572 }
573
574 return NULL;
575}
576
577const UserState* KeyStore::getUserStateByUid(uid_t uid) const {
578 uid_t userId = get_user_id(uid);
579 return getUserState(userId);
580}
581
582const grant_t* KeyStore::getGrant(const char* filename, uid_t uid) const {
583 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin()); it != mGrants.end(); it++) {
584 grant_t* grant = *it;
585 if (grant->uid == uid &&
586 !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
587 return grant;
588 }
589 }
590 return NULL;
591}
592
593bool KeyStore::upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
594 const BlobType type, uid_t uid) {
595 bool updated = false;
596 uint8_t version = oldVersion;
597
598 /* From V0 -> V1: All old types were unknown */
599 if (version == 0) {
600 ALOGV("upgrading to version 1 and setting type %d", type);
601
602 blob->setType(type);
603 if (type == TYPE_KEY_PAIR) {
604 importBlobAsKey(blob, filename, uid);
605 }
606 version = 1;
607 updated = true;
608 }
609
610 /* From V1 -> V2: All old keys were encrypted */
611 if (version == 1) {
612 ALOGV("upgrading to version 2");
613
614 blob->setEncrypted(true);
615 version = 2;
616 updated = true;
Kenny Roota91203b2012-02-15 15:00:46 -0800617 }
Kenny Root07438c82012-11-02 15:41:02 -0700618
619 /*
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700620 * If we've updated, set the key blob to the right version
621 * and write it.
Kenny Root07438c82012-11-02 15:41:02 -0700622 */
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700623 if (updated) {
624 ALOGV("updated and writing file %s", filename);
625 blob->setVersion(version);
626 }
Kenny Root70e3a862012-02-15 17:20:23 -0800627
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700628 return updated;
629}
630
631struct BIO_Delete {
632 void operator()(BIO* p) const { BIO_free(p); }
633};
634typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
635
636ResponseCode KeyStore::importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
637 // We won't even write to the blob directly with this BIO, so const_cast is okay.
638 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
639 if (b.get() == NULL) {
640 ALOGE("Problem instantiating BIO");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100641 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700642 }
643
644 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
645 if (pkey.get() == NULL) {
646 ALOGE("Couldn't read old PEM file");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100647 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700648 }
649
650 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
651 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
652 if (len < 0) {
653 ALOGE("Couldn't measure PKCS#8 length");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100654 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700655 }
656
657 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
658 uint8_t* tmp = pkcs8key.get();
659 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
660 ALOGE("Couldn't convert to PKCS#8");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100661 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700662 }
663
664 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
665 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100666 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700667 return rc;
668 }
669
670 return get(filename, blob, TYPE_KEY_PAIR, uid);
671}
672
673void KeyStore::readMetaData() {
674 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
675 if (in < 0) {
676 return;
677 }
678 size_t fileLength = readFully(in, (uint8_t*)&mMetaData, sizeof(mMetaData));
679 if (fileLength != sizeof(mMetaData)) {
680 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength, sizeof(mMetaData));
681 }
682 close(in);
683}
684
685void KeyStore::writeMetaData() {
686 const char* tmpFileName = ".metadata.tmp";
687 int out =
688 TEMP_FAILURE_RETRY(open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
689 if (out < 0) {
690 ALOGE("couldn't write metadata file: %s", strerror(errno));
691 return;
692 }
693 size_t fileLength = writeFully(out, (uint8_t*)&mMetaData, sizeof(mMetaData));
694 if (fileLength != sizeof(mMetaData)) {
695 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
696 sizeof(mMetaData));
697 }
698 close(out);
699 rename(tmpFileName, sMetaDataFile);
700}
701
702bool KeyStore::upgradeKeystore() {
703 bool upgraded = false;
704
705 if (mMetaData.version == 0) {
706 UserState* userState = getUserStateByUid(0);
707
708 // Initialize first so the directory is made.
709 userState->initialize();
710
711 // Migrate the old .masterkey file to user 0.
712 if (access(sOldMasterKey, R_OK) == 0) {
713 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
714 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
715 return false;
716 }
717 }
718
719 // Initialize again in case we had a key.
720 userState->initialize();
721
722 // Try to migrate existing keys.
723 DIR* dir = opendir(".");
724 if (!dir) {
725 // Give up now; maybe we can upgrade later.
726 ALOGE("couldn't open keystore's directory; something is wrong");
727 return false;
728 }
729
730 struct dirent* file;
731 while ((file = readdir(dir)) != NULL) {
732 // We only care about files.
733 if (file->d_type != DT_REG) {
734 continue;
735 }
736
737 // Skip anything that starts with a "."
738 if (file->d_name[0] == '.') {
739 continue;
740 }
741
742 // Find the current file's user.
743 char* end;
744 unsigned long thisUid = strtoul(file->d_name, &end, 10);
745 if (end[0] != '_' || end[1] == 0) {
746 continue;
747 }
748 UserState* otherUser = getUserStateByUid(thisUid);
749 if (otherUser->getUserId() != 0) {
750 unlinkat(dirfd(dir), file->d_name, 0);
751 }
752
753 // Rename the file into user directory.
754 DIR* otherdir = opendir(otherUser->getUserDirName());
755 if (otherdir == NULL) {
756 ALOGW("couldn't open user directory for rename");
757 continue;
758 }
759 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
760 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
761 }
762 closedir(otherdir);
763 }
764 closedir(dir);
765
766 mMetaData.version = 1;
767 upgraded = true;
768 }
769
770 return upgraded;
Kenny Roota91203b2012-02-15 15:00:46 -0800771}