blob: ab386ad845be894ffd73437b0f0891cffddf0bfb [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
Janis Danisevskise8ba1802017-01-30 10:49:51 +000043KeyStore::KeyStore(Entropy* entropy, const km_device_t& device, const km_device_t& fallback,
44 bool allowNewFallback)
45 : mEntropy(entropy), mDevice(device), mFallbackDevice(fallback),
46 mAllowNewFallback(allowNewFallback) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070047 memset(&mMetaData, '\0', sizeof(mMetaData));
Kenny Root70e3a862012-02-15 17:20:23 -080048}
49
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070050KeyStore::~KeyStore() {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070051 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
52 it++) {
53 delete *it;
Shawn Willden55268b52015-07-28 11:06:00 -060054 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070055 mMasterKeys.clear();
Shawn Willden55268b52015-07-28 11:06:00 -060056}
57
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070058ResponseCode KeyStore::initialize() {
59 readMetaData();
60 if (upgradeKeystore()) {
61 writeMetaData();
Shawn Willden55268b52015-07-28 11:06:00 -060062 }
63
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +010064 return ResponseCode::NO_ERROR;
Shawn Willden55268b52015-07-28 11:06:00 -060065}
66
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070067ResponseCode KeyStore::initializeUser(const android::String8& pw, uid_t userId) {
68 UserState* userState = getUserState(userId);
69 return userState->initialize(pw, mEntropy);
Chad Brubakerfc18edc2015-01-12 15:17:18 -080070}
71
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070072ResponseCode KeyStore::copyMasterKey(uid_t srcUser, uid_t dstUser) {
73 UserState* userState = getUserState(dstUser);
74 UserState* initState = getUserState(srcUser);
75 return userState->copyMasterKey(initState);
Kenny Root70e3a862012-02-15 17:20:23 -080076}
77
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070078ResponseCode KeyStore::writeMasterKey(const android::String8& pw, uid_t userId) {
79 UserState* userState = getUserState(userId);
80 return userState->writeMasterKey(pw, mEntropy);
Shawn Willden55268b52015-07-28 11:06:00 -060081}
82
Shawn Willdenc1d1fee2016-01-26 22:44:56 -070083ResponseCode KeyStore::readMasterKey(const android::String8& pw, uid_t userId) {
84 UserState* userState = getUserState(userId);
85 return userState->readMasterKey(pw, mEntropy);
Kenny Root49468902013-03-19 13:41:33 -070086}
87
Kenny Roota91203b2012-02-15 15:00:46 -080088/* Here is the encoding of keys. This is necessary in order to allow arbitrary
89 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
90 * into two bytes. The first byte is one of [+-.] which represents the first
91 * two bits of the character. The second byte encodes the rest of the bits into
92 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
93 * that Base64 cannot be used here due to the need of prefix match on keys. */
94
Kenny Root655b9582013-04-04 08:37:42 -070095static size_t encode_key_length(const android::String8& keyName) {
96 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
97 size_t length = keyName.length();
98 for (int i = length; i > 0; --i, ++in) {
99 if (*in < '0' || *in > '~') {
100 ++length;
101 }
102 }
103 return length;
104}
105
Kenny Root07438c82012-11-02 15:41:02 -0700106static int encode_key(char* out, const android::String8& keyName) {
107 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
108 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800109 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700110 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800111 *out = '+' + (*in >> 6);
112 *++out = '0' + (*in & 0x3F);
113 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700114 } else {
115 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800116 }
117 }
118 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800119 return length;
120}
121
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400122android::String8 KeyStore::getKeyName(const android::String8& keyName, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000123 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
124 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400125 if (type == TYPE_KEY_CHARACTERISTICS) {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400126 return android::String8::format(".chr_%s", encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400127 } else {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400128 return android::String8(encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400129 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700130}
131
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400132android::String8 KeyStore::getKeyNameForUid(
133 const android::String8& keyName, uid_t uid, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000134 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
135 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400136 if (type == TYPE_KEY_CHARACTERISTICS) {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400137 return android::String8::format(".%u_chr_%s", uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400138 } else {
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400139 return android::String8::format("%u_%s", uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400140 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700141}
142
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400143android::String8 KeyStore::getKeyNameForUidWithDir(
144 const android::String8& keyName, uid_t uid, const BlobType type) {
Bin Chencfd95ae2016-08-22 12:16:09 +1000145 std::vector<char> encoded(encode_key_length(keyName) + 1); // add 1 for null char
146 encode_key(encoded.data(), keyName);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400147
148 if (type == TYPE_KEY_CHARACTERISTICS) {
149 return android::String8::format("%s/.%u_chr_%s", getUserStateByUid(uid)->getUserDirName(),
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400150 uid, encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400151 } else {
152 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Tucker Sylvestro9c28dd52016-10-06 15:09:48 -0400153 encoded.data());
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400154 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700155}
156
157void KeyStore::resetUser(uid_t userId, bool keepUnenryptedEntries) {
158 android::String8 prefix("");
159 android::Vector<android::String16> aliases;
160 UserState* userState = getUserState(userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100161 if (list(prefix, &aliases, userId) != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700162 return;
163 }
164 for (uint32_t i = 0; i < aliases.size(); i++) {
165 android::String8 filename(aliases[i]);
166 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400167 getKeyName(filename, TYPE_ANY).string());
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700168 bool shouldDelete = true;
169 if (keepUnenryptedEntries) {
170 Blob blob;
171 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
172
Shawn Willden07aebe72017-02-28 13:53:24 -0700173 switch (rc) {
174 case ResponseCode::SYSTEM_ERROR:
175 case ResponseCode::VALUE_CORRUPTED:
176 // If we can't read blobs, delete them.
177 shouldDelete = true;
178 break;
179
180 case ResponseCode::NO_ERROR:
181 case ResponseCode::LOCKED:
182 // Delete encrypted blobs but keep unencrypted blobs and super-encrypted blobs. We
183 // need to keep super-encrypted blobs so we can report that the user is
184 // unauthenticated if a caller tries to use them, rather than reporting that they
185 // don't exist.
186 shouldDelete = blob.isEncrypted();
187 break;
188
189 default:
190 ALOGE("Got unexpected return code %d from KeyStore::get()", rc);
191 // This shouldn't happen. To be on the safe side, delete it.
192 shouldDelete = true;
193 break;
194 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700195 }
196 if (shouldDelete) {
197 del(filename, ::TYPE_ANY, userId);
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400198
199 // del() will fail silently if no cached characteristics are present for this alias.
200 android::String8 chr_filename(aliases[i]);
201 chr_filename = android::String8::format("%s/%s", userState->getUserDirName(),
202 getKeyName(chr_filename,
203 TYPE_KEY_CHARACTERISTICS).string());
204 del(chr_filename, ::TYPE_KEY_CHARACTERISTICS, userId);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700205 }
206 }
207 if (!userState->deleteMasterKey()) {
208 ALOGE("Failed to delete user %d's master key", userId);
209 }
210 if (!keepUnenryptedEntries) {
211 if (!userState->reset()) {
212 ALOGE("Failed to remove user %d's directory", userId);
213 }
214 }
215}
216
217bool KeyStore::isEmpty(uid_t userId) const {
218 const UserState* userState = getUserState(userId);
219 if (userState == NULL) {
220 return true;
221 }
222
223 DIR* dir = opendir(userState->getUserDirName());
224 if (!dir) {
225 return true;
226 }
227
228 bool result = true;
229 struct dirent* file;
230 while ((file = readdir(dir)) != NULL) {
231 // We only care about files.
232 if (file->d_type != DT_REG) {
233 continue;
234 }
235
236 // Skip anything that starts with a "."
237 if (file->d_name[0] == '.') {
238 continue;
239 }
240
241 result = false;
242 break;
243 }
244 closedir(dir);
245 return result;
246}
247
248void KeyStore::lock(uid_t userId) {
249 UserState* userState = getUserState(userId);
250 userState->zeroizeMasterKeysInMemory();
251 userState->setState(STATE_LOCKED);
252}
253
254ResponseCode KeyStore::get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
255 UserState* userState = getUserState(userId);
256 ResponseCode rc =
Shawn Willdene9830582017-04-18 10:47:57 -0600257 keyBlob->readBlob(filename, userState->getEncryptionKey(), userState->getState());
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100258 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700259 return rc;
260 }
261
262 const uint8_t version = keyBlob->getVersion();
263 if (version < CURRENT_BLOB_VERSION) {
264 /* If we upgrade the key, we need to write it to disk again. Then
265 * it must be read it again since the blob is encrypted each time
266 * it's written.
267 */
268 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100269 if ((rc = this->put(filename, keyBlob, userId)) != ResponseCode::NO_ERROR ||
Shawn Willdene9830582017-04-18 10:47:57 -0600270 (rc = keyBlob->readBlob(filename, userState->getEncryptionKey(),
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100271 userState->getState())) != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700272 return rc;
273 }
274 }
275 }
276
277 /*
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100278 * This will upgrade software-backed keys to hardware-backed keys.
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700279 */
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100280 if (rc == ResponseCode::NO_ERROR && type == TYPE_KEY_PAIR && keyBlob->isFallback()) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700281 ResponseCode imported =
282 importKey(keyBlob->getValue(), keyBlob->getLength(), filename, userId,
283 keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
284
Shawn Willden07aebe72017-02-28 13:53:24 -0700285 // The HAL allowed the import, reget the key to have the "fresh" version.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100286 if (imported == ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700287 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
288 }
289 }
290
291 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
292 if (keyBlob->getType() == TYPE_KEY_PAIR) {
293 keyBlob->setType(TYPE_KEYMASTER_10);
294 rc = this->put(filename, keyBlob, userId);
295 }
296
297 if (type != TYPE_ANY && keyBlob->getType() != type) {
298 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100299 return ResponseCode::KEY_NOT_FOUND;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700300 }
301
302 return rc;
303}
304
305ResponseCode KeyStore::put(const char* filename, Blob* keyBlob, uid_t userId) {
306 UserState* userState = getUserState(userId);
307 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
308 mEntropy);
309}
310
311ResponseCode KeyStore::del(const char* filename, const BlobType type, uid_t userId) {
312 Blob keyBlob;
313 ResponseCode rc = get(filename, &keyBlob, type, userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100314 if (rc == ResponseCode::VALUE_CORRUPTED) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700315 // The file is corrupt, the best we can do is rm it.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100316 return (unlink(filename) && errno != ENOENT) ?
317 ResponseCode::SYSTEM_ERROR : ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700318 }
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100319 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700320 return rc;
321 }
322
Janis Danisevskis69c434a2017-01-30 10:27:10 +0000323 auto& dev = getDevice(keyBlob);
324
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100325 if (keyBlob.getType() == ::TYPE_KEY_PAIR || keyBlob.getType() == ::TYPE_KEYMASTER_10) {
Janis Danisevskis69c434a2017-01-30 10:27:10 +0000326 auto ret = KS_HANDLE_HIDL_ERROR(dev->deleteKey(blob2hidlVec(keyBlob)));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100327
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700328 // A device doesn't have to implement delete_key.
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100329 if (ret != ErrorCode::OK && ret != ErrorCode::UNIMPLEMENTED)
330 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700331 }
332
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100333 return (unlink(filename) && errno != ENOENT) ?
334 ResponseCode::SYSTEM_ERROR : ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700335}
336
Kenny Root07438c82012-11-02 15:41:02 -0700337/*
338 * Converts from the "escaped" format on disk to actual name.
339 * This will be smaller than the input string.
340 *
341 * Characters that should combine with the next at the end will be truncated.
342 */
343static size_t decode_key_length(const char* in, size_t length) {
344 size_t outLength = 0;
345
346 for (const char* end = in + length; in < end; in++) {
347 /* This combines with the next character. */
348 if (*in < '0' || *in > '~') {
349 continue;
350 }
351
352 outLength++;
353 }
354 return outLength;
355}
356
357static void decode_key(char* out, const char* in, size_t length) {
358 for (const char* end = in + length; in < end; in++) {
359 if (*in < '0' || *in > '~') {
360 /* Truncate combining characters at the end. */
361 if (in + 1 >= end) {
362 break;
363 }
364
365 *out = (*in++ - '+') << 6;
366 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800367 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700368 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800369 }
370 }
371 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800372}
373
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700374ResponseCode KeyStore::list(const android::String8& prefix,
375 android::Vector<android::String16>* matches, uid_t userId) {
Kenny Roota91203b2012-02-15 15:00:46 -0800376
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700377 UserState* userState = getUserState(userId);
378 size_t n = prefix.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800379
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700380 DIR* dir = opendir(userState->getUserDirName());
381 if (!dir) {
382 ALOGW("can't open directory for user: %s", strerror(errno));
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100383 return ResponseCode::SYSTEM_ERROR;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700384 }
385
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700386 struct dirent* file;
387 while ((file = readdir(dir)) != NULL) {
388 // We only care about files.
389 if (file->d_type != DT_REG) {
390 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700391 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700392
393 // Skip anything that starts with a "."
394 if (file->d_name[0] == '.') {
395 continue;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700396 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700397
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700398 if (!strncmp(prefix.string(), file->d_name, n)) {
399 const char* p = &file->d_name[n];
400 size_t plen = strlen(p);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700401
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700402 size_t extra = decode_key_length(p, plen);
403 char* match = (char*)malloc(extra + 1);
404 if (match != NULL) {
405 decode_key(match, p, plen);
406 matches->push(android::String16(match, extra));
407 free(match);
Chad Brubakerdf705172015-06-17 20:17:51 -0700408 } else {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700409 ALOGW("could not allocate match of size %zd", extra);
Chad Brubakerdf705172015-06-17 20:17:51 -0700410 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700411 }
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700412 }
413 closedir(dir);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100414 return ResponseCode::NO_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700415}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700416
Janis Danisevskis6d449e82017-06-07 18:03:31 -0700417std::string KeyStore::addGrant(const char* filename, const char* alias, uid_t granteeUid) {
418 return mGrants.put(granteeUid, alias, filename);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700419}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700420
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700421bool KeyStore::removeGrant(const char* filename, uid_t granteeUid) {
Janis Danisevskis6d449e82017-06-07 18:03:31 -0700422 return mGrants.removeByFileName(granteeUid, filename);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700423}
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700424
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700425ResponseCode KeyStore::importKey(const uint8_t* key, size_t keyLen, const char* filename,
426 uid_t userId, int32_t flags) {
427 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, keyLen));
428 if (!pkcs8.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100429 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700430 }
431 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
432 if (!pkey.get()) {
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100433 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700434 }
435 int type = EVP_PKEY_type(pkey->type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100436 AuthorizationSet params;
437 add_legacy_key_authorizations(type, &params);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700438 switch (type) {
439 case EVP_PKEY_RSA:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100440 params.push_back(TAG_ALGORITHM, Algorithm::RSA);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700441 break;
442 case EVP_PKEY_EC:
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100443 params.push_back(TAG_ALGORITHM, Algorithm::EC);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700444 break;
445 default:
446 ALOGW("Unsupported key type %d", type);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100447 return ResponseCode::SYSTEM_ERROR;
Chad Brubaker3a7d9e62015-06-04 15:01:46 -0700448 }
449
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100450 AuthorizationSet opParams(params);
451 hidl_vec<uint8_t> blob;
Kenny Root07438c82012-11-02 15:41:02 -0700452
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100453 ErrorCode error;
454 auto hidlCb = [&] (ErrorCode ret, const hidl_vec<uint8_t>& keyBlob,
455 const KeyCharacteristics& /* ignored */) {
456 error = ret;
457 if (error != ErrorCode::OK) return;
458 blob = keyBlob;
459 };
460 auto input = blob2hidlVec(key, keyLen);
Kenny Roota91203b2012-02-15 15:00:46 -0800461
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100462 ErrorCode rc = KS_HANDLE_HIDL_ERROR(
463 mDevice->importKey(params.hidl_data(), KeyFormat::PKCS8, input, hidlCb));
464 if (rc != ErrorCode::OK) return ResponseCode::SYSTEM_ERROR;
465 if (error != ErrorCode::OK) {
466 ALOGE("Keymaster error %d importing key pair", error);
467 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700468 }
469
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100470 Blob keyBlob(&blob[0], blob.size(), NULL, 0, TYPE_KEYMASTER_10);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700471
472 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100473 keyBlob.setFallback(false);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700474
475 return put(filename, &keyBlob, userId);
476}
477
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100478bool KeyStore::isHardwareBacked(const android::String16& /*keyType*/) const {
Shawn Willdenb8550a02017-02-23 11:06:05 -0700479 using ::android::hardware::hidl_string;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700480 if (mDevice == NULL) {
481 ALOGW("can't get keymaster device");
482 return false;
483 }
Janis Danisevskise2b6caf2017-03-02 16:37:10 -0800484
485 bool isSecure = false;
Shawn Willdenb8550a02017-02-23 11:06:05 -0700486 auto hidlcb = [&] (bool _isSecure, bool, bool, bool, bool, const hidl_string&,
487 const hidl_string&) {
Janis Danisevskise2b6caf2017-03-02 16:37:10 -0800488 isSecure = _isSecure;
489 };
490 auto rc = mDevice->getHardwareFeatures(hidlcb);
491 if (!rc.isOk()) {
492 ALOGE("Communication with keymaster HAL failed while retrieving hardware features (%s)",
493 rc.description().c_str());
494 return false;
495 }
496 return isSecure;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700497}
498
499ResponseCode KeyStore::getKeyForName(Blob* keyBlob, const android::String8& keyName,
500 const uid_t uid, const BlobType type) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400501 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid, type));
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700502 uid_t userId = get_user_id(uid);
503
504 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100505 if (responseCode == ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700506 return responseCode;
Riley Spahneaabae92014-06-30 12:39:52 -0700507 }
508
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700509 // If this is one of the legacy UID->UID mappings, use it.
510 uid_t euid = get_keystore_euid(uid);
511 if (euid != uid) {
Tucker Sylvestro0ab28b72016-08-05 18:02:47 -0400512 filepath8 = getKeyNameForUidWithDir(keyName, euid, type);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700513 responseCode = get(filepath8.string(), keyBlob, type, userId);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100514 if (responseCode == ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700515 return responseCode;
516 }
517 }
518
519 // They might be using a granted key.
Janis Danisevskis6d449e82017-06-07 18:03:31 -0700520 auto grant = mGrants.get(uid, keyName.string());
521 if (!grant) return ResponseCode::KEY_NOT_FOUND;
522 filepath8 = grant->key_file_.c_str();
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700523
524 // It is a granted key. Try to load it.
525 return get(filepath8.string(), keyBlob, type, userId);
526}
527
528UserState* KeyStore::getUserState(uid_t userId) {
529 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin()); it != mMasterKeys.end();
530 it++) {
531 UserState* state = *it;
532 if (state->getUserId() == userId) {
533 return state;
534 }
535 }
536
537 UserState* userState = new UserState(userId);
538 if (!userState->initialize()) {
539 /* There's not much we can do if initialization fails. Trying to
540 * unlock the keystore for that user will fail as well, so any
541 * subsequent request for this user will just return SYSTEM_ERROR.
542 */
543 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
544 }
545 mMasterKeys.add(userState);
546 return userState;
547}
548
549UserState* KeyStore::getUserStateByUid(uid_t uid) {
550 uid_t userId = get_user_id(uid);
551 return getUserState(userId);
552}
553
554const UserState* KeyStore::getUserState(uid_t userId) const {
555 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
556 it != mMasterKeys.end(); it++) {
557 UserState* state = *it;
558 if (state->getUserId() == userId) {
559 return state;
560 }
561 }
562
563 return NULL;
564}
565
566const UserState* KeyStore::getUserStateByUid(uid_t uid) const {
567 uid_t userId = get_user_id(uid);
568 return getUserState(userId);
569}
570
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700571bool KeyStore::upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
572 const BlobType type, uid_t uid) {
573 bool updated = false;
574 uint8_t version = oldVersion;
575
576 /* From V0 -> V1: All old types were unknown */
577 if (version == 0) {
578 ALOGV("upgrading to version 1 and setting type %d", type);
579
580 blob->setType(type);
581 if (type == TYPE_KEY_PAIR) {
582 importBlobAsKey(blob, filename, uid);
583 }
584 version = 1;
585 updated = true;
586 }
587
588 /* From V1 -> V2: All old keys were encrypted */
589 if (version == 1) {
590 ALOGV("upgrading to version 2");
591
592 blob->setEncrypted(true);
593 version = 2;
594 updated = true;
Kenny Roota91203b2012-02-15 15:00:46 -0800595 }
Kenny Root07438c82012-11-02 15:41:02 -0700596
597 /*
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700598 * If we've updated, set the key blob to the right version
599 * and write it.
Kenny Root07438c82012-11-02 15:41:02 -0700600 */
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700601 if (updated) {
602 ALOGV("updated and writing file %s", filename);
603 blob->setVersion(version);
604 }
Kenny Root70e3a862012-02-15 17:20:23 -0800605
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700606 return updated;
607}
608
609struct BIO_Delete {
610 void operator()(BIO* p) const { BIO_free(p); }
611};
Janis Danisevskisccfff102017-05-01 11:02:51 -0700612typedef std::unique_ptr<BIO, BIO_Delete> Unique_BIO;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700613
614ResponseCode KeyStore::importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
615 // We won't even write to the blob directly with this BIO, so const_cast is okay.
616 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
617 if (b.get() == NULL) {
618 ALOGE("Problem instantiating BIO");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100619 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700620 }
621
622 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
623 if (pkey.get() == NULL) {
624 ALOGE("Couldn't read old PEM file");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100625 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700626 }
627
628 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
629 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
630 if (len < 0) {
631 ALOGE("Couldn't measure PKCS#8 length");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100632 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700633 }
634
Janis Danisevskisccfff102017-05-01 11:02:51 -0700635 std::unique_ptr<unsigned char[]> pkcs8key(new unsigned char[len]);
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700636 uint8_t* tmp = pkcs8key.get();
637 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
638 ALOGE("Couldn't convert to PKCS#8");
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100639 return ResponseCode::SYSTEM_ERROR;
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700640 }
641
642 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
643 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Janis Danisevskisc7a9fa22016-10-13 18:43:45 +0100644 if (rc != ResponseCode::NO_ERROR) {
Shawn Willdenc1d1fee2016-01-26 22:44:56 -0700645 return rc;
646 }
647
648 return get(filename, blob, TYPE_KEY_PAIR, uid);
649}
650
651void KeyStore::readMetaData() {
652 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
653 if (in < 0) {
654 return;
655 }
656 size_t fileLength = readFully(in, (uint8_t*)&mMetaData, sizeof(mMetaData));
657 if (fileLength != sizeof(mMetaData)) {
658 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength, sizeof(mMetaData));
659 }
660 close(in);
661}
662
663void KeyStore::writeMetaData() {
664 const char* tmpFileName = ".metadata.tmp";
665 int out =
666 TEMP_FAILURE_RETRY(open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
667 if (out < 0) {
668 ALOGE("couldn't write metadata file: %s", strerror(errno));
669 return;
670 }
671 size_t fileLength = writeFully(out, (uint8_t*)&mMetaData, sizeof(mMetaData));
672 if (fileLength != sizeof(mMetaData)) {
673 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
674 sizeof(mMetaData));
675 }
676 close(out);
677 rename(tmpFileName, sMetaDataFile);
678}
679
680bool KeyStore::upgradeKeystore() {
681 bool upgraded = false;
682
683 if (mMetaData.version == 0) {
684 UserState* userState = getUserStateByUid(0);
685
686 // Initialize first so the directory is made.
687 userState->initialize();
688
689 // Migrate the old .masterkey file to user 0.
690 if (access(sOldMasterKey, R_OK) == 0) {
691 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
692 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
693 return false;
694 }
695 }
696
697 // Initialize again in case we had a key.
698 userState->initialize();
699
700 // Try to migrate existing keys.
701 DIR* dir = opendir(".");
702 if (!dir) {
703 // Give up now; maybe we can upgrade later.
704 ALOGE("couldn't open keystore's directory; something is wrong");
705 return false;
706 }
707
708 struct dirent* file;
709 while ((file = readdir(dir)) != NULL) {
710 // We only care about files.
711 if (file->d_type != DT_REG) {
712 continue;
713 }
714
715 // Skip anything that starts with a "."
716 if (file->d_name[0] == '.') {
717 continue;
718 }
719
720 // Find the current file's user.
721 char* end;
722 unsigned long thisUid = strtoul(file->d_name, &end, 10);
723 if (end[0] != '_' || end[1] == 0) {
724 continue;
725 }
726 UserState* otherUser = getUserStateByUid(thisUid);
727 if (otherUser->getUserId() != 0) {
728 unlinkat(dirfd(dir), file->d_name, 0);
729 }
730
731 // Rename the file into user directory.
732 DIR* otherdir = opendir(otherUser->getUserDirName());
733 if (otherdir == NULL) {
734 ALOGW("couldn't open user directory for rename");
735 continue;
736 }
737 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
738 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
739 }
740 closedir(otherdir);
741 }
742 closedir(dir);
743
744 mMetaData.version = 1;
745 upgraded = true;
746 }
747
748 return upgraded;
Kenny Roota91203b2012-02-15 15:00:46 -0800749}