blob: 2d9de5d6b6033d9c2dae52234058fe3ac94c1a5b [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 Danisevskis69c434a2017-01-30 10:27:10 +0000312 auto& dev = getDevice(keyBlob);
313
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100314 if (keyBlob.getType() == ::TYPE_KEY_PAIR || keyBlob.getType() == ::TYPE_KEYMASTER_10) {
Janis Danisevskis69c434a2017-01-30 10:27:10 +0000315 auto ret = KS_HANDLE_HIDL_ERROR(dev->deleteKey(blob2hidlVec(keyBlob)));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100316
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700317 // A device doesn't have to implement delete_key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100318 if (ret != ErrorCode::OK && ret != ErrorCode::UNIMPLEMENTED)
319 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700320 }
321
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100322 return (unlink(filename) && errno != ENOENT) ?
323 ResponseCode::SYSTEM_ERROR : ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700324}
325
Kenny Root07438c82012-11-02 15:41:02 -0700326/*
327 * Converts from the "escaped" format on disk to actual name.
328 * This will be smaller than the input string.
329 *
330 * Characters that should combine with the next at the end will be truncated.
331 */
332static size_t decode_key_length(const char* in, size_t length) {
333 size_t outLength = 0;
334
335 for (const char* end = in + length; in < end; in++) {
336 /* This combines with the next character. */
337 if (*in < '0' || *in > '~') {
338 continue;
339 }
340
341 outLength++;
342 }
343 return outLength;
344}
345
346static void decode_key(char* out, const char* in, size_t length) {
347 for (const char* end = in + length; in < end; in++) {
348 if (*in < '0' || *in > '~') {
349 /* Truncate combining characters at the end. */
350 if (in + 1 >= end) {
351 break;
352 }
353
354 *out = (*in++ - '+') << 6;
355 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800356 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700357 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800358 }
359 }
360 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800361}
362
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700363ResponseCode KeyStore::list(const android::String8& prefix,
364 android::Vector<android::String16>* matches, uid_t userId) {
Kenny Roota91203b2012-02-15 15:00:46 -0800365
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700366 UserState* userState = getUserState(userId);
367 size_t n = prefix.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800368
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700369 DIR* dir = opendir(userState->getUserDirName());
370 if (!dir) {
371 ALOGW("can't open directory for user: %s", strerror(errno));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100372 return ResponseCode::SYSTEM_ERROR;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700373 }
374
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700375 struct dirent* file;
376 while ((file = readdir(dir)) != NULL) {
377 // We only care about files.
378 if (file->d_type != DT_REG) {
379 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700380 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700381
382 // Skip anything that starts with a "."
383 if (file->d_name[0] == '.') {
384 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700385 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700386
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700387 if (!strncmp(prefix.string(), file->d_name, n)) {
388 const char* p = &file->d_name[n];
389 size_t plen = strlen(p);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700390
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700391 size_t extra = decode_key_length(p, plen);
392 char* match = (char*)malloc(extra + 1);
393 if (match != NULL) {
394 decode_key(match, p, plen);
395 matches->push(android::String16(match, extra));
396 free(match);
Chad Brubakerdf705172015-06-17 20:17:51 -0700397 } else {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700398 ALOGW("could not allocate match of size %zd", extra);
Chad Brubakerdf705172015-06-17 20:17:51 -0700399 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700400 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700401 }
402 closedir(dir);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100403 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700404}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700405
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700406void KeyStore::addGrant(const char* filename, uid_t granteeUid) {
407 const grant_t* existing = getGrant(filename, granteeUid);
408 if (existing == NULL) {
409 grant_t* grant = new grant_t;
410 grant->uid = granteeUid;
411 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
412 mGrants.add(grant);
413 }
414}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700415
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700416bool KeyStore::removeGrant(const char* filename, uid_t granteeUid) {
417 for (android::Vector<grant_t*>::iterator it(mGrants.begin()); it != mGrants.end(); it++) {
418 grant_t* grant = *it;
419 if (grant->uid == granteeUid &&
420 !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
421 mGrants.erase(it);
422 return true;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700423 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700424 }
425 return false;
426}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700427
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700428ResponseCode KeyStore::importKey(const uint8_t* key, size_t keyLen, const char* filename,
429 uid_t userId, int32_t flags) {
430 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
431 if (!pkcs8.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100432 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700433 }
434 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
435 if (!pkey.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100436 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700437 }
438 int type = EVP_PKEY_type(pkey->type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100439 AuthorizationSet params;
440 add_legacy_key_authorizations(type, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700441 switch (type) {
442 case EVP_PKEY_RSA:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100443 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700444 break;
445 case EVP_PKEY_EC:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100446 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700447 break;
448 default:
449 ALOGW("Unsupported key type %d", type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100450 return ResponseCode::SYSTEM_ERROR;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700451 }
452
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100453 AuthorizationSet opParams(params);
454 hidl_vec<uint8_t> blob;
Kenny Root07438c82012-11-02 15:41:02 -0700455
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100456 ErrorCode error;
457 auto hidlCb = [&] (ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
458 const KeyCharacteristics& /* ignored */) {
459 error = ret;
460 if (error != ErrorCode::OK) return;
461 blob = keyBlob;
462 };
463 auto input = blob2hidlVec(key, keyLen);
Kenny Roota91203b2012-02-15 15:00:46 -0800464
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100465 ErrorCode rc = KS_HANDLE_HIDL_ERROR(
466 mDevice->importKey(params.hidl_data(), KeyFormat::PKCS8, input, hidlCb));
467 if (rc != ErrorCode::OK) return ResponseCode::SYSTEM_ERROR;
468 if (error != ErrorCode::OK) {
469 ALOGE("Keymaster error %d importing key pair", error);
470 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700471 }
472
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100473 Blob keyBlob(&blob[0], blob.size(), NULL, 0, TYPE_KEYMASTER_10);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700474
475 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100476 keyBlob.setFallback(false);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700477
478 return put(filename, &keyBlob, userId);
479}
480
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100481bool KeyStore::isHardwareBacked(const android::String16& /*keyType*/) const {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700482 if (mDevice == NULL) {
483 ALOGW("can't get keymaster device");
484 return false;
485 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100486// TODO: This information seems not to be available here
487// if (sRSAKeyType == keyType) {
488// return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
489// } else {
490// return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0 &&
491// (mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2);
492// }
493 return true;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700494}
495
496ResponseCode KeyStore::getKeyForName(Blob* keyBlob, const android::String8& keyName,
497 const uid_t uid, const BlobType type) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400498 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid, type));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700499 uid_t userId = get_user_id(uid);
500
501 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100502 if (responseCode == ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700503 return responseCode;
Riley Spahneaabae92014-06-30 12:39:52 -0700504 }
505
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700506 // If this is one of the legacy UID->UID mappings, use it.
507 uid_t euid = get_keystore_euid(uid);
508 if (euid != uid) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400509 filepath8 = getKeyNameForUidWithDir(keyName, euid, type);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700510 responseCode = get(filepath8.string(), keyBlob, type, userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100511 if (responseCode == ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700512 return responseCode;
513 }
514 }
515
516 // They might be using a granted key.
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400517 android::String8 filename8 = getKeyName(keyName, type);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700518 char* end;
519 strtoul(filename8.string(), &end, 10);
520 if (end[0] != '_' || end[1] == 0) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100521 return ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700522 }
523 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
524 filename8.string());
525 if (!hasGrant(filepath8.string(), uid)) {
526 return responseCode;
527 }
528
529 // It is a granted key. Try to load it.
530 return get(filepath8.string(), keyBlob, type, userId);
531}
532
533UserState* KeyStore::getUserState(uid_t userId) {
534 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
535 it++) {
536 UserState* state = *it;
537 if (state->getUserId() == userId) {
538 return state;
539 }
540 }
541
542 UserState* userState = new UserState(userId);
543 if (!userState->initialize()) {
544 /* There's not much we can do if initialization fails. Trying to
545 * unlock the keystore for that user will fail as well, so any
546 * subsequent request for this user will just return SYSTEM_ERROR.
547 */
548 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
549 }
550 mMasterKeys.add(userState);
551 return userState;
552}
553
554UserState* KeyStore::getUserStateByUid(uid_t uid) {
555 uid_t userId = get_user_id(uid);
556 return getUserState(userId);
557}
558
559const UserState* KeyStore::getUserState(uid_t userId) const {
560 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
561 it != mMasterKeys.end(); it++) {
562 UserState* state = *it;
563 if (state->getUserId() == userId) {
564 return state;
565 }
566 }
567
568 return NULL;
569}
570
571const UserState* KeyStore::getUserStateByUid(uid_t uid) const {
572 uid_t userId = get_user_id(uid);
573 return getUserState(userId);
574}
575
576const grant_t* KeyStore::getGrant(const char* filename, uid_t uid) const {
577 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin()); it != mGrants.end(); it++) {
578 grant_t* grant = *it;
579 if (grant->uid == uid &&
580 !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
581 return grant;
582 }
583 }
584 return NULL;
585}
586
587bool KeyStore::upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
588 const BlobType type, uid_t uid) {
589 bool updated = false;
590 uint8_t version = oldVersion;
591
592 /* From V0 -> V1: All old types were unknown */
593 if (version == 0) {
594 ALOGV("upgrading to version 1 and setting type %d", type);
595
596 blob->setType(type);
597 if (type == TYPE_KEY_PAIR) {
598 importBlobAsKey(blob, filename, uid);
599 }
600 version = 1;
601 updated = true;
602 }
603
604 /* From V1 -> V2: All old keys were encrypted */
605 if (version == 1) {
606 ALOGV("upgrading to version 2");
607
608 blob->setEncrypted(true);
609 version = 2;
610 updated = true;
Kenny Roota91203b2012-02-15 15:00:46 -0800611 }
Kenny Root07438c82012-11-02 15:41:02 -0700612
613 /*
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700614 * If we've updated, set the key blob to the right version
615 * and write it.
Kenny Root07438c82012-11-02 15:41:02 -0700616 */
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700617 if (updated) {
618 ALOGV("updated and writing file %s", filename);
619 blob->setVersion(version);
620 }
Kenny Root70e3a862012-02-15 17:20:23 -0800621
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700622 return updated;
623}
624
625struct BIO_Delete {
626 void operator()(BIO* p) const { BIO_free(p); }
627};
628typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
629
630ResponseCode KeyStore::importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
631 // We won't even write to the blob directly with this BIO, so const_cast is okay.
632 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
633 if (b.get() == NULL) {
634 ALOGE("Problem instantiating BIO");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100635 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700636 }
637
638 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
639 if (pkey.get() == NULL) {
640 ALOGE("Couldn't read old PEM file");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100641 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700642 }
643
644 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
645 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
646 if (len < 0) {
647 ALOGE("Couldn't measure PKCS#8 length");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100648 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700649 }
650
651 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
652 uint8_t* tmp = pkcs8key.get();
653 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
654 ALOGE("Couldn't convert to PKCS#8");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100655 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700656 }
657
658 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
659 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100660 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700661 return rc;
662 }
663
664 return get(filename, blob, TYPE_KEY_PAIR, uid);
665}
666
667void KeyStore::readMetaData() {
668 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
669 if (in < 0) {
670 return;
671 }
672 size_t fileLength = readFully(in, (uint8_t*)&mMetaData, sizeof(mMetaData));
673 if (fileLength != sizeof(mMetaData)) {
674 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength, sizeof(mMetaData));
675 }
676 close(in);
677}
678
679void KeyStore::writeMetaData() {
680 const char* tmpFileName = ".metadata.tmp";
681 int out =
682 TEMP_FAILURE_RETRY(open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
683 if (out < 0) {
684 ALOGE("couldn't write metadata file: %s", strerror(errno));
685 return;
686 }
687 size_t fileLength = writeFully(out, (uint8_t*)&mMetaData, sizeof(mMetaData));
688 if (fileLength != sizeof(mMetaData)) {
689 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
690 sizeof(mMetaData));
691 }
692 close(out);
693 rename(tmpFileName, sMetaDataFile);
694}
695
696bool KeyStore::upgradeKeystore() {
697 bool upgraded = false;
698
699 if (mMetaData.version == 0) {
700 UserState* userState = getUserStateByUid(0);
701
702 // Initialize first so the directory is made.
703 userState->initialize();
704
705 // Migrate the old .masterkey file to user 0.
706 if (access(sOldMasterKey, R_OK) == 0) {
707 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
708 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
709 return false;
710 }
711 }
712
713 // Initialize again in case we had a key.
714 userState->initialize();
715
716 // Try to migrate existing keys.
717 DIR* dir = opendir(".");
718 if (!dir) {
719 // Give up now; maybe we can upgrade later.
720 ALOGE("couldn't open keystore's directory; something is wrong");
721 return false;
722 }
723
724 struct dirent* file;
725 while ((file = readdir(dir)) != NULL) {
726 // We only care about files.
727 if (file->d_type != DT_REG) {
728 continue;
729 }
730
731 // Skip anything that starts with a "."
732 if (file->d_name[0] == '.') {
733 continue;
734 }
735
736 // Find the current file's user.
737 char* end;
738 unsigned long thisUid = strtoul(file->d_name, &end, 10);
739 if (end[0] != '_' || end[1] == 0) {
740 continue;
741 }
742 UserState* otherUser = getUserStateByUid(thisUid);
743 if (otherUser->getUserId() != 0) {
744 unlinkat(dirfd(dir), file->d_name, 0);
745 }
746
747 // Rename the file into user directory.
748 DIR* otherdir = opendir(otherUser->getUserDirName());
749 if (otherdir == NULL) {
750 ALOGW("couldn't open user directory for rename");
751 continue;
752 }
753 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
754 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
755 }
756 closedir(otherdir);
757 }
758 closedir(dir);
759
760 mMetaData.version = 1;
761 upgraded = true;
762 }
763
764 return upgraded;
Kenny Roota91203b2012-02-15 15:00:46 -0800765}