blob: a5d482e2b89bd280eb1094be7e68f4652454b213 [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>
Janis Danisevskis6905c332017-09-01 13:24:23 -070027#include <utils/String8.h>
Kenny Root70e3a862012-02-15 17:20:23 -080028
Kenny Root07438c82012-11-02 15:41:02 -070029#include <keystore/IKeystoreService.h>
Kenny Root07438c82012-11-02 15:41:02 -070030
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010031#include <android/hardware/keymaster/3.0/IKeymasterDevice.h>
32
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070033#include "keystore_utils.h"
34#include "permissions.h"
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010035#include <keystore/keystore_hidl_support.h>
Kenny Roota91203b2012-02-15 15:00:46 -080036
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070037const char* KeyStore::sOldMasterKey = ".masterkey";
38const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Roota91203b2012-02-15 15:00:46 -080039
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070040const android::String16 KeyStore::sRSAKeyType("RSA");
Riley Spahneaabae92014-06-30 12:39:52 -070041
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010042using namespace keystore;
Janis Danisevskis6905c332017-09-01 13:24:23 -070043using android::String8;
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010044
Janis Danisevskise8ba1802017-01-30 10:49:51 +000045KeyStore::KeyStore(Entropy* entropy, const km_device_t& device, const km_device_t& fallback,
46 bool allowNewFallback)
47 : mEntropy(entropy), mDevice(device), mFallbackDevice(fallback),
48 mAllowNewFallback(allowNewFallback) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070049 memset(&mMetaData, '\0', sizeof(mMetaData));
Kenny Root70e3a862012-02-15 17:20:23 -080050}
51
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070052KeyStore::~KeyStore() {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070053 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
54 it++) {
55 delete *it;
Shawn Willden55268b52015-07-28 11:06:00 -060056 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070057 mMasterKeys.clear();
Shawn Willden55268b52015-07-28 11:06:00 -060058}
59
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070060ResponseCode KeyStore::initialize() {
61 readMetaData();
62 if (upgradeKeystore()) {
63 writeMetaData();
Shawn Willden55268b52015-07-28 11:06:00 -060064 }
65
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010066 return ResponseCode::NO_ERROR;
Shawn Willden55268b52015-07-28 11:06:00 -060067}
68
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070069ResponseCode KeyStore::initializeUser(const android::String8& pw, uid_t userId) {
70 UserState* userState = getUserState(userId);
71 return userState->initialize(pw, mEntropy);
Chad Brubakerfc18edc2015-01-12 15:17:18 -080072}
73
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070074ResponseCode KeyStore::copyMasterKey(uid_t srcUser, uid_t dstUser) {
75 UserState* userState = getUserState(dstUser);
76 UserState* initState = getUserState(srcUser);
77 return userState->copyMasterKey(initState);
Kenny Root70e3a862012-02-15 17:20:23 -080078}
79
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070080ResponseCode KeyStore::writeMasterKey(const android::String8& pw, uid_t userId) {
81 UserState* userState = getUserState(userId);
82 return userState->writeMasterKey(pw, mEntropy);
Shawn Willden55268b52015-07-28 11:06:00 -060083}
84
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070085ResponseCode KeyStore::readMasterKey(const android::String8& pw, uid_t userId) {
86 UserState* userState = getUserState(userId);
87 return userState->readMasterKey(pw, mEntropy);
Kenny Root49468902013-03-19 13:41:33 -070088}
89
Kenny Roota91203b2012-02-15 15:00:46 -080090/* Here is the encoding of keys. This is necessary in order to allow arbitrary
91 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
92 * into two bytes. The first byte is one of [+-.] which represents the first
93 * two bits of the character. The second byte encodes the rest of the bits into
94 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
95 * that Base64 cannot be used here due to the need of prefix match on keys. */
96
Kenny Root655b9582013-04-04 08:37:42 -070097static size_t encode_key_length(const android::String8& keyName) {
98 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
99 size_t length = keyName.length();
100 for (int i = length; i > 0; --i, ++in) {
101 if (*in < '0' || *in > '~') {
102 ++length;
103 }
104 }
105 return length;
106}
107
Kenny Root07438c82012-11-02 15:41:02 -0700108static int encode_key(char* out, const android::String8& keyName) {
109 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
110 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800111 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700112 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800113 *out = '+' + (*in >> 6);
114 *++out = '0' + (*in & 0x3F);
115 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700116 } else {
117 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800118 }
119 }
120 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800121 return length;
122}
123
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400124android::String8 KeyStore::getKeyName(const android::String8& keyName, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000125 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
126 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400127 if (type == TYPE_KEY_CHARACTERISTICS) {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400128 return android::String8::format(".chr_%s", encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400129 } else {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400130 return android::String8(encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400131 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700132}
133
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400134android::String8 KeyStore::getKeyNameForUid(
135 const android::String8& keyName, uid_t uid, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000136 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
137 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400138 if (type == TYPE_KEY_CHARACTERISTICS) {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400139 return android::String8::format(".%u_chr_%s", uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400140 } else {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400141 return android::String8::format("%u_%s", uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400142 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700143}
144
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400145android::String8 KeyStore::getKeyNameForUidWithDir(
146 const android::String8& keyName, uid_t uid, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000147 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
148 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400149
150 if (type == TYPE_KEY_CHARACTERISTICS) {
151 return android::String8::format("%s/.%u_chr_%s", getUserStateByUid(uid)->getUserDirName(),
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400152 uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400153 } else {
154 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400155 encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400156 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700157}
158
159void KeyStore::resetUser(uid_t userId, bool keepUnenryptedEntries) {
160 android::String8 prefix("");
161 android::Vector<android::String16> aliases;
162 UserState* userState = getUserState(userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100163 if (list(prefix, &aliases, userId) != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700164 return;
165 }
166 for (uint32_t i = 0; i < aliases.size(); i++) {
167 android::String8 filename(aliases[i]);
168 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400169 getKeyName(filename, TYPE_ANY).string());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700170 bool shouldDelete = true;
171 if (keepUnenryptedEntries) {
172 Blob blob;
173 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
174
Shawn Willden07aebe72017-02-28 13:53:24 -0700175 switch (rc) {
176 case ResponseCode::SYSTEM_ERROR:
177 case ResponseCode::VALUE_CORRUPTED:
178 // If we can't read blobs, delete them.
179 shouldDelete = true;
180 break;
181
182 case ResponseCode::NO_ERROR:
183 case ResponseCode::LOCKED:
184 // Delete encrypted blobs but keep unencrypted blobs and super-encrypted blobs. We
185 // need to keep super-encrypted blobs so we can report that the user is
186 // unauthenticated if a caller tries to use them, rather than reporting that they
187 // don't exist.
188 shouldDelete = blob.isEncrypted();
189 break;
190
191 default:
192 ALOGE("Got unexpected return code %d from KeyStore::get()", rc);
193 // This shouldn't happen. To be on the safe side, delete it.
194 shouldDelete = true;
195 break;
196 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700197 }
198 if (shouldDelete) {
199 del(filename, ::TYPE_ANY, userId);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400200
201 // del() will fail silently if no cached characteristics are present for this alias.
202 android::String8 chr_filename(aliases[i]);
203 chr_filename = android::String8::format("%s/%s", userState->getUserDirName(),
204 getKeyName(chr_filename,
205 TYPE_KEY_CHARACTERISTICS).string());
206 del(chr_filename, ::TYPE_KEY_CHARACTERISTICS, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700207 }
208 }
209 if (!userState->deleteMasterKey()) {
210 ALOGE("Failed to delete user %d's master key", userId);
211 }
212 if (!keepUnenryptedEntries) {
213 if (!userState->reset()) {
214 ALOGE("Failed to remove user %d's directory", userId);
215 }
216 }
217}
218
219bool KeyStore::isEmpty(uid_t userId) const {
220 const UserState* userState = getUserState(userId);
221 if (userState == NULL) {
222 return true;
223 }
224
225 DIR* dir = opendir(userState->getUserDirName());
226 if (!dir) {
227 return true;
228 }
229
230 bool result = true;
231 struct dirent* file;
232 while ((file = readdir(dir)) != NULL) {
233 // We only care about files.
234 if (file->d_type != DT_REG) {
235 continue;
236 }
237
238 // Skip anything that starts with a "."
239 if (file->d_name[0] == '.') {
240 continue;
241 }
242
243 result = false;
244 break;
245 }
246 closedir(dir);
247 return result;
248}
249
250void KeyStore::lock(uid_t userId) {
251 UserState* userState = getUserState(userId);
252 userState->zeroizeMasterKeysInMemory();
253 userState->setState(STATE_LOCKED);
254}
255
256ResponseCode KeyStore::get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
257 UserState* userState = getUserState(userId);
258 ResponseCode rc =
Shawn Willdene9830582017-04-18 10:47:57 -0600259 keyBlob->readBlob(filename, userState->getEncryptionKey(), userState->getState());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100260 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700261 return rc;
262 }
263
264 const uint8_t version = keyBlob->getVersion();
265 if (version < CURRENT_BLOB_VERSION) {
266 /* If we upgrade the key, we need to write it to disk again. Then
267 * it must be read it again since the blob is encrypted each time
268 * it's written.
269 */
270 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100271 if ((rc = this->put(filename, keyBlob, userId)) != ResponseCode::NO_ERROR ||
Shawn Willdene9830582017-04-18 10:47:57 -0600272 (rc = keyBlob->readBlob(filename, userState->getEncryptionKey(),
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100273 userState->getState())) != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700274 return rc;
275 }
276 }
277 }
278
279 /*
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100280 * This will upgrade software-backed keys to hardware-backed keys.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700281 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100282 if (rc == ResponseCode::NO_ERROR && type == TYPE_KEY_PAIR && keyBlob->isFallback()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700283 ResponseCode imported =
284 importKey(keyBlob->getValue(), keyBlob->getLength(), filename, userId,
285 keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
286
Shawn Willden07aebe72017-02-28 13:53:24 -0700287 // The HAL allowed the import, reget the key to have the "fresh" version.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100288 if (imported == ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700289 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
290 }
291 }
292
293 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
294 if (keyBlob->getType() == TYPE_KEY_PAIR) {
295 keyBlob->setType(TYPE_KEYMASTER_10);
296 rc = this->put(filename, keyBlob, userId);
297 }
298
299 if (type != TYPE_ANY && keyBlob->getType() != type) {
300 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100301 return ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700302 }
303
304 return rc;
305}
306
307ResponseCode KeyStore::put(const char* filename, Blob* keyBlob, uid_t userId) {
308 UserState* userState = getUserState(userId);
309 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
310 mEntropy);
311}
312
313ResponseCode KeyStore::del(const char* filename, const BlobType type, uid_t userId) {
314 Blob keyBlob;
315 ResponseCode rc = get(filename, &keyBlob, type, userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100316 if (rc == ResponseCode::VALUE_CORRUPTED) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700317 // The file is corrupt, the best we can do is rm it.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100318 return (unlink(filename) && errno != ENOENT) ?
319 ResponseCode::SYSTEM_ERROR : ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700320 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100321 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700322 return rc;
323 }
324
Janis Danisevskis69c434a2017-01-30 10:27:10 +0000325 auto& dev = getDevice(keyBlob);
326
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100327 if (keyBlob.getType() == ::TYPE_KEY_PAIR || keyBlob.getType() == ::TYPE_KEYMASTER_10) {
Janis Danisevskis69c434a2017-01-30 10:27:10 +0000328 auto ret = KS_HANDLE_HIDL_ERROR(dev->deleteKey(blob2hidlVec(keyBlob)));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100329
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700330 // A device doesn't have to implement delete_key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100331 if (ret != ErrorCode::OK && ret != ErrorCode::UNIMPLEMENTED)
332 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700333 }
334
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100335 return (unlink(filename) && errno != ENOENT) ?
336 ResponseCode::SYSTEM_ERROR : ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700337}
338
Kenny Root07438c82012-11-02 15:41:02 -0700339/*
340 * Converts from the "escaped" format on disk to actual name.
341 * This will be smaller than the input string.
342 *
343 * Characters that should combine with the next at the end will be truncated.
344 */
345static size_t decode_key_length(const char* in, size_t length) {
346 size_t outLength = 0;
347
348 for (const char* end = in + length; in < end; in++) {
349 /* This combines with the next character. */
350 if (*in < '0' || *in > '~') {
351 continue;
352 }
353
354 outLength++;
355 }
356 return outLength;
357}
358
359static void decode_key(char* out, const char* in, size_t length) {
360 for (const char* end = in + length; in < end; in++) {
361 if (*in < '0' || *in > '~') {
362 /* Truncate combining characters at the end. */
363 if (in + 1 >= end) {
364 break;
365 }
366
367 *out = (*in++ - '+') << 6;
368 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800369 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700370 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800371 }
372 }
373 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800374}
375
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700376ResponseCode KeyStore::list(const android::String8& prefix,
377 android::Vector<android::String16>* matches, uid_t userId) {
Kenny Roota91203b2012-02-15 15:00:46 -0800378
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700379 UserState* userState = getUserState(userId);
380 size_t n = prefix.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800381
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700382 DIR* dir = opendir(userState->getUserDirName());
383 if (!dir) {
384 ALOGW("can't open directory for user: %s", strerror(errno));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100385 return ResponseCode::SYSTEM_ERROR;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700386 }
387
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700388 struct dirent* file;
389 while ((file = readdir(dir)) != NULL) {
390 // We only care about files.
391 if (file->d_type != DT_REG) {
392 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700393 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700394
395 // Skip anything that starts with a "."
396 if (file->d_name[0] == '.') {
397 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700398 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700399
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700400 if (!strncmp(prefix.string(), file->d_name, n)) {
401 const char* p = &file->d_name[n];
402 size_t plen = strlen(p);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700403
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700404 size_t extra = decode_key_length(p, plen);
405 char* match = (char*)malloc(extra + 1);
406 if (match != NULL) {
407 decode_key(match, p, plen);
408 matches->push(android::String16(match, extra));
409 free(match);
Chad Brubakerdf705172015-06-17 20:17:51 -0700410 } else {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700411 ALOGW("could not allocate match of size %zd", extra);
Chad Brubakerdf705172015-06-17 20:17:51 -0700412 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700413 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700414 }
415 closedir(dir);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100416 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700417}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700418
Janis Danisevskis6905c332017-09-01 13:24:23 -0700419std::string KeyStore::addGrant(const char* alias, uid_t granterUid, uid_t granteeUid) {
420 return mGrants.put(granteeUid, alias, getUserStateByUid(granterUid)->getUserDirName(),
421 granterUid);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700422}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700423
Janis Danisevskis6905c332017-09-01 13:24:23 -0700424bool KeyStore::removeGrant(const char* alias, uid_t granteeUid) {
425 return mGrants.removeByFileAlias(granteeUid, alias);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700426}
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 Willdenb8550a02017-02-23 11:06:05 -0700482 using ::android::hardware::hidl_string;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700483 if (mDevice == NULL) {
484 ALOGW("can't get keymaster device");
485 return false;
486 }
Janis Danisevskise2b6caf2017-03-02 16:37:10 -0800487
488 bool isSecure = false;
Shawn Willdenb8550a02017-02-23 11:06:05 -0700489 auto hidlcb = [&] (bool _isSecure, bool, bool, bool, bool, const hidl_string&,
490 const hidl_string&) {
Janis Danisevskise2b6caf2017-03-02 16:37:10 -0800491 isSecure = _isSecure;
492 };
493 auto rc = mDevice->getHardwareFeatures(hidlcb);
494 if (!rc.isOk()) {
495 ALOGE("Communication with keymaster HAL failed while retrieving hardware features (%s)",
496 rc.description().c_str());
497 return false;
498 }
499 return isSecure;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700500}
501
502ResponseCode KeyStore::getKeyForName(Blob* keyBlob, const android::String8& keyName,
503 const uid_t uid, const BlobType type) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400504 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid, type));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700505 uid_t userId = get_user_id(uid);
506
507 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100508 if (responseCode == ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700509 return responseCode;
Riley Spahneaabae92014-06-30 12:39:52 -0700510 }
511
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700512 // If this is one of the legacy UID->UID mappings, use it.
513 uid_t euid = get_keystore_euid(uid);
514 if (euid != uid) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400515 filepath8 = getKeyNameForUidWithDir(keyName, euid, type);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700516 responseCode = get(filepath8.string(), keyBlob, type, userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100517 if (responseCode == ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700518 return responseCode;
519 }
520 }
521
522 // They might be using a granted key.
Janis Danisevskis6d449e82017-06-07 18:03:31 -0700523 auto grant = mGrants.get(uid, keyName.string());
524 if (!grant) return ResponseCode::KEY_NOT_FOUND;
Janis Danisevskis6905c332017-09-01 13:24:23 -0700525 filepath8.format("%s/%s", grant->owner_dir_name_.c_str(),
526 getKeyNameForUid(String8(grant->alias_.c_str()), grant->owner_uid_, type).c_str());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700527
528 // It is a granted key. Try to load it.
529 return get(filepath8.string(), keyBlob, type, userId);
530}
531
532UserState* KeyStore::getUserState(uid_t userId) {
533 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
534 it++) {
535 UserState* state = *it;
536 if (state->getUserId() == userId) {
537 return state;
538 }
539 }
540
541 UserState* userState = new UserState(userId);
542 if (!userState->initialize()) {
543 /* There's not much we can do if initialization fails. Trying to
544 * unlock the keystore for that user will fail as well, so any
545 * subsequent request for this user will just return SYSTEM_ERROR.
546 */
547 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
548 }
549 mMasterKeys.add(userState);
550 return userState;
551}
552
553UserState* KeyStore::getUserStateByUid(uid_t uid) {
554 uid_t userId = get_user_id(uid);
555 return getUserState(userId);
556}
557
558const UserState* KeyStore::getUserState(uid_t userId) const {
559 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
560 it != mMasterKeys.end(); it++) {
561 UserState* state = *it;
562 if (state->getUserId() == userId) {
563 return state;
564 }
565 }
566
567 return NULL;
568}
569
570const UserState* KeyStore::getUserStateByUid(uid_t uid) const {
571 uid_t userId = get_user_id(uid);
572 return getUserState(userId);
573}
574
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700575bool KeyStore::upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
576 const BlobType type, uid_t uid) {
577 bool updated = false;
578 uint8_t version = oldVersion;
579
580 /* From V0 -> V1: All old types were unknown */
581 if (version == 0) {
582 ALOGV("upgrading to version 1 and setting type %d", type);
583
584 blob->setType(type);
585 if (type == TYPE_KEY_PAIR) {
586 importBlobAsKey(blob, filename, uid);
587 }
588 version = 1;
589 updated = true;
590 }
591
592 /* From V1 -> V2: All old keys were encrypted */
593 if (version == 1) {
594 ALOGV("upgrading to version 2");
595
596 blob->setEncrypted(true);
597 version = 2;
598 updated = true;
Kenny Roota91203b2012-02-15 15:00:46 -0800599 }
Kenny Root07438c82012-11-02 15:41:02 -0700600
601 /*
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700602 * If we've updated, set the key blob to the right version
603 * and write it.
Kenny Root07438c82012-11-02 15:41:02 -0700604 */
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700605 if (updated) {
606 ALOGV("updated and writing file %s", filename);
607 blob->setVersion(version);
608 }
Kenny Root70e3a862012-02-15 17:20:23 -0800609
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700610 return updated;
611}
612
613struct BIO_Delete {
614 void operator()(BIO* p) const { BIO_free(p); }
615};
Janis Danisevskisccfff102017-05-01 11:02:51 -0700616typedef std::unique_ptr<BIO, BIO_Delete> Unique_BIO;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700617
618ResponseCode KeyStore::importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
619 // We won't even write to the blob directly with this BIO, so const_cast is okay.
620 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
621 if (b.get() == NULL) {
622 ALOGE("Problem instantiating BIO");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100623 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700624 }
625
626 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
627 if (pkey.get() == NULL) {
628 ALOGE("Couldn't read old PEM file");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100629 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700630 }
631
632 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
633 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
634 if (len < 0) {
635 ALOGE("Couldn't measure PKCS#8 length");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100636 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700637 }
638
Janis Danisevskisccfff102017-05-01 11:02:51 -0700639 std::unique_ptr<unsigned char[]> pkcs8key(new unsigned char[len]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700640 uint8_t* tmp = pkcs8key.get();
641 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
642 ALOGE("Couldn't convert to PKCS#8");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100643 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700644 }
645
646 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
647 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100648 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700649 return rc;
650 }
651
652 return get(filename, blob, TYPE_KEY_PAIR, uid);
653}
654
655void KeyStore::readMetaData() {
656 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
657 if (in < 0) {
658 return;
659 }
660 size_t fileLength = readFully(in, (uint8_t*)&mMetaData, sizeof(mMetaData));
661 if (fileLength != sizeof(mMetaData)) {
662 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength, sizeof(mMetaData));
663 }
664 close(in);
665}
666
667void KeyStore::writeMetaData() {
668 const char* tmpFileName = ".metadata.tmp";
669 int out =
670 TEMP_FAILURE_RETRY(open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
671 if (out < 0) {
672 ALOGE("couldn't write metadata file: %s", strerror(errno));
673 return;
674 }
675 size_t fileLength = writeFully(out, (uint8_t*)&mMetaData, sizeof(mMetaData));
676 if (fileLength != sizeof(mMetaData)) {
677 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
678 sizeof(mMetaData));
679 }
680 close(out);
681 rename(tmpFileName, sMetaDataFile);
682}
683
684bool KeyStore::upgradeKeystore() {
685 bool upgraded = false;
686
687 if (mMetaData.version == 0) {
688 UserState* userState = getUserStateByUid(0);
689
690 // Initialize first so the directory is made.
691 userState->initialize();
692
693 // Migrate the old .masterkey file to user 0.
694 if (access(sOldMasterKey, R_OK) == 0) {
695 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
696 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
697 return false;
698 }
699 }
700
701 // Initialize again in case we had a key.
702 userState->initialize();
703
704 // Try to migrate existing keys.
705 DIR* dir = opendir(".");
706 if (!dir) {
707 // Give up now; maybe we can upgrade later.
708 ALOGE("couldn't open keystore's directory; something is wrong");
709 return false;
710 }
711
712 struct dirent* file;
713 while ((file = readdir(dir)) != NULL) {
714 // We only care about files.
715 if (file->d_type != DT_REG) {
716 continue;
717 }
718
719 // Skip anything that starts with a "."
720 if (file->d_name[0] == '.') {
721 continue;
722 }
723
724 // Find the current file's user.
725 char* end;
726 unsigned long thisUid = strtoul(file->d_name, &end, 10);
727 if (end[0] != '_' || end[1] == 0) {
728 continue;
729 }
730 UserState* otherUser = getUserStateByUid(thisUid);
731 if (otherUser->getUserId() != 0) {
732 unlinkat(dirfd(dir), file->d_name, 0);
733 }
734
735 // Rename the file into user directory.
736 DIR* otherdir = opendir(otherUser->getUserDirName());
737 if (otherdir == NULL) {
738 ALOGW("couldn't open user directory for rename");
739 continue;
740 }
741 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
742 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
743 }
744 closedir(otherdir);
745 }
746 closedir(dir);
747
748 mMetaData.version = 1;
749 upgraded = true;
750 }
751
752 return upgraded;
Kenny Roota91203b2012-02-15 15:00:46 -0800753}