blob: 0b86e834427cf570f4e263cfff951d1a135b999a [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
Shawn Willdenc1d1fee2016-01-26 22:44:56 -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 Willdenc1d1fee2016-01-26 22:44:56 -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 Willdenc1d1fee2016-01-26 22:44:56 -070028#include "keystore_utils.h"
29#include "permissions.h"
Kenny Roota91203b2012-02-15 15:00:46 -080030
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070031const char* KeyStore::sOldMasterKey = ".masterkey";
32const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Roota91203b2012-02-15 15:00:46 -080033
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070034const android::String16 KeyStore::sRSAKeyType("RSA");
Riley Spahneaabae92014-06-30 12:39:52 -070035
Shawn Willden715d0232016-01-21 00:45:13 -070036KeyStore::KeyStore(Entropy* entropy, keymaster2_device_t* device, keymaster2_device_t* fallback)
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070037 : mEntropy(entropy), mDevice(device), mFallbackDevice(fallback) {
38 memset(&mMetaData, '\0', sizeof(mMetaData));
Kenny Root70e3a862012-02-15 17:20:23 -080039}
40
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070041KeyStore::~KeyStore() {
42 for (android::Vector<grant_t*>::iterator it(mGrants.begin()); it != mGrants.end(); it++) {
43 delete *it;
Shawn Willden55268b52015-07-28 11:06:00 -060044 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070045 mGrants.clear();
Shawn Willden55268b52015-07-28 11:06:00 -060046
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070047 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
48 it++) {
49 delete *it;
Shawn Willden55268b52015-07-28 11:06:00 -060050 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070051 mMasterKeys.clear();
Shawn Willden55268b52015-07-28 11:06:00 -060052}
53
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070054ResponseCode KeyStore::initialize() {
55 readMetaData();
56 if (upgradeKeystore()) {
57 writeMetaData();
Shawn Willden55268b52015-07-28 11:06:00 -060058 }
59
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070060 return ::NO_ERROR;
Shawn Willden55268b52015-07-28 11:06:00 -060061}
62
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070063ResponseCode KeyStore::initializeUser(const android::String8& pw, uid_t userId) {
64 UserState* userState = getUserState(userId);
65 return userState->initialize(pw, mEntropy);
Chad Brubakerfc18edc2015-01-12 15:17:18 -080066}
67
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070068ResponseCode KeyStore::copyMasterKey(uid_t srcUser, uid_t dstUser) {
69 UserState* userState = getUserState(dstUser);
70 UserState* initState = getUserState(srcUser);
71 return userState->copyMasterKey(initState);
Kenny Root70e3a862012-02-15 17:20:23 -080072}
73
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070074ResponseCode KeyStore::writeMasterKey(const android::String8& pw, uid_t userId) {
75 UserState* userState = getUserState(userId);
76 return userState->writeMasterKey(pw, mEntropy);
Shawn Willden55268b52015-07-28 11:06:00 -060077}
78
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070079ResponseCode KeyStore::readMasterKey(const android::String8& pw, uid_t userId) {
80 UserState* userState = getUserState(userId);
81 return userState->readMasterKey(pw, mEntropy);
Kenny Root49468902013-03-19 13:41:33 -070082}
83
Kenny Roota91203b2012-02-15 15:00:46 -080084/* Here is the encoding of keys. This is necessary in order to allow arbitrary
85 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
86 * into two bytes. The first byte is one of [+-.] which represents the first
87 * two bits of the character. The second byte encodes the rest of the bits into
88 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
89 * that Base64 cannot be used here due to the need of prefix match on keys. */
90
Kenny Root655b9582013-04-04 08:37:42 -070091static size_t encode_key_length(const android::String8& keyName) {
92 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
93 size_t length = keyName.length();
94 for (int i = length; i > 0; --i, ++in) {
95 if (*in < '0' || *in > '~') {
96 ++length;
97 }
98 }
99 return length;
100}
101
Kenny Root07438c82012-11-02 15:41:02 -0700102static int encode_key(char* out, const android::String8& keyName) {
103 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
104 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800105 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700106 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800107 *out = '+' + (*in >> 6);
108 *++out = '0' + (*in & 0x3F);
109 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700110 } else {
111 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800112 }
113 }
114 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800115 return length;
116}
117
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400118android::String8 KeyStore::getKeyName(const android::String8& keyName, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000119 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
120 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400121 if (type == TYPE_KEY_CHARACTERISTICS) {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400122 return android::String8::format(".chr_%s", encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400123 } else {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400124 return android::String8(encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400125 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700126}
127
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400128android::String8 KeyStore::getKeyNameForUid(
129 const android::String8& keyName, uid_t uid, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000130 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
131 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400132 if (type == TYPE_KEY_CHARACTERISTICS) {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400133 return android::String8::format(".%u_chr_%s", uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400134 } else {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400135 return android::String8::format("%u_%s", uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400136 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700137}
138
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400139android::String8 KeyStore::getKeyNameForUidWithDir(
140 const android::String8& keyName, uid_t uid, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000141 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
142 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400143
144 if (type == TYPE_KEY_CHARACTERISTICS) {
145 return android::String8::format("%s/.%u_chr_%s", getUserStateByUid(uid)->getUserDirName(),
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400146 uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400147 } else {
148 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400149 encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400150 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700151}
152
153void KeyStore::resetUser(uid_t userId, bool keepUnenryptedEntries) {
154 android::String8 prefix("");
155 android::Vector<android::String16> aliases;
156 UserState* userState = getUserState(userId);
157 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
158 return;
159 }
160 for (uint32_t i = 0; i < aliases.size(); i++) {
161 android::String8 filename(aliases[i]);
162 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400163 getKeyName(filename, TYPE_ANY).string());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700164 bool shouldDelete = true;
165 if (keepUnenryptedEntries) {
166 Blob blob;
167 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
168
169 /* get can fail if the blob is encrypted and the state is
170 * not unlocked, only skip deleting blobs that were loaded and
171 * who are not encrypted. If there are blobs we fail to read for
172 * other reasons err on the safe side and delete them since we
173 * can't tell if they're encrypted.
174 */
175 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
176 }
177 if (shouldDelete) {
178 del(filename, ::TYPE_ANY, userId);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400179
180 // del() will fail silently if no cached characteristics are present for this alias.
181 android::String8 chr_filename(aliases[i]);
182 chr_filename = android::String8::format("%s/%s", userState->getUserDirName(),
183 getKeyName(chr_filename,
184 TYPE_KEY_CHARACTERISTICS).string());
185 del(chr_filename, ::TYPE_KEY_CHARACTERISTICS, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700186 }
187 }
188 if (!userState->deleteMasterKey()) {
189 ALOGE("Failed to delete user %d's master key", userId);
190 }
191 if (!keepUnenryptedEntries) {
192 if (!userState->reset()) {
193 ALOGE("Failed to remove user %d's directory", userId);
194 }
195 }
196}
197
198bool KeyStore::isEmpty(uid_t userId) const {
199 const UserState* userState = getUserState(userId);
200 if (userState == NULL) {
201 return true;
202 }
203
204 DIR* dir = opendir(userState->getUserDirName());
205 if (!dir) {
206 return true;
207 }
208
209 bool result = true;
210 struct dirent* file;
211 while ((file = readdir(dir)) != NULL) {
212 // We only care about files.
213 if (file->d_type != DT_REG) {
214 continue;
215 }
216
217 // Skip anything that starts with a "."
218 if (file->d_name[0] == '.') {
219 continue;
220 }
221
222 result = false;
223 break;
224 }
225 closedir(dir);
226 return result;
227}
228
229void KeyStore::lock(uid_t userId) {
230 UserState* userState = getUserState(userId);
231 userState->zeroizeMasterKeysInMemory();
232 userState->setState(STATE_LOCKED);
233}
234
235ResponseCode KeyStore::get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
236 UserState* userState = getUserState(userId);
237 ResponseCode rc =
238 keyBlob->readBlob(filename, userState->getDecryptionKey(), userState->getState());
239 if (rc != NO_ERROR) {
240 return rc;
241 }
242
243 const uint8_t version = keyBlob->getVersion();
244 if (version < CURRENT_BLOB_VERSION) {
245 /* If we upgrade the key, we need to write it to disk again. Then
246 * it must be read it again since the blob is encrypted each time
247 * it's written.
248 */
249 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
250 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR ||
251 (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
252 userState->getState())) != NO_ERROR) {
253 return rc;
254 }
255 }
256 }
257
258 /*
259 * This will upgrade software-backed keys to hardware-backed keys when
260 * the HAL for the device supports the newer key types.
261 */
262 if (rc == NO_ERROR && type == TYPE_KEY_PAIR &&
263 mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2 &&
264 keyBlob->isFallback()) {
265 ResponseCode imported =
266 importKey(keyBlob->getValue(), keyBlob->getLength(), filename, userId,
267 keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
268
269 // The HAL allowed the import, reget the key to have the "fresh"
270 // version.
271 if (imported == NO_ERROR) {
272 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
273 }
274 }
275
276 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
277 if (keyBlob->getType() == TYPE_KEY_PAIR) {
278 keyBlob->setType(TYPE_KEYMASTER_10);
279 rc = this->put(filename, keyBlob, userId);
280 }
281
282 if (type != TYPE_ANY && keyBlob->getType() != type) {
283 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
284 return KEY_NOT_FOUND;
285 }
286
287 return rc;
288}
289
290ResponseCode KeyStore::put(const char* filename, Blob* keyBlob, uid_t userId) {
291 UserState* userState = getUserState(userId);
292 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
293 mEntropy);
294}
295
296ResponseCode KeyStore::del(const char* filename, const BlobType type, uid_t userId) {
297 Blob keyBlob;
298 ResponseCode rc = get(filename, &keyBlob, type, userId);
299 if (rc == ::VALUE_CORRUPTED) {
300 // The file is corrupt, the best we can do is rm it.
301 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
302 }
303 if (rc != ::NO_ERROR) {
304 return rc;
305 }
306
307 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
308 // A device doesn't have to implement delete_key.
309 if (mDevice->delete_key != NULL && !keyBlob.isFallback()) {
310 keymaster_key_blob_t blob = {keyBlob.getValue(),
311 static_cast<size_t>(keyBlob.getLength())};
312 if (mDevice->delete_key(mDevice, &blob)) {
313 rc = ::SYSTEM_ERROR;
314 }
315 }
316 }
317 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
Shawn Willden715d0232016-01-21 00:45:13 -0700318 auto* dev = getDeviceForBlob(keyBlob);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700319 if (dev->delete_key) {
320 keymaster_key_blob_t blob;
321 blob.key_material = keyBlob.getValue();
322 blob.key_material_size = keyBlob.getLength();
323 dev->delete_key(dev, &blob);
324 }
325 }
326 if (rc != ::NO_ERROR) {
327 return rc;
328 }
329
330 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
331}
332
Kenny Root07438c82012-11-02 15:41:02 -0700333/*
334 * Converts from the "escaped" format on disk to actual name.
335 * This will be smaller than the input string.
336 *
337 * Characters that should combine with the next at the end will be truncated.
338 */
339static size_t decode_key_length(const char* in, size_t length) {
340 size_t outLength = 0;
341
342 for (const char* end = in + length; in < end; in++) {
343 /* This combines with the next character. */
344 if (*in < '0' || *in > '~') {
345 continue;
346 }
347
348 outLength++;
349 }
350 return outLength;
351}
352
353static void decode_key(char* out, const char* in, size_t length) {
354 for (const char* end = in + length; in < end; in++) {
355 if (*in < '0' || *in > '~') {
356 /* Truncate combining characters at the end. */
357 if (in + 1 >= end) {
358 break;
359 }
360
361 *out = (*in++ - '+') << 6;
362 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800363 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700364 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800365 }
366 }
367 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800368}
369
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700370ResponseCode KeyStore::list(const android::String8& prefix,
371 android::Vector<android::String16>* matches, uid_t userId) {
Kenny Roota91203b2012-02-15 15:00:46 -0800372
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700373 UserState* userState = getUserState(userId);
374 size_t n = prefix.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800375
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700376 DIR* dir = opendir(userState->getUserDirName());
377 if (!dir) {
378 ALOGW("can't open directory for user: %s", strerror(errno));
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700379 return ::SYSTEM_ERROR;
380 }
381
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700382 struct dirent* file;
383 while ((file = readdir(dir)) != NULL) {
384 // We only care about files.
385 if (file->d_type != DT_REG) {
386 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700387 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700388
389 // Skip anything that starts with a "."
390 if (file->d_name[0] == '.') {
391 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700392 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700393
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700394 if (!strncmp(prefix.string(), file->d_name, n)) {
395 const char* p = &file->d_name[n];
396 size_t plen = strlen(p);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700397
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700398 size_t extra = decode_key_length(p, plen);
399 char* match = (char*)malloc(extra + 1);
400 if (match != NULL) {
401 decode_key(match, p, plen);
402 matches->push(android::String16(match, extra));
403 free(match);
Chad Brubakerdf705172015-06-17 20:17:51 -0700404 } else {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700405 ALOGW("could not allocate match of size %zd", extra);
Chad Brubakerdf705172015-06-17 20:17:51 -0700406 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700407 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700408 }
409 closedir(dir);
410 return ::NO_ERROR;
411}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700412
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700413void KeyStore::addGrant(const char* filename, uid_t granteeUid) {
414 const grant_t* existing = getGrant(filename, granteeUid);
415 if (existing == NULL) {
416 grant_t* grant = new grant_t;
417 grant->uid = granteeUid;
418 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
419 mGrants.add(grant);
420 }
421}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700422
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700423bool KeyStore::removeGrant(const char* filename, uid_t granteeUid) {
424 for (android::Vector<grant_t*>::iterator it(mGrants.begin()); it != mGrants.end(); it++) {
425 grant_t* grant = *it;
426 if (grant->uid == granteeUid &&
427 !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
428 mGrants.erase(it);
429 return true;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700430 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700431 }
432 return false;
433}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700434
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700435ResponseCode KeyStore::importKey(const uint8_t* key, size_t keyLen, const char* filename,
436 uid_t userId, int32_t flags) {
437 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
438 if (!pkcs8.get()) {
439 return ::SYSTEM_ERROR;
440 }
441 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
442 if (!pkey.get()) {
443 return ::SYSTEM_ERROR;
444 }
445 int type = EVP_PKEY_type(pkey->type);
446 android::KeymasterArguments params;
447 add_legacy_key_authorizations(type, &params.params);
448 switch (type) {
449 case EVP_PKEY_RSA:
450 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
451 break;
452 case EVP_PKEY_EC:
453 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
454 break;
455 default:
456 ALOGW("Unsupported key type %d", type);
457 return ::SYSTEM_ERROR;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700458 }
459
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700460 std::vector<keymaster_key_param_t> opParams(params.params);
461 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
462 keymaster_blob_t input = {key, keyLen};
463 keymaster_key_blob_t blob = {nullptr, 0};
464 bool isFallback = false;
465 keymaster_error_t error = mDevice->import_key(mDevice, &inParams, KM_KEY_FORMAT_PKCS8, &input,
466 &blob, NULL /* characteristics */);
467 if (error != KM_ERROR_OK) {
468 ALOGE("Keymaster error %d importing key pair, falling back", error);
Kenny Root07438c82012-11-02 15:41:02 -0700469
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700470 /*
471 * There should be no way to get here. Fallback shouldn't ever really happen
472 * because the main device may be many (SW, KM0/SW hybrid, KM1/SW hybrid), but it must
473 * provide full support of the API. In any case, we'll do the fallback just for
474 * consistency... and I suppose to cover for broken HW implementations.
475 */
476 error = mFallbackDevice->import_key(mFallbackDevice, &inParams, KM_KEY_FORMAT_PKCS8, &input,
477 &blob, NULL /* characteristics */);
478 isFallback = true;
Kenny Roota91203b2012-02-15 15:00:46 -0800479
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700480 if (error) {
481 ALOGE("Keymaster error while importing key pair with fallback: %d", error);
482 return SYSTEM_ERROR;
Riley Spahneaabae92014-06-30 12:39:52 -0700483 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700484 }
485
486 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, TYPE_KEYMASTER_10);
487 free(const_cast<uint8_t*>(blob.key_material));
488
489 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
490 keyBlob.setFallback(isFallback);
491
492 return put(filename, &keyBlob, userId);
493}
494
495bool KeyStore::isHardwareBacked(const android::String16& keyType) const {
496 if (mDevice == NULL) {
497 ALOGW("can't get keymaster device");
498 return false;
499 }
500
501 if (sRSAKeyType == keyType) {
502 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
Riley Spahneaabae92014-06-30 12:39:52 -0700503 } else {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700504 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0 &&
505 (mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2);
506 }
507}
508
509ResponseCode KeyStore::getKeyForName(Blob* keyBlob, const android::String8& keyName,
510 const uid_t uid, const BlobType type) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400511 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid, type));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700512 uid_t userId = get_user_id(uid);
513
514 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
515 if (responseCode == NO_ERROR) {
516 return responseCode;
Riley Spahneaabae92014-06-30 12:39:52 -0700517 }
518
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700519 // If this is one of the legacy UID->UID mappings, use it.
520 uid_t euid = get_keystore_euid(uid);
521 if (euid != uid) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400522 filepath8 = getKeyNameForUidWithDir(keyName, euid, type);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700523 responseCode = get(filepath8.string(), keyBlob, type, userId);
524 if (responseCode == NO_ERROR) {
525 return responseCode;
526 }
527 }
528
529 // They might be using a granted key.
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400530 android::String8 filename8 = getKeyName(keyName, type);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700531 char* end;
532 strtoul(filename8.string(), &end, 10);
533 if (end[0] != '_' || end[1] == 0) {
534 return KEY_NOT_FOUND;
535 }
536 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
537 filename8.string());
538 if (!hasGrant(filepath8.string(), uid)) {
539 return responseCode;
540 }
541
542 // It is a granted key. Try to load it.
543 return get(filepath8.string(), keyBlob, type, userId);
544}
545
546UserState* KeyStore::getUserState(uid_t userId) {
547 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
548 it++) {
549 UserState* state = *it;
550 if (state->getUserId() == userId) {
551 return state;
552 }
553 }
554
555 UserState* userState = new UserState(userId);
556 if (!userState->initialize()) {
557 /* There's not much we can do if initialization fails. Trying to
558 * unlock the keystore for that user will fail as well, so any
559 * subsequent request for this user will just return SYSTEM_ERROR.
560 */
561 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
562 }
563 mMasterKeys.add(userState);
564 return userState;
565}
566
567UserState* KeyStore::getUserStateByUid(uid_t uid) {
568 uid_t userId = get_user_id(uid);
569 return getUserState(userId);
570}
571
572const UserState* KeyStore::getUserState(uid_t userId) const {
573 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
574 it != mMasterKeys.end(); it++) {
575 UserState* state = *it;
576 if (state->getUserId() == userId) {
577 return state;
578 }
579 }
580
581 return NULL;
582}
583
584const UserState* KeyStore::getUserStateByUid(uid_t uid) const {
585 uid_t userId = get_user_id(uid);
586 return getUserState(userId);
587}
588
589const grant_t* KeyStore::getGrant(const char* filename, uid_t uid) const {
590 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin()); it != mGrants.end(); it++) {
591 grant_t* grant = *it;
592 if (grant->uid == uid &&
593 !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
594 return grant;
595 }
596 }
597 return NULL;
598}
599
600bool KeyStore::upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
601 const BlobType type, uid_t uid) {
602 bool updated = false;
603 uint8_t version = oldVersion;
604
605 /* From V0 -> V1: All old types were unknown */
606 if (version == 0) {
607 ALOGV("upgrading to version 1 and setting type %d", type);
608
609 blob->setType(type);
610 if (type == TYPE_KEY_PAIR) {
611 importBlobAsKey(blob, filename, uid);
612 }
613 version = 1;
614 updated = true;
615 }
616
617 /* From V1 -> V2: All old keys were encrypted */
618 if (version == 1) {
619 ALOGV("upgrading to version 2");
620
621 blob->setEncrypted(true);
622 version = 2;
623 updated = true;
Kenny Roota91203b2012-02-15 15:00:46 -0800624 }
Kenny Root07438c82012-11-02 15:41:02 -0700625
626 /*
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700627 * If we've updated, set the key blob to the right version
628 * and write it.
Kenny Root07438c82012-11-02 15:41:02 -0700629 */
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700630 if (updated) {
631 ALOGV("updated and writing file %s", filename);
632 blob->setVersion(version);
633 }
Kenny Root70e3a862012-02-15 17:20:23 -0800634
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700635 return updated;
636}
637
638struct BIO_Delete {
639 void operator()(BIO* p) const { BIO_free(p); }
640};
641typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
642
643ResponseCode KeyStore::importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
644 // We won't even write to the blob directly with this BIO, so const_cast is okay.
645 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
646 if (b.get() == NULL) {
647 ALOGE("Problem instantiating BIO");
648 return SYSTEM_ERROR;
649 }
650
651 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
652 if (pkey.get() == NULL) {
653 ALOGE("Couldn't read old PEM file");
654 return SYSTEM_ERROR;
655 }
656
657 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
658 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
659 if (len < 0) {
660 ALOGE("Couldn't measure PKCS#8 length");
661 return SYSTEM_ERROR;
662 }
663
664 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
665 uint8_t* tmp = pkcs8key.get();
666 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
667 ALOGE("Couldn't convert to PKCS#8");
668 return SYSTEM_ERROR;
669 }
670
671 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
672 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
673 if (rc != NO_ERROR) {
674 return rc;
675 }
676
677 return get(filename, blob, TYPE_KEY_PAIR, uid);
678}
679
680void KeyStore::readMetaData() {
681 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
682 if (in < 0) {
683 return;
684 }
685 size_t fileLength = readFully(in, (uint8_t*)&mMetaData, sizeof(mMetaData));
686 if (fileLength != sizeof(mMetaData)) {
687 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength, sizeof(mMetaData));
688 }
689 close(in);
690}
691
692void KeyStore::writeMetaData() {
693 const char* tmpFileName = ".metadata.tmp";
694 int out =
695 TEMP_FAILURE_RETRY(open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
696 if (out < 0) {
697 ALOGE("couldn't write metadata file: %s", strerror(errno));
698 return;
699 }
700 size_t fileLength = writeFully(out, (uint8_t*)&mMetaData, sizeof(mMetaData));
701 if (fileLength != sizeof(mMetaData)) {
702 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
703 sizeof(mMetaData));
704 }
705 close(out);
706 rename(tmpFileName, sMetaDataFile);
707}
708
709bool KeyStore::upgradeKeystore() {
710 bool upgraded = false;
711
712 if (mMetaData.version == 0) {
713 UserState* userState = getUserStateByUid(0);
714
715 // Initialize first so the directory is made.
716 userState->initialize();
717
718 // Migrate the old .masterkey file to user 0.
719 if (access(sOldMasterKey, R_OK) == 0) {
720 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
721 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
722 return false;
723 }
724 }
725
726 // Initialize again in case we had a key.
727 userState->initialize();
728
729 // Try to migrate existing keys.
730 DIR* dir = opendir(".");
731 if (!dir) {
732 // Give up now; maybe we can upgrade later.
733 ALOGE("couldn't open keystore's directory; something is wrong");
734 return false;
735 }
736
737 struct dirent* file;
738 while ((file = readdir(dir)) != NULL) {
739 // We only care about files.
740 if (file->d_type != DT_REG) {
741 continue;
742 }
743
744 // Skip anything that starts with a "."
745 if (file->d_name[0] == '.') {
746 continue;
747 }
748
749 // Find the current file's user.
750 char* end;
751 unsigned long thisUid = strtoul(file->d_name, &end, 10);
752 if (end[0] != '_' || end[1] == 0) {
753 continue;
754 }
755 UserState* otherUser = getUserStateByUid(thisUid);
756 if (otherUser->getUserId() != 0) {
757 unlinkat(dirfd(dir), file->d_name, 0);
758 }
759
760 // Rename the file into user directory.
761 DIR* otherdir = opendir(otherUser->getUserDirName());
762 if (otherdir == NULL) {
763 ALOGW("couldn't open user directory for rename");
764 continue;
765 }
766 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
767 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
768 }
769 closedir(otherdir);
770 }
771 closedir(dir);
772
773 mMetaData.version = 1;
774 upgraded = true;
775 }
776
777 return upgraded;
Kenny Roota91203b2012-02-15 15:00:46 -0800778}