blob: 0d8dc21bd741c7ae895c90e7c330560e7756d679 [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
Shawn Willden6507c272016-01-05 22:51:48 -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
Shawn Willden6507c272016-01-05 22:51:48 -070017#include "keystore.h"
Kenny Root07438c82012-11-02 15:41:02 -070018
Kenny Roota91203b2012-02-15 15:00:46 -080019#include <dirent.h>
20#include <fcntl.h>
Kenny Roota91203b2012-02-15 15:00:46 -080021
Kenny Root822c3a92012-03-23 16:34:39 -070022#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080023
Shawn Willden6507c272016-01-05 22:51:48 -070024#include <utils/String16.h>
Kenny Root70e3a862012-02-15 17:20:23 -080025
Kenny Root07438c82012-11-02 15:41:02 -070026#include <keystore/IKeystoreService.h>
Kenny Root07438c82012-11-02 15:41:02 -070027
Shawn Willden6507c272016-01-05 22:51:48 -070028#include "keystore_utils.h"
29#include "permissions.h"
Kenny Roota91203b2012-02-15 15:00:46 -080030
Shawn Willden6507c272016-01-05 22:51:48 -070031const char* KeyStore::sOldMasterKey = ".masterkey";
32const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Roota91203b2012-02-15 15:00:46 -080033
Shawn Willden6507c272016-01-05 22:51:48 -070034const android::String16 KeyStore::sRSAKeyType("RSA");
35const android::String16 KeyStore::sECKeyType("EC");
Riley Spahneaabae92014-06-30 12:39:52 -070036
Shawn Willden6507c272016-01-05 22:51:48 -070037KeyStore::KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
38 : mEntropy(entropy), mDevice(device), mFallbackDevice(fallback) {
39 memset(&mMetaData, '\0', sizeof(mMetaData));
Kenny Root70e3a862012-02-15 17:20:23 -080040}
41
Shawn Willden6507c272016-01-05 22:51:48 -070042KeyStore::~KeyStore() {
43 for (android::Vector<grant_t*>::iterator it(mGrants.begin()); it != mGrants.end(); it++) {
44 delete *it;
Shawn Willden55268b52015-07-28 11:06:00 -060045 }
Shawn Willden6507c272016-01-05 22:51:48 -070046 mGrants.clear();
Shawn Willden55268b52015-07-28 11:06:00 -060047
Shawn Willden6507c272016-01-05 22:51:48 -070048 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
49 it++) {
50 delete *it;
Shawn Willden55268b52015-07-28 11:06:00 -060051 }
Shawn Willden6507c272016-01-05 22:51:48 -070052 mMasterKeys.clear();
Shawn Willden55268b52015-07-28 11:06:00 -060053}
54
Shawn Willden6507c272016-01-05 22:51:48 -070055ResponseCode KeyStore::initialize() {
56 readMetaData();
57 if (upgradeKeystore()) {
58 writeMetaData();
Shawn Willden55268b52015-07-28 11:06:00 -060059 }
60
Shawn Willden6507c272016-01-05 22:51:48 -070061 return ::NO_ERROR;
Shawn Willden55268b52015-07-28 11:06:00 -060062}
63
Shawn Willden6507c272016-01-05 22:51:48 -070064ResponseCode KeyStore::initializeUser(const android::String8& pw, uid_t userId) {
65 UserState* userState = getUserState(userId);
66 return userState->initialize(pw, mEntropy);
Chad Brubakerfc18edc2015-01-12 15:17:18 -080067}
68
Shawn Willden6507c272016-01-05 22:51:48 -070069ResponseCode KeyStore::copyMasterKey(uid_t srcUser, uid_t dstUser) {
70 UserState* userState = getUserState(dstUser);
71 UserState* initState = getUserState(srcUser);
72 return userState->copyMasterKey(initState);
Kenny Root70e3a862012-02-15 17:20:23 -080073}
74
Shawn Willden6507c272016-01-05 22:51:48 -070075ResponseCode KeyStore::writeMasterKey(const android::String8& pw, uid_t userId) {
76 UserState* userState = getUserState(userId);
77 return userState->writeMasterKey(pw, mEntropy);
Shawn Willden55268b52015-07-28 11:06:00 -060078}
79
Shawn Willden6507c272016-01-05 22:51:48 -070080ResponseCode KeyStore::readMasterKey(const android::String8& pw, uid_t userId) {
81 UserState* userState = getUserState(userId);
82 return userState->readMasterKey(pw, mEntropy);
Kenny Root49468902013-03-19 13:41:33 -070083}
84
Kenny Roota91203b2012-02-15 15:00:46 -080085/* Here is the encoding of keys. This is necessary in order to allow arbitrary
86 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
87 * into two bytes. The first byte is one of [+-.] which represents the first
88 * two bits of the character. The second byte encodes the rest of the bits into
89 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
90 * that Base64 cannot be used here due to the need of prefix match on keys. */
91
Kenny Root655b9582013-04-04 08:37:42 -070092static size_t encode_key_length(const android::String8& keyName) {
93 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
94 size_t length = keyName.length();
95 for (int i = length; i > 0; --i, ++in) {
96 if (*in < '0' || *in > '~') {
97 ++length;
98 }
99 }
100 return length;
101}
102
Kenny Root07438c82012-11-02 15:41:02 -0700103static int encode_key(char* out, const android::String8& keyName) {
104 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
105 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800106 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700107 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800108 *out = '+' + (*in >> 6);
109 *++out = '0' + (*in & 0x3F);
110 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700111 } else {
112 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800113 }
114 }
115 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800116 return length;
117}
118
Shawn Willden6507c272016-01-05 22:51:48 -0700119android::String8 KeyStore::getKeyName(const android::String8& keyName) {
120 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
121 encode_key(encoded, keyName);
122 return android::String8(encoded);
123}
124
125android::String8 KeyStore::getKeyNameForUid(const android::String8& keyName, uid_t uid) {
126 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
127 encode_key(encoded, keyName);
128 return android::String8::format("%u_%s", uid, encoded);
129}
130
131android::String8 KeyStore::getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
132 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
133 encode_key(encoded, keyName);
134 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
135 encoded);
136}
137
138void KeyStore::resetUser(uid_t userId, bool keepUnenryptedEntries) {
139 android::String8 prefix("");
140 android::Vector<android::String16> aliases;
141 UserState* userState = getUserState(userId);
142 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
143 return;
144 }
145 for (uint32_t i = 0; i < aliases.size(); i++) {
146 android::String8 filename(aliases[i]);
147 filename = android::String8::format("%s/%s", userState->getUserDirName(),
148 getKeyName(filename).string());
149 bool shouldDelete = true;
150 if (keepUnenryptedEntries) {
151 Blob blob;
152 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
153
154 /* get can fail if the blob is encrypted and the state is
155 * not unlocked, only skip deleting blobs that were loaded and
156 * who are not encrypted. If there are blobs we fail to read for
157 * other reasons err on the safe side and delete them since we
158 * can't tell if they're encrypted.
159 */
160 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
161 }
162 if (shouldDelete) {
163 del(filename, ::TYPE_ANY, userId);
164 }
165 }
166 if (!userState->deleteMasterKey()) {
167 ALOGE("Failed to delete user %d's master key", userId);
168 }
169 if (!keepUnenryptedEntries) {
170 if (!userState->reset()) {
171 ALOGE("Failed to remove user %d's directory", userId);
172 }
173 }
174}
175
176bool KeyStore::isEmpty(uid_t userId) const {
177 const UserState* userState = getUserState(userId);
178 if (userState == NULL) {
179 return true;
180 }
181
182 DIR* dir = opendir(userState->getUserDirName());
183 if (!dir) {
184 return true;
185 }
186
187 bool result = true;
188 struct dirent* file;
189 while ((file = readdir(dir)) != NULL) {
190 // We only care about files.
191 if (file->d_type != DT_REG) {
192 continue;
193 }
194
195 // Skip anything that starts with a "."
196 if (file->d_name[0] == '.') {
197 continue;
198 }
199
200 result = false;
201 break;
202 }
203 closedir(dir);
204 return result;
205}
206
207void KeyStore::lock(uid_t userId) {
208 UserState* userState = getUserState(userId);
209 userState->zeroizeMasterKeysInMemory();
210 userState->setState(STATE_LOCKED);
211}
212
213ResponseCode KeyStore::get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
214 UserState* userState = getUserState(userId);
215 ResponseCode rc =
216 keyBlob->readBlob(filename, userState->getDecryptionKey(), userState->getState());
217 if (rc != NO_ERROR) {
218 return rc;
219 }
220
221 const uint8_t version = keyBlob->getVersion();
222 if (version < CURRENT_BLOB_VERSION) {
223 /* If we upgrade the key, we need to write it to disk again. Then
224 * it must be read it again since the blob is encrypted each time
225 * it's written.
226 */
227 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
228 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR ||
229 (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
230 userState->getState())) != NO_ERROR) {
231 return rc;
232 }
233 }
234 }
235
236 /*
237 * This will upgrade software-backed keys to hardware-backed keys when
238 * the HAL for the device supports the newer key types.
239 */
240 if (rc == NO_ERROR && type == TYPE_KEY_PAIR &&
241 mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2 &&
242 keyBlob->isFallback()) {
243 ResponseCode imported =
244 importKey(keyBlob->getValue(), keyBlob->getLength(), filename, userId,
245 keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
246
247 // The HAL allowed the import, reget the key to have the "fresh"
248 // version.
249 if (imported == NO_ERROR) {
250 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
251 }
252 }
253
254 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
255 if (keyBlob->getType() == TYPE_KEY_PAIR) {
256 keyBlob->setType(TYPE_KEYMASTER_10);
257 rc = this->put(filename, keyBlob, userId);
258 }
259
260 if (type != TYPE_ANY && keyBlob->getType() != type) {
261 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
262 return KEY_NOT_FOUND;
263 }
264
265 return rc;
266}
267
268ResponseCode KeyStore::put(const char* filename, Blob* keyBlob, uid_t userId) {
269 UserState* userState = getUserState(userId);
270 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
271 mEntropy);
272}
273
274ResponseCode KeyStore::del(const char* filename, const BlobType type, uid_t userId) {
275 Blob keyBlob;
276 ResponseCode rc = get(filename, &keyBlob, type, userId);
277 if (rc == ::VALUE_CORRUPTED) {
278 // The file is corrupt, the best we can do is rm it.
279 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
280 }
281 if (rc != ::NO_ERROR) {
282 return rc;
283 }
284
285 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
286 // A device doesn't have to implement delete_key.
287 if (mDevice->delete_key != NULL && !keyBlob.isFallback()) {
288 keymaster_key_blob_t blob = {keyBlob.getValue(),
289 static_cast<size_t>(keyBlob.getLength())};
290 if (mDevice->delete_key(mDevice, &blob)) {
291 rc = ::SYSTEM_ERROR;
292 }
293 }
294 }
295 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
296 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
297 if (dev->delete_key) {
298 keymaster_key_blob_t blob;
299 blob.key_material = keyBlob.getValue();
300 blob.key_material_size = keyBlob.getLength();
301 dev->delete_key(dev, &blob);
302 }
303 }
304 if (rc != ::NO_ERROR) {
305 return rc;
306 }
307
308 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
309}
310
Kenny Root07438c82012-11-02 15:41:02 -0700311/*
312 * Converts from the "escaped" format on disk to actual name.
313 * This will be smaller than the input string.
314 *
315 * Characters that should combine with the next at the end will be truncated.
316 */
317static size_t decode_key_length(const char* in, size_t length) {
318 size_t outLength = 0;
319
320 for (const char* end = in + length; in < end; in++) {
321 /* This combines with the next character. */
322 if (*in < '0' || *in > '~') {
323 continue;
324 }
325
326 outLength++;
327 }
328 return outLength;
329}
330
331static void decode_key(char* out, const char* in, size_t length) {
332 for (const char* end = in + length; in < end; in++) {
333 if (*in < '0' || *in > '~') {
334 /* Truncate combining characters at the end. */
335 if (in + 1 >= end) {
336 break;
337 }
338
339 *out = (*in++ - '+') << 6;
340 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800341 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700342 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800343 }
344 }
345 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800346}
347
Shawn Willden6507c272016-01-05 22:51:48 -0700348ResponseCode KeyStore::list(const android::String8& prefix,
349 android::Vector<android::String16>* matches, uid_t userId) {
Kenny Roota91203b2012-02-15 15:00:46 -0800350
Shawn Willden6507c272016-01-05 22:51:48 -0700351 UserState* userState = getUserState(userId);
352 size_t n = prefix.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800353
Shawn Willden6507c272016-01-05 22:51:48 -0700354 DIR* dir = opendir(userState->getUserDirName());
355 if (!dir) {
356 ALOGW("can't open directory for user: %s", strerror(errno));
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700357 return ::SYSTEM_ERROR;
358 }
359
Shawn Willden6507c272016-01-05 22:51:48 -0700360 struct dirent* file;
361 while ((file = readdir(dir)) != NULL) {
362 // We only care about files.
363 if (file->d_type != DT_REG) {
364 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700365 }
Shawn Willden6507c272016-01-05 22:51:48 -0700366
367 // Skip anything that starts with a "."
368 if (file->d_name[0] == '.') {
369 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700370 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700371
Shawn Willden6507c272016-01-05 22:51:48 -0700372 if (!strncmp(prefix.string(), file->d_name, n)) {
373 const char* p = &file->d_name[n];
374 size_t plen = strlen(p);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700375
Shawn Willden6507c272016-01-05 22:51:48 -0700376 size_t extra = decode_key_length(p, plen);
377 char* match = (char*)malloc(extra + 1);
378 if (match != NULL) {
379 decode_key(match, p, plen);
380 matches->push(android::String16(match, extra));
381 free(match);
Chad Brubakerdf705172015-06-17 20:17:51 -0700382 } else {
Shawn Willden6507c272016-01-05 22:51:48 -0700383 ALOGW("could not allocate match of size %zd", extra);
Chad Brubakerdf705172015-06-17 20:17:51 -0700384 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700385 }
Shawn Willden6507c272016-01-05 22:51:48 -0700386 }
387 closedir(dir);
388 return ::NO_ERROR;
389}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700390
Shawn Willden6507c272016-01-05 22:51:48 -0700391void KeyStore::addGrant(const char* filename, uid_t granteeUid) {
392 const grant_t* existing = getGrant(filename, granteeUid);
393 if (existing == NULL) {
394 grant_t* grant = new grant_t;
395 grant->uid = granteeUid;
396 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
397 mGrants.add(grant);
398 }
399}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700400
Shawn Willden6507c272016-01-05 22:51:48 -0700401bool KeyStore::removeGrant(const char* filename, uid_t granteeUid) {
402 for (android::Vector<grant_t*>::iterator it(mGrants.begin()); it != mGrants.end(); it++) {
403 grant_t* grant = *it;
404 if (grant->uid == granteeUid &&
405 !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
406 mGrants.erase(it);
407 return true;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700408 }
Shawn Willden6507c272016-01-05 22:51:48 -0700409 }
410 return false;
411}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700412
Shawn Willden6507c272016-01-05 22:51:48 -0700413ResponseCode KeyStore::importKey(const uint8_t* key, size_t keyLen, const char* filename,
414 uid_t userId, int32_t flags) {
415 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
416 if (!pkcs8.get()) {
417 return ::SYSTEM_ERROR;
418 }
419 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
420 if (!pkey.get()) {
421 return ::SYSTEM_ERROR;
422 }
423 int type = EVP_PKEY_type(pkey->type);
424 android::KeymasterArguments params;
425 add_legacy_key_authorizations(type, &params.params);
426 switch (type) {
427 case EVP_PKEY_RSA:
428 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
429 break;
430 case EVP_PKEY_EC:
431 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
432 break;
433 default:
434 ALOGW("Unsupported key type %d", type);
435 return ::SYSTEM_ERROR;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700436 }
437
Shawn Willden6507c272016-01-05 22:51:48 -0700438 std::vector<keymaster_key_param_t> opParams(params.params);
439 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
440 keymaster_blob_t input = {key, keyLen};
441 keymaster_key_blob_t blob = {nullptr, 0};
442 bool isFallback = false;
443 keymaster_error_t error = mDevice->import_key(mDevice, &inParams, KM_KEY_FORMAT_PKCS8, &input,
444 &blob, NULL /* characteristics */);
445 if (error != KM_ERROR_OK) {
446 ALOGE("Keymaster error %d importing key pair, falling back", error);
Kenny Root07438c82012-11-02 15:41:02 -0700447
Shawn Willden6507c272016-01-05 22:51:48 -0700448 /*
449 * There should be no way to get here. Fallback shouldn't ever really happen
450 * because the main device may be many (SW, KM0/SW hybrid, KM1/SW hybrid), but it must
451 * provide full support of the API. In any case, we'll do the fallback just for
452 * consistency... and I suppose to cover for broken HW implementations.
453 */
454 error = mFallbackDevice->import_key(mFallbackDevice, &inParams, KM_KEY_FORMAT_PKCS8, &input,
455 &blob, NULL /* characteristics */);
456 isFallback = true;
Kenny Roota91203b2012-02-15 15:00:46 -0800457
Shawn Willden6507c272016-01-05 22:51:48 -0700458 if (error) {
459 ALOGE("Keymaster error while importing key pair with fallback: %d", error);
460 return SYSTEM_ERROR;
Riley Spahneaabae92014-06-30 12:39:52 -0700461 }
Shawn Willden6507c272016-01-05 22:51:48 -0700462 }
463
464 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, TYPE_KEYMASTER_10);
465 free(const_cast<uint8_t*>(blob.key_material));
466
467 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
468 keyBlob.setFallback(isFallback);
469
470 return put(filename, &keyBlob, userId);
471}
472
473bool KeyStore::isHardwareBacked(const android::String16& keyType) const {
474 if (mDevice == NULL) {
475 ALOGW("can't get keymaster device");
476 return false;
477 }
478
479 if (sRSAKeyType == keyType) {
480 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
Riley Spahneaabae92014-06-30 12:39:52 -0700481 } else {
Shawn Willden6507c272016-01-05 22:51:48 -0700482 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0 &&
483 (mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2);
484 }
485}
486
487ResponseCode KeyStore::getKeyForName(Blob* keyBlob, const android::String8& keyName,
488 const uid_t uid, const BlobType type) {
489 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
490 uid_t userId = get_user_id(uid);
491
492 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
493 if (responseCode == NO_ERROR) {
494 return responseCode;
Riley Spahneaabae92014-06-30 12:39:52 -0700495 }
496
Shawn Willden6507c272016-01-05 22:51:48 -0700497 // If this is one of the legacy UID->UID mappings, use it.
498 uid_t euid = get_keystore_euid(uid);
499 if (euid != uid) {
500 filepath8 = getKeyNameForUidWithDir(keyName, euid);
501 responseCode = get(filepath8.string(), keyBlob, type, userId);
502 if (responseCode == NO_ERROR) {
503 return responseCode;
504 }
505 }
506
507 // They might be using a granted key.
508 android::String8 filename8 = getKeyName(keyName);
509 char* end;
510 strtoul(filename8.string(), &end, 10);
511 if (end[0] != '_' || end[1] == 0) {
512 return KEY_NOT_FOUND;
513 }
514 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
515 filename8.string());
516 if (!hasGrant(filepath8.string(), uid)) {
517 return responseCode;
518 }
519
520 // It is a granted key. Try to load it.
521 return get(filepath8.string(), keyBlob, type, userId);
522}
523
524UserState* KeyStore::getUserState(uid_t userId) {
525 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
526 it++) {
527 UserState* state = *it;
528 if (state->getUserId() == userId) {
529 return state;
530 }
531 }
532
533 UserState* userState = new UserState(userId);
534 if (!userState->initialize()) {
535 /* There's not much we can do if initialization fails. Trying to
536 * unlock the keystore for that user will fail as well, so any
537 * subsequent request for this user will just return SYSTEM_ERROR.
538 */
539 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
540 }
541 mMasterKeys.add(userState);
542 return userState;
543}
544
545UserState* KeyStore::getUserStateByUid(uid_t uid) {
546 uid_t userId = get_user_id(uid);
547 return getUserState(userId);
548}
549
550const UserState* KeyStore::getUserState(uid_t userId) const {
551 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
552 it != mMasterKeys.end(); it++) {
553 UserState* state = *it;
554 if (state->getUserId() == userId) {
555 return state;
556 }
557 }
558
559 return NULL;
560}
561
562const UserState* KeyStore::getUserStateByUid(uid_t uid) const {
563 uid_t userId = get_user_id(uid);
564 return getUserState(userId);
565}
566
567const grant_t* KeyStore::getGrant(const char* filename, uid_t uid) const {
568 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin()); it != mGrants.end(); it++) {
569 grant_t* grant = *it;
570 if (grant->uid == uid &&
571 !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
572 return grant;
573 }
574 }
575 return NULL;
576}
577
578bool KeyStore::upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
579 const BlobType type, uid_t uid) {
580 bool updated = false;
581 uint8_t version = oldVersion;
582
583 /* From V0 -> V1: All old types were unknown */
584 if (version == 0) {
585 ALOGV("upgrading to version 1 and setting type %d", type);
586
587 blob->setType(type);
588 if (type == TYPE_KEY_PAIR) {
589 importBlobAsKey(blob, filename, uid);
590 }
591 version = 1;
592 updated = true;
593 }
594
595 /* From V1 -> V2: All old keys were encrypted */
596 if (version == 1) {
597 ALOGV("upgrading to version 2");
598
599 blob->setEncrypted(true);
600 version = 2;
601 updated = true;
Kenny Roota91203b2012-02-15 15:00:46 -0800602 }
Kenny Root07438c82012-11-02 15:41:02 -0700603
604 /*
Shawn Willden6507c272016-01-05 22:51:48 -0700605 * If we've updated, set the key blob to the right version
606 * and write it.
Kenny Root07438c82012-11-02 15:41:02 -0700607 */
Shawn Willden6507c272016-01-05 22:51:48 -0700608 if (updated) {
609 ALOGV("updated and writing file %s", filename);
610 blob->setVersion(version);
611 }
Kenny Root70e3a862012-02-15 17:20:23 -0800612
Shawn Willden6507c272016-01-05 22:51:48 -0700613 return updated;
614}
615
616struct BIO_Delete {
617 void operator()(BIO* p) const { BIO_free(p); }
618};
619typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
620
621ResponseCode KeyStore::importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
622 // We won't even write to the blob directly with this BIO, so const_cast is okay.
623 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
624 if (b.get() == NULL) {
625 ALOGE("Problem instantiating BIO");
626 return SYSTEM_ERROR;
627 }
628
629 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
630 if (pkey.get() == NULL) {
631 ALOGE("Couldn't read old PEM file");
632 return SYSTEM_ERROR;
633 }
634
635 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
636 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
637 if (len < 0) {
638 ALOGE("Couldn't measure PKCS#8 length");
639 return SYSTEM_ERROR;
640 }
641
642 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
643 uint8_t* tmp = pkcs8key.get();
644 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
645 ALOGE("Couldn't convert to PKCS#8");
646 return SYSTEM_ERROR;
647 }
648
649 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
650 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
651 if (rc != NO_ERROR) {
652 return rc;
653 }
654
655 return get(filename, blob, TYPE_KEY_PAIR, uid);
656}
657
658void KeyStore::readMetaData() {
659 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
660 if (in < 0) {
661 return;
662 }
663 size_t fileLength = readFully(in, (uint8_t*)&mMetaData, sizeof(mMetaData));
664 if (fileLength != sizeof(mMetaData)) {
665 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength, sizeof(mMetaData));
666 }
667 close(in);
668}
669
670void KeyStore::writeMetaData() {
671 const char* tmpFileName = ".metadata.tmp";
672 int out =
673 TEMP_FAILURE_RETRY(open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
674 if (out < 0) {
675 ALOGE("couldn't write metadata file: %s", strerror(errno));
676 return;
677 }
678 size_t fileLength = writeFully(out, (uint8_t*)&mMetaData, sizeof(mMetaData));
679 if (fileLength != sizeof(mMetaData)) {
680 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
681 sizeof(mMetaData));
682 }
683 close(out);
684 rename(tmpFileName, sMetaDataFile);
685}
686
687bool KeyStore::upgradeKeystore() {
688 bool upgraded = false;
689
690 if (mMetaData.version == 0) {
691 UserState* userState = getUserStateByUid(0);
692
693 // Initialize first so the directory is made.
694 userState->initialize();
695
696 // Migrate the old .masterkey file to user 0.
697 if (access(sOldMasterKey, R_OK) == 0) {
698 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
699 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
700 return false;
701 }
702 }
703
704 // Initialize again in case we had a key.
705 userState->initialize();
706
707 // Try to migrate existing keys.
708 DIR* dir = opendir(".");
709 if (!dir) {
710 // Give up now; maybe we can upgrade later.
711 ALOGE("couldn't open keystore's directory; something is wrong");
712 return false;
713 }
714
715 struct dirent* file;
716 while ((file = readdir(dir)) != NULL) {
717 // We only care about files.
718 if (file->d_type != DT_REG) {
719 continue;
720 }
721
722 // Skip anything that starts with a "."
723 if (file->d_name[0] == '.') {
724 continue;
725 }
726
727 // Find the current file's user.
728 char* end;
729 unsigned long thisUid = strtoul(file->d_name, &end, 10);
730 if (end[0] != '_' || end[1] == 0) {
731 continue;
732 }
733 UserState* otherUser = getUserStateByUid(thisUid);
734 if (otherUser->getUserId() != 0) {
735 unlinkat(dirfd(dir), file->d_name, 0);
736 }
737
738 // Rename the file into user directory.
739 DIR* otherdir = opendir(otherUser->getUserDirName());
740 if (otherdir == NULL) {
741 ALOGW("couldn't open user directory for rename");
742 continue;
743 }
744 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
745 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
746 }
747 closedir(otherdir);
748 }
749 closedir(dir);
750
751 mMetaData.version = 1;
752 upgraded = true;
753 }
754
755 return upgraded;
Kenny Roota91203b2012-02-15 15:00:46 -0800756}