blob: 3fc9efced59f5aefe80b21286410f55d8281c84d [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
43KeyStore::KeyStore(Entropy* entropy, const km_device_t& device, const km_device_t& fallback)
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070044 : mEntropy(entropy), mDevice(device), mFallbackDevice(fallback) {
45 memset(&mMetaData, '\0', sizeof(mMetaData));
Kenny Root70e3a862012-02-15 17:20:23 -080046}
47
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070048KeyStore::~KeyStore() {
49 for (android::Vector<grant_t*>::iterator it(mGrants.begin()); it != mGrants.end(); it++) {
50 delete *it;
Shawn Willden55268b52015-07-28 11:06:00 -060051 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070052 mGrants.clear();
Shawn Willden55268b52015-07-28 11:06:00 -060053
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070054 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
55 it++) {
56 delete *it;
Shawn Willden55268b52015-07-28 11:06:00 -060057 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070058 mMasterKeys.clear();
Shawn Willden55268b52015-07-28 11:06:00 -060059}
60
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070061ResponseCode KeyStore::initialize() {
62 readMetaData();
63 if (upgradeKeystore()) {
64 writeMetaData();
Shawn Willden55268b52015-07-28 11:06:00 -060065 }
66
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010067 return ResponseCode::NO_ERROR;
Shawn Willden55268b52015-07-28 11:06:00 -060068}
69
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070070ResponseCode KeyStore::initializeUser(const android::String8& pw, uid_t userId) {
71 UserState* userState = getUserState(userId);
72 return userState->initialize(pw, mEntropy);
Chad Brubakerfc18edc2015-01-12 15:17:18 -080073}
74
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070075ResponseCode KeyStore::copyMasterKey(uid_t srcUser, uid_t dstUser) {
76 UserState* userState = getUserState(dstUser);
77 UserState* initState = getUserState(srcUser);
78 return userState->copyMasterKey(initState);
Kenny Root70e3a862012-02-15 17:20:23 -080079}
80
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070081ResponseCode KeyStore::writeMasterKey(const android::String8& pw, uid_t userId) {
82 UserState* userState = getUserState(userId);
83 return userState->writeMasterKey(pw, mEntropy);
Shawn Willden55268b52015-07-28 11:06:00 -060084}
85
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070086ResponseCode KeyStore::readMasterKey(const android::String8& pw, uid_t userId) {
87 UserState* userState = getUserState(userId);
88 return userState->readMasterKey(pw, mEntropy);
Kenny Root49468902013-03-19 13:41:33 -070089}
90
Kenny Roota91203b2012-02-15 15:00:46 -080091/* Here is the encoding of keys. This is necessary in order to allow arbitrary
92 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
93 * into two bytes. The first byte is one of [+-.] which represents the first
94 * two bits of the character. The second byte encodes the rest of the bits into
95 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
96 * that Base64 cannot be used here due to the need of prefix match on keys. */
97
Kenny Root655b9582013-04-04 08:37:42 -070098static size_t encode_key_length(const android::String8& keyName) {
99 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
100 size_t length = keyName.length();
101 for (int i = length; i > 0; --i, ++in) {
102 if (*in < '0' || *in > '~') {
103 ++length;
104 }
105 }
106 return length;
107}
108
Kenny Root07438c82012-11-02 15:41:02 -0700109static int encode_key(char* out, const android::String8& keyName) {
110 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
111 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800112 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700113 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800114 *out = '+' + (*in >> 6);
115 *++out = '0' + (*in & 0x3F);
116 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700117 } else {
118 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800119 }
120 }
121 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800122 return length;
123}
124
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400125android::String8 KeyStore::getKeyName(const android::String8& keyName, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000126 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
127 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400128 if (type == TYPE_KEY_CHARACTERISTICS) {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400129 return android::String8::format(".chr_%s", encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400130 } else {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400131 return android::String8(encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400132 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700133}
134
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400135android::String8 KeyStore::getKeyNameForUid(
136 const android::String8& keyName, uid_t uid, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000137 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
138 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400139 if (type == TYPE_KEY_CHARACTERISTICS) {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400140 return android::String8::format(".%u_chr_%s", uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400141 } else {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400142 return android::String8::format("%u_%s", uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400143 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700144}
145
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400146android::String8 KeyStore::getKeyNameForUidWithDir(
147 const android::String8& keyName, uid_t uid, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000148 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
149 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400150
151 if (type == TYPE_KEY_CHARACTERISTICS) {
152 return android::String8::format("%s/.%u_chr_%s", getUserStateByUid(uid)->getUserDirName(),
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400153 uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400154 } else {
155 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400156 encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400157 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700158}
159
160void KeyStore::resetUser(uid_t userId, bool keepUnenryptedEntries) {
161 android::String8 prefix("");
162 android::Vector<android::String16> aliases;
163 UserState* userState = getUserState(userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100164 if (list(prefix, &aliases, userId) != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700165 return;
166 }
167 for (uint32_t i = 0; i < aliases.size(); i++) {
168 android::String8 filename(aliases[i]);
169 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400170 getKeyName(filename, TYPE_ANY).string());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700171 bool shouldDelete = true;
172 if (keepUnenryptedEntries) {
173 Blob blob;
174 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
175
176 /* get can fail if the blob is encrypted and the state is
177 * not unlocked, only skip deleting blobs that were loaded and
178 * who are not encrypted. If there are blobs we fail to read for
179 * other reasons err on the safe side and delete them since we
180 * can't tell if they're encrypted.
181 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100182 shouldDelete = !(rc == ResponseCode::NO_ERROR && !blob.isEncrypted());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700183 }
184 if (shouldDelete) {
185 del(filename, ::TYPE_ANY, userId);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400186
187 // del() will fail silently if no cached characteristics are present for this alias.
188 android::String8 chr_filename(aliases[i]);
189 chr_filename = android::String8::format("%s/%s", userState->getUserDirName(),
190 getKeyName(chr_filename,
191 TYPE_KEY_CHARACTERISTICS).string());
192 del(chr_filename, ::TYPE_KEY_CHARACTERISTICS, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700193 }
194 }
195 if (!userState->deleteMasterKey()) {
196 ALOGE("Failed to delete user %d's master key", userId);
197 }
198 if (!keepUnenryptedEntries) {
199 if (!userState->reset()) {
200 ALOGE("Failed to remove user %d's directory", userId);
201 }
202 }
203}
204
205bool KeyStore::isEmpty(uid_t userId) const {
206 const UserState* userState = getUserState(userId);
207 if (userState == NULL) {
208 return true;
209 }
210
211 DIR* dir = opendir(userState->getUserDirName());
212 if (!dir) {
213 return true;
214 }
215
216 bool result = true;
217 struct dirent* file;
218 while ((file = readdir(dir)) != NULL) {
219 // We only care about files.
220 if (file->d_type != DT_REG) {
221 continue;
222 }
223
224 // Skip anything that starts with a "."
225 if (file->d_name[0] == '.') {
226 continue;
227 }
228
229 result = false;
230 break;
231 }
232 closedir(dir);
233 return result;
234}
235
236void KeyStore::lock(uid_t userId) {
237 UserState* userState = getUserState(userId);
238 userState->zeroizeMasterKeysInMemory();
239 userState->setState(STATE_LOCKED);
240}
241
242ResponseCode KeyStore::get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
243 UserState* userState = getUserState(userId);
244 ResponseCode rc =
245 keyBlob->readBlob(filename, userState->getDecryptionKey(), userState->getState());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100246 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700247 return rc;
248 }
249
250 const uint8_t version = keyBlob->getVersion();
251 if (version < CURRENT_BLOB_VERSION) {
252 /* If we upgrade the key, we need to write it to disk again. Then
253 * it must be read it again since the blob is encrypted each time
254 * it's written.
255 */
256 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100257 if ((rc = this->put(filename, keyBlob, userId)) != ResponseCode::NO_ERROR ||
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700258 (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100259 userState->getState())) != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700260 return rc;
261 }
262 }
263 }
264
265 /*
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100266 * This will upgrade software-backed keys to hardware-backed keys.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700267 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100268 if (rc == ResponseCode::NO_ERROR && type == TYPE_KEY_PAIR && keyBlob->isFallback()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700269 ResponseCode imported =
270 importKey(keyBlob->getValue(), keyBlob->getLength(), filename, userId,
271 keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
272
273 // The HAL allowed the import, reget the key to have the "fresh"
274 // version.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100275 if (imported == ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700276 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
277 }
278 }
279
280 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
281 if (keyBlob->getType() == TYPE_KEY_PAIR) {
282 keyBlob->setType(TYPE_KEYMASTER_10);
283 rc = this->put(filename, keyBlob, userId);
284 }
285
286 if (type != TYPE_ANY && keyBlob->getType() != type) {
287 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100288 return ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700289 }
290
291 return rc;
292}
293
294ResponseCode KeyStore::put(const char* filename, Blob* keyBlob, uid_t userId) {
295 UserState* userState = getUserState(userId);
296 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
297 mEntropy);
298}
299
300ResponseCode KeyStore::del(const char* filename, const BlobType type, uid_t userId) {
301 Blob keyBlob;
302 ResponseCode rc = get(filename, &keyBlob, type, userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100303 if (rc == ResponseCode::VALUE_CORRUPTED) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700304 // The file is corrupt, the best we can do is rm it.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100305 return (unlink(filename) && errno != ENOENT) ?
306 ResponseCode::SYSTEM_ERROR : ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700307 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100308 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700309 return rc;
310 }
311
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100312 if (keyBlob.getType() == ::TYPE_KEY_PAIR || keyBlob.getType() == ::TYPE_KEYMASTER_10) {
313 auto ret = KS_HANDLE_HIDL_ERROR(mDevice->deleteKey(blob2hidlVec(keyBlob)));
314
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700315 // A device doesn't have to implement delete_key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100316 if (ret != ErrorCode::OK && ret != ErrorCode::UNIMPLEMENTED)
317 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700318 }
319
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100320 return (unlink(filename) && errno != ENOENT) ?
321 ResponseCode::SYSTEM_ERROR : ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700322}
323
Kenny Root07438c82012-11-02 15:41:02 -0700324/*
325 * Converts from the "escaped" format on disk to actual name.
326 * This will be smaller than the input string.
327 *
328 * Characters that should combine with the next at the end will be truncated.
329 */
330static size_t decode_key_length(const char* in, size_t length) {
331 size_t outLength = 0;
332
333 for (const char* end = in + length; in < end; in++) {
334 /* This combines with the next character. */
335 if (*in < '0' || *in > '~') {
336 continue;
337 }
338
339 outLength++;
340 }
341 return outLength;
342}
343
344static void decode_key(char* out, const char* in, size_t length) {
345 for (const char* end = in + length; in < end; in++) {
346 if (*in < '0' || *in > '~') {
347 /* Truncate combining characters at the end. */
348 if (in + 1 >= end) {
349 break;
350 }
351
352 *out = (*in++ - '+') << 6;
353 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800354 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700355 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800356 }
357 }
358 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800359}
360
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700361ResponseCode KeyStore::list(const android::String8& prefix,
362 android::Vector<android::String16>* matches, uid_t userId) {
Kenny Roota91203b2012-02-15 15:00:46 -0800363
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700364 UserState* userState = getUserState(userId);
365 size_t n = prefix.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800366
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700367 DIR* dir = opendir(userState->getUserDirName());
368 if (!dir) {
369 ALOGW("can't open directory for user: %s", strerror(errno));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100370 return ResponseCode::SYSTEM_ERROR;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700371 }
372
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700373 struct dirent* file;
374 while ((file = readdir(dir)) != NULL) {
375 // We only care about files.
376 if (file->d_type != DT_REG) {
377 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700378 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700379
380 // Skip anything that starts with a "."
381 if (file->d_name[0] == '.') {
382 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700383 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700384
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700385 if (!strncmp(prefix.string(), file->d_name, n)) {
386 const char* p = &file->d_name[n];
387 size_t plen = strlen(p);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700388
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700389 size_t extra = decode_key_length(p, plen);
390 char* match = (char*)malloc(extra + 1);
391 if (match != NULL) {
392 decode_key(match, p, plen);
393 matches->push(android::String16(match, extra));
394 free(match);
Chad Brubakerdf705172015-06-17 20:17:51 -0700395 } else {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700396 ALOGW("could not allocate match of size %zd", extra);
Chad Brubakerdf705172015-06-17 20:17:51 -0700397 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700398 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700399 }
400 closedir(dir);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100401 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700402}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700403
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700404void KeyStore::addGrant(const char* filename, uid_t granteeUid) {
405 const grant_t* existing = getGrant(filename, granteeUid);
406 if (existing == NULL) {
407 grant_t* grant = new grant_t;
408 grant->uid = granteeUid;
409 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
410 mGrants.add(grant);
411 }
412}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700413
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700414bool KeyStore::removeGrant(const char* filename, uid_t granteeUid) {
415 for (android::Vector<grant_t*>::iterator it(mGrants.begin()); it != mGrants.end(); it++) {
416 grant_t* grant = *it;
417 if (grant->uid == granteeUid &&
418 !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
419 mGrants.erase(it);
420 return true;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700421 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700422 }
423 return false;
424}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700425
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700426ResponseCode KeyStore::importKey(const uint8_t* key, size_t keyLen, const char* filename,
427 uid_t userId, int32_t flags) {
428 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
429 if (!pkcs8.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100430 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700431 }
432 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
433 if (!pkey.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100434 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700435 }
436 int type = EVP_PKEY_type(pkey->type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100437 AuthorizationSet params;
438 add_legacy_key_authorizations(type, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700439 switch (type) {
440 case EVP_PKEY_RSA:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100441 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700442 break;
443 case EVP_PKEY_EC:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100444 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700445 break;
446 default:
447 ALOGW("Unsupported key type %d", type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100448 return ResponseCode::SYSTEM_ERROR;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700449 }
450
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100451 AuthorizationSet opParams(params);
452 hidl_vec<uint8_t> blob;
Kenny Root07438c82012-11-02 15:41:02 -0700453
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100454 ErrorCode error;
455 auto hidlCb = [&] (ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
456 const KeyCharacteristics& /* ignored */) {
457 error = ret;
458 if (error != ErrorCode::OK) return;
459 blob = keyBlob;
460 };
461 auto input = blob2hidlVec(key, keyLen);
Kenny Roota91203b2012-02-15 15:00:46 -0800462
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100463 ErrorCode rc = KS_HANDLE_HIDL_ERROR(
464 mDevice->importKey(params.hidl_data(), KeyFormat::PKCS8, input, hidlCb));
465 if (rc != ErrorCode::OK) return ResponseCode::SYSTEM_ERROR;
466 if (error != ErrorCode::OK) {
467 ALOGE("Keymaster error %d importing key pair", error);
468 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700469 }
470
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100471 Blob keyBlob(&blob[0], blob.size(), NULL, 0, TYPE_KEYMASTER_10);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700472
473 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100474 keyBlob.setFallback(false);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700475
476 return put(filename, &keyBlob, userId);
477}
478
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100479bool KeyStore::isHardwareBacked(const android::String16& /*keyType*/) const {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700480 if (mDevice == NULL) {
481 ALOGW("can't get keymaster device");
482 return false;
483 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100484// TODO: This information seems not to be available here
485// if (sRSAKeyType == keyType) {
486// return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
487// } else {
488// return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0 &&
489// (mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2);
490// }
491 return true;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700492}
493
494ResponseCode KeyStore::getKeyForName(Blob* keyBlob, const android::String8& keyName,
495 const uid_t uid, const BlobType type) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400496 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid, type));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700497 uid_t userId = get_user_id(uid);
498
499 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100500 if (responseCode == ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700501 return responseCode;
Riley Spahneaabae92014-06-30 12:39:52 -0700502 }
503
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700504 // If this is one of the legacy UID->UID mappings, use it.
505 uid_t euid = get_keystore_euid(uid);
506 if (euid != uid) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400507 filepath8 = getKeyNameForUidWithDir(keyName, euid, type);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700508 responseCode = get(filepath8.string(), keyBlob, type, userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100509 if (responseCode == ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700510 return responseCode;
511 }
512 }
513
514 // They might be using a granted key.
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400515 android::String8 filename8 = getKeyName(keyName, type);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700516 char* end;
517 strtoul(filename8.string(), &end, 10);
518 if (end[0] != '_' || end[1] == 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100519 return ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700520 }
521 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
522 filename8.string());
523 if (!hasGrant(filepath8.string(), uid)) {
524 return responseCode;
525 }
526
527 // It is a granted key. Try to load it.
528 return get(filepath8.string(), keyBlob, type, userId);
529}
530
531UserState* KeyStore::getUserState(uid_t userId) {
532 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
533 it++) {
534 UserState* state = *it;
535 if (state->getUserId() == userId) {
536 return state;
537 }
538 }
539
540 UserState* userState = new UserState(userId);
541 if (!userState->initialize()) {
542 /* There's not much we can do if initialization fails. Trying to
543 * unlock the keystore for that user will fail as well, so any
544 * subsequent request for this user will just return SYSTEM_ERROR.
545 */
546 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
547 }
548 mMasterKeys.add(userState);
549 return userState;
550}
551
552UserState* KeyStore::getUserStateByUid(uid_t uid) {
553 uid_t userId = get_user_id(uid);
554 return getUserState(userId);
555}
556
557const UserState* KeyStore::getUserState(uid_t userId) const {
558 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
559 it != mMasterKeys.end(); it++) {
560 UserState* state = *it;
561 if (state->getUserId() == userId) {
562 return state;
563 }
564 }
565
566 return NULL;
567}
568
569const UserState* KeyStore::getUserStateByUid(uid_t uid) const {
570 uid_t userId = get_user_id(uid);
571 return getUserState(userId);
572}
573
574const grant_t* KeyStore::getGrant(const char* filename, uid_t uid) const {
575 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin()); it != mGrants.end(); it++) {
576 grant_t* grant = *it;
577 if (grant->uid == uid &&
578 !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
579 return grant;
580 }
581 }
582 return NULL;
583}
584
585bool KeyStore::upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
586 const BlobType type, uid_t uid) {
587 bool updated = false;
588 uint8_t version = oldVersion;
589
590 /* From V0 -> V1: All old types were unknown */
591 if (version == 0) {
592 ALOGV("upgrading to version 1 and setting type %d", type);
593
594 blob->setType(type);
595 if (type == TYPE_KEY_PAIR) {
596 importBlobAsKey(blob, filename, uid);
597 }
598 version = 1;
599 updated = true;
600 }
601
602 /* From V1 -> V2: All old keys were encrypted */
603 if (version == 1) {
604 ALOGV("upgrading to version 2");
605
606 blob->setEncrypted(true);
607 version = 2;
608 updated = true;
Kenny Roota91203b2012-02-15 15:00:46 -0800609 }
Kenny Root07438c82012-11-02 15:41:02 -0700610
611 /*
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700612 * If we've updated, set the key blob to the right version
613 * and write it.
Kenny Root07438c82012-11-02 15:41:02 -0700614 */
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700615 if (updated) {
616 ALOGV("updated and writing file %s", filename);
617 blob->setVersion(version);
618 }
Kenny Root70e3a862012-02-15 17:20:23 -0800619
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700620 return updated;
621}
622
623struct BIO_Delete {
624 void operator()(BIO* p) const { BIO_free(p); }
625};
626typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
627
628ResponseCode KeyStore::importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
629 // We won't even write to the blob directly with this BIO, so const_cast is okay.
630 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
631 if (b.get() == NULL) {
632 ALOGE("Problem instantiating BIO");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100633 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700634 }
635
636 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
637 if (pkey.get() == NULL) {
638 ALOGE("Couldn't read old PEM file");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100639 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700640 }
641
642 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
643 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
644 if (len < 0) {
645 ALOGE("Couldn't measure PKCS#8 length");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100646 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700647 }
648
649 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
650 uint8_t* tmp = pkcs8key.get();
651 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
652 ALOGE("Couldn't convert to PKCS#8");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100653 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700654 }
655
656 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
657 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100658 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700659 return rc;
660 }
661
662 return get(filename, blob, TYPE_KEY_PAIR, uid);
663}
664
665void KeyStore::readMetaData() {
666 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
667 if (in < 0) {
668 return;
669 }
670 size_t fileLength = readFully(in, (uint8_t*)&mMetaData, sizeof(mMetaData));
671 if (fileLength != sizeof(mMetaData)) {
672 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength, sizeof(mMetaData));
673 }
674 close(in);
675}
676
677void KeyStore::writeMetaData() {
678 const char* tmpFileName = ".metadata.tmp";
679 int out =
680 TEMP_FAILURE_RETRY(open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
681 if (out < 0) {
682 ALOGE("couldn't write metadata file: %s", strerror(errno));
683 return;
684 }
685 size_t fileLength = writeFully(out, (uint8_t*)&mMetaData, sizeof(mMetaData));
686 if (fileLength != sizeof(mMetaData)) {
687 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
688 sizeof(mMetaData));
689 }
690 close(out);
691 rename(tmpFileName, sMetaDataFile);
692}
693
694bool KeyStore::upgradeKeystore() {
695 bool upgraded = false;
696
697 if (mMetaData.version == 0) {
698 UserState* userState = getUserStateByUid(0);
699
700 // Initialize first so the directory is made.
701 userState->initialize();
702
703 // Migrate the old .masterkey file to user 0.
704 if (access(sOldMasterKey, R_OK) == 0) {
705 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
706 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
707 return false;
708 }
709 }
710
711 // Initialize again in case we had a key.
712 userState->initialize();
713
714 // Try to migrate existing keys.
715 DIR* dir = opendir(".");
716 if (!dir) {
717 // Give up now; maybe we can upgrade later.
718 ALOGE("couldn't open keystore's directory; something is wrong");
719 return false;
720 }
721
722 struct dirent* file;
723 while ((file = readdir(dir)) != NULL) {
724 // We only care about files.
725 if (file->d_type != DT_REG) {
726 continue;
727 }
728
729 // Skip anything that starts with a "."
730 if (file->d_name[0] == '.') {
731 continue;
732 }
733
734 // Find the current file's user.
735 char* end;
736 unsigned long thisUid = strtoul(file->d_name, &end, 10);
737 if (end[0] != '_' || end[1] == 0) {
738 continue;
739 }
740 UserState* otherUser = getUserStateByUid(thisUid);
741 if (otherUser->getUserId() != 0) {
742 unlinkat(dirfd(dir), file->d_name, 0);
743 }
744
745 // Rename the file into user directory.
746 DIR* otherdir = opendir(otherUser->getUserDirName());
747 if (otherdir == NULL) {
748 ALOGW("couldn't open user directory for rename");
749 continue;
750 }
751 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
752 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
753 }
754 closedir(otherdir);
755 }
756 closedir(dir);
757
758 mMetaData.version = 1;
759 upgraded = true;
760 }
761
762 return upgraded;
Kenny Roota91203b2012-02-15 15:00:46 -0800763}