blob: 23711e728cc53b0576aefb05006461b9024427b5 [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
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
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
23#include <unistd.h>
24#include <signal.h>
25#include <errno.h>
26#include <dirent.h>
27#include <fcntl.h>
28#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070029#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080030#include <sys/types.h>
31#include <sys/socket.h>
32#include <sys/stat.h>
33#include <sys/time.h>
34#include <arpa/inet.h>
35
36#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070037#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080038#include <openssl/evp.h>
39#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070040#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080041
Kenny Root70e3a862012-02-15 17:20:23 -080042#include <hardware/keymaster.h>
43
Kenny Root822c3a92012-03-23 16:34:39 -070044#include <utils/UniquePtr.h>
45
Kenny Root70e3a862012-02-15 17:20:23 -080046#include <cutils/list.h>
47
Kenny Root07438c82012-11-02 15:41:02 -070048#include <keystore/IKeystoreService.h>
49#include <binder/IPCThreadState.h>
50#include <binder/IServiceManager.h>
51
Kenny Roota91203b2012-02-15 15:00:46 -080052#include <cutils/log.h>
53#include <cutils/sockets.h>
54#include <private/android_filesystem_config.h>
55
Kenny Root07438c82012-11-02 15:41:02 -070056#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080057
58/* KeyStore is a secured storage for key-value pairs. In this implementation,
59 * each file stores one key-value pair. Keys are encoded in file names, and
60 * values are encrypted with checksums. The encryption key is protected by a
61 * user-defined password. To keep things simple, buffers are always larger than
62 * the maximum space we needed, so boundary checks on buffers are omitted. */
63
64#define KEY_SIZE ((NAME_MAX - 15) / 2)
65#define VALUE_SIZE 32768
66#define PASSWORD_SIZE VALUE_SIZE
67
Kenny Root822c3a92012-03-23 16:34:39 -070068
69struct BIO_Delete {
70 void operator()(BIO* p) const {
71 BIO_free(p);
72 }
73};
74typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
75
76struct EVP_PKEY_Delete {
77 void operator()(EVP_PKEY* p) const {
78 EVP_PKEY_free(p);
79 }
80};
81typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
82
83struct PKCS8_PRIV_KEY_INFO_Delete {
84 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
85 PKCS8_PRIV_KEY_INFO_free(p);
86 }
87};
88typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
89
90
Kenny Roota91203b2012-02-15 15:00:46 -080091struct Value {
Kenny Root822c3a92012-03-23 16:34:39 -070092 Value(const uint8_t* orig, int origLen) {
93 assert(origLen <= VALUE_SIZE);
94 memcpy(value, orig, origLen);
95 length = origLen;
96 }
97
98 Value() {
99 }
100
Kenny Roota91203b2012-02-15 15:00:46 -0800101 int length;
102 uint8_t value[VALUE_SIZE];
103};
104
Kenny Root70e3a862012-02-15 17:20:23 -0800105class ValueString {
106public:
107 ValueString(const Value* orig) {
Kenny Root822c3a92012-03-23 16:34:39 -0700108 assert(length <= VALUE_SIZE);
Kenny Root70e3a862012-02-15 17:20:23 -0800109 length = orig->length;
110 value = new char[length + 1];
111 memcpy(value, orig->value, length);
112 value[length] = '\0';
113 }
114
115 ~ValueString() {
116 delete[] value;
117 }
118
119 const char* c_str() const {
120 return value;
121 }
122
123 char* release() {
124 char* ret = value;
125 value = NULL;
126 return ret;
127 }
128
129private:
130 char* value;
131 size_t length;
132};
133
134static int keymaster_device_initialize(keymaster_device_t** dev) {
135 int rc;
136
137 const hw_module_t* mod;
138 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
139 if (rc) {
140 ALOGE("could not find any keystore module");
141 goto out;
142 }
143
144 rc = keymaster_open(mod, dev);
145 if (rc) {
146 ALOGE("could not open keymaster device in %s (%s)",
147 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
148 goto out;
149 }
150
151 return 0;
152
153out:
154 *dev = NULL;
155 return rc;
156}
157
158static void keymaster_device_release(keymaster_device_t* dev) {
159 keymaster_close(dev);
160}
161
Kenny Root07438c82012-11-02 15:41:02 -0700162/***************
163 * PERMISSIONS *
164 ***************/
165
166/* Here are the permissions, actions, users, and the main function. */
167typedef enum {
168 P_TEST = 1 << 0,
169 P_GET = 1 << 1,
170 P_INSERT = 1 << 2,
171 P_DELETE = 1 << 3,
172 P_EXIST = 1 << 4,
173 P_SAW = 1 << 5,
174 P_RESET = 1 << 6,
175 P_PASSWORD = 1 << 7,
176 P_LOCK = 1 << 8,
177 P_UNLOCK = 1 << 9,
178 P_ZERO = 1 << 10,
179 P_SIGN = 1 << 11,
180 P_VERIFY = 1 << 12,
181 P_GRANT = 1 << 13,
182} perm_t;
183
184static struct user_euid {
185 uid_t uid;
186 uid_t euid;
187} user_euids[] = {
188 {AID_VPN, AID_SYSTEM},
189 {AID_WIFI, AID_SYSTEM},
190 {AID_ROOT, AID_SYSTEM},
191};
192
193static struct user_perm {
194 uid_t uid;
195 perm_t perms;
196} user_perms[] = {
197 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
198 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
199 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
200 {AID_ROOT, static_cast<perm_t>(P_GET) },
201};
202
203static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
204 | P_VERIFY);
205
206static bool has_permission(uid_t uid, perm_t perm) {
207 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
208 struct user_perm user = user_perms[i];
209 if (user.uid == uid) {
210 return user.perms & perm;
211 }
212 }
213
214 return DEFAULT_PERMS & perm;
215}
216
217static uid_t get_keystore_euid(uid_t uid) {
218 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
219 struct user_euid user = user_euids[i];
220 if (user.uid == uid) {
221 return user.euid;
222 }
223 }
224
225 return uid;
226}
227
Kenny Roota91203b2012-02-15 15:00:46 -0800228/* Here is the encoding of keys. This is necessary in order to allow arbitrary
229 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
230 * into two bytes. The first byte is one of [+-.] which represents the first
231 * two bits of the character. The second byte encodes the rest of the bits into
232 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
233 * that Base64 cannot be used here due to the need of prefix match on keys. */
234
Kenny Root07438c82012-11-02 15:41:02 -0700235static int encode_key(char* out, const android::String8& keyName) {
236 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
237 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800238 for (int i = length; i > 0; --i, ++in, ++out) {
239 if (*in >= '0' && *in <= '~') {
240 *out = *in;
241 } else {
242 *out = '+' + (*in >> 6);
243 *++out = '0' + (*in & 0x3F);
244 ++length;
245 }
246 }
247 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800248 return length;
249}
250
Kenny Root07438c82012-11-02 15:41:02 -0700251static int encode_key_for_uid(char* out, uid_t uid, const android::String8& keyName) {
Kenny Root70e3a862012-02-15 17:20:23 -0800252 int n = snprintf(out, NAME_MAX, "%u_", uid);
253 out += n;
254
Kenny Root07438c82012-11-02 15:41:02 -0700255 return n + encode_key(out, keyName);
Kenny Roota91203b2012-02-15 15:00:46 -0800256}
257
Kenny Root07438c82012-11-02 15:41:02 -0700258/*
259 * Converts from the "escaped" format on disk to actual name.
260 * This will be smaller than the input string.
261 *
262 * Characters that should combine with the next at the end will be truncated.
263 */
264static size_t decode_key_length(const char* in, size_t length) {
265 size_t outLength = 0;
266
267 for (const char* end = in + length; in < end; in++) {
268 /* This combines with the next character. */
269 if (*in < '0' || *in > '~') {
270 continue;
271 }
272
273 outLength++;
274 }
275 return outLength;
276}
277
278static void decode_key(char* out, const char* in, size_t length) {
279 for (const char* end = in + length; in < end; in++) {
280 if (*in < '0' || *in > '~') {
281 /* Truncate combining characters at the end. */
282 if (in + 1 >= end) {
283 break;
284 }
285
286 *out = (*in++ - '+') << 6;
287 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800288 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700289 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800290 }
291 }
292 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800293}
294
295static size_t readFully(int fd, uint8_t* data, size_t size) {
296 size_t remaining = size;
297 while (remaining > 0) {
298 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, size));
299 if (n == -1 || n == 0) {
300 return size-remaining;
301 }
302 data += n;
303 remaining -= n;
304 }
305 return size;
306}
307
308static size_t writeFully(int fd, uint8_t* data, size_t size) {
309 size_t remaining = size;
310 while (remaining > 0) {
311 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, size));
312 if (n == -1 || n == 0) {
313 return size-remaining;
314 }
315 data += n;
316 remaining -= n;
317 }
318 return size;
319}
320
321class Entropy {
322public:
323 Entropy() : mRandom(-1) {}
324 ~Entropy() {
325 if (mRandom != -1) {
326 close(mRandom);
327 }
328 }
329
330 bool open() {
331 const char* randomDevice = "/dev/urandom";
332 mRandom = ::open(randomDevice, O_RDONLY);
333 if (mRandom == -1) {
334 ALOGE("open: %s: %s", randomDevice, strerror(errno));
335 return false;
336 }
337 return true;
338 }
339
Kenny Root51878182012-03-13 12:53:19 -0700340 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800341 return (readFully(mRandom, data, size) == size);
342 }
343
344private:
345 int mRandom;
346};
347
348/* Here is the file format. There are two parts in blob.value, the secret and
349 * the description. The secret is stored in ciphertext, and its original size
350 * can be found in blob.length. The description is stored after the secret in
351 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700352 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
353 * the second is the blob's type, and the third byte is reserved. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800354 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
355 * and decryptBlob(). Thus they should not be accessed from outside. */
356
Kenny Root822c3a92012-03-23 16:34:39 -0700357/* ** Note to future implementors of encryption: **
358 * Currently this is the construction:
359 * metadata || Enc(MD5(data) || data)
360 *
361 * This should be the construction used for encrypting if re-implementing:
362 *
363 * Derive independent keys for encryption and MAC:
364 * Kenc = AES_encrypt(masterKey, "Encrypt")
365 * Kmac = AES_encrypt(masterKey, "MAC")
366 *
367 * Store this:
368 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
369 * HMAC(Kmac, metadata || Enc(data))
370 */
Kenny Roota91203b2012-02-15 15:00:46 -0800371struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700372 uint8_t version;
373 uint8_t type;
374 uint8_t reserved;
Kenny Roota91203b2012-02-15 15:00:46 -0800375 uint8_t info;
376 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700377 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800378 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700379 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800380 int32_t length; // in network byte order when encrypted
381 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
382};
383
Kenny Root822c3a92012-03-23 16:34:39 -0700384typedef enum {
385 TYPE_GENERIC = 1,
386 TYPE_MASTER_KEY = 2,
387 TYPE_KEY_PAIR = 3,
388} BlobType;
389
Kenny Root07438c82012-11-02 15:41:02 -0700390static const uint8_t CURRENT_BLOB_VERSION = 1;
Kenny Root822c3a92012-03-23 16:34:39 -0700391
Kenny Roota91203b2012-02-15 15:00:46 -0800392class Blob {
393public:
Kenny Root07438c82012-11-02 15:41:02 -0700394 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
395 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800396 mBlob.length = valueLength;
397 memcpy(mBlob.value, value, valueLength);
398
399 mBlob.info = infoLength;
400 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700401
Kenny Root07438c82012-11-02 15:41:02 -0700402 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700403 mBlob.type = uint8_t(type);
Kenny Roota91203b2012-02-15 15:00:46 -0800404 }
405
406 Blob(blob b) {
407 mBlob = b;
408 }
409
410 Blob() {}
411
Kenny Root51878182012-03-13 12:53:19 -0700412 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800413 return mBlob.value;
414 }
415
Kenny Root51878182012-03-13 12:53:19 -0700416 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800417 return mBlob.length;
418 }
419
Kenny Root51878182012-03-13 12:53:19 -0700420 const uint8_t* getInfo() const {
421 return mBlob.value + mBlob.length;
422 }
423
424 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800425 return mBlob.info;
426 }
427
Kenny Root822c3a92012-03-23 16:34:39 -0700428 uint8_t getVersion() const {
429 return mBlob.version;
430 }
431
432 void setVersion(uint8_t version) {
433 mBlob.version = version;
434 }
435
436 BlobType getType() const {
437 return BlobType(mBlob.type);
438 }
439
440 void setType(BlobType type) {
441 mBlob.type = uint8_t(type);
442 }
443
Kenny Roota91203b2012-02-15 15:00:46 -0800444 ResponseCode encryptBlob(const char* filename, AES_KEY *aes_key, Entropy* entropy) {
445 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
446 return SYSTEM_ERROR;
447 }
448
449 // data includes the value and the value's length
450 size_t dataLength = mBlob.length + sizeof(mBlob.length);
451 // pad data to the AES_BLOCK_SIZE
452 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
453 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
454 // encrypted data includes the digest value
455 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
456 // move info after space for padding
457 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
458 // zero padding area
459 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
460
461 mBlob.length = htonl(mBlob.length);
462 MD5(mBlob.digested, digestedLength, mBlob.digest);
463
464 uint8_t vector[AES_BLOCK_SIZE];
465 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
466 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
467 aes_key, vector, AES_ENCRYPT);
468
Kenny Root822c3a92012-03-23 16:34:39 -0700469 mBlob.reserved = 0;
Kenny Roota91203b2012-02-15 15:00:46 -0800470 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
471 size_t fileLength = encryptedLength + headerLength + mBlob.info;
472
473 const char* tmpFileName = ".tmp";
474 int out = open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
475 if (out == -1) {
476 return SYSTEM_ERROR;
477 }
478 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
479 if (close(out) != 0) {
480 return SYSTEM_ERROR;
481 }
482 if (writtenBytes != fileLength) {
483 unlink(tmpFileName);
484 return SYSTEM_ERROR;
485 }
Kenny Root07438c82012-11-02 15:41:02 -0700486 return (rename(tmpFileName, filename) == 0) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800487 }
488
489 ResponseCode decryptBlob(const char* filename, AES_KEY *aes_key) {
490 int in = open(filename, O_RDONLY);
491 if (in == -1) {
492 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
493 }
494 // fileLength may be less than sizeof(mBlob) since the in
495 // memory version has extra padding to tolerate rounding up to
496 // the AES_BLOCK_SIZE
497 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
498 if (close(in) != 0) {
499 return SYSTEM_ERROR;
500 }
501 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
502 if (fileLength < headerLength) {
503 return VALUE_CORRUPTED;
504 }
505
506 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
507 if (encryptedLength < 0 || encryptedLength % AES_BLOCK_SIZE != 0) {
508 return VALUE_CORRUPTED;
509 }
510 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
511 mBlob.vector, AES_DECRYPT);
512 size_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
513 uint8_t computedDigest[MD5_DIGEST_LENGTH];
514 MD5(mBlob.digested, digestedLength, computedDigest);
515 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
516 return VALUE_CORRUPTED;
517 }
518
519 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
520 mBlob.length = ntohl(mBlob.length);
521 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
522 return VALUE_CORRUPTED;
523 }
524 if (mBlob.info != 0) {
525 // move info from after padding to after data
526 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
527 }
Kenny Root07438c82012-11-02 15:41:02 -0700528 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800529 }
530
531private:
532 struct blob mBlob;
533};
534
Kenny Root70e3a862012-02-15 17:20:23 -0800535typedef struct {
536 uint32_t uid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700537 const uint8_t* filename;
Kenny Root70e3a862012-02-15 17:20:23 -0800538
539 struct listnode plist;
540} grant_t;
541
Kenny Roota91203b2012-02-15 15:00:46 -0800542class KeyStore {
543public:
Kenny Root70e3a862012-02-15 17:20:23 -0800544 KeyStore(Entropy* entropy, keymaster_device_t* device)
Kenny Root51878182012-03-13 12:53:19 -0700545 : mEntropy(entropy)
Kenny Root70e3a862012-02-15 17:20:23 -0800546 , mDevice(device)
Kenny Root51878182012-03-13 12:53:19 -0700547 , mRetry(MAX_RETRY)
548 {
Kenny Roota91203b2012-02-15 15:00:46 -0800549 if (access(MASTER_KEY_FILE, R_OK) == 0) {
550 setState(STATE_LOCKED);
551 } else {
552 setState(STATE_UNINITIALIZED);
553 }
Kenny Root70e3a862012-02-15 17:20:23 -0800554
555 list_init(&mGrants);
Kenny Roota91203b2012-02-15 15:00:46 -0800556 }
557
Kenny Root51878182012-03-13 12:53:19 -0700558 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800559 return mState;
560 }
561
Kenny Root51878182012-03-13 12:53:19 -0700562 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800563 return mRetry;
564 }
565
Kenny Root70e3a862012-02-15 17:20:23 -0800566 keymaster_device_t* getDevice() const {
567 return mDevice;
568 }
569
Kenny Root07438c82012-11-02 15:41:02 -0700570 ResponseCode initialize(const android::String8& pw) {
Kenny Roota91203b2012-02-15 15:00:46 -0800571 if (!generateMasterKey()) {
572 return SYSTEM_ERROR;
573 }
574 ResponseCode response = writeMasterKey(pw);
575 if (response != NO_ERROR) {
576 return response;
577 }
578 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700579 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800580 }
581
Kenny Root07438c82012-11-02 15:41:02 -0700582 ResponseCode writeMasterKey(const android::String8& pw) {
Kenny Roota91203b2012-02-15 15:00:46 -0800583 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
584 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
585 AES_KEY passwordAesKey;
586 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700587 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Roota91203b2012-02-15 15:00:46 -0800588 return masterKeyBlob.encryptBlob(MASTER_KEY_FILE, &passwordAesKey, mEntropy);
589 }
590
Kenny Root07438c82012-11-02 15:41:02 -0700591 ResponseCode readMasterKey(const android::String8& pw) {
Kenny Roota91203b2012-02-15 15:00:46 -0800592 int in = open(MASTER_KEY_FILE, O_RDONLY);
593 if (in == -1) {
594 return SYSTEM_ERROR;
595 }
596
597 // we read the raw blob to just to get the salt to generate
598 // the AES key, then we create the Blob to use with decryptBlob
599 blob rawBlob;
600 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
601 if (close(in) != 0) {
602 return SYSTEM_ERROR;
603 }
604 // find salt at EOF if present, otherwise we have an old file
605 uint8_t* salt;
606 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
607 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
608 } else {
609 salt = NULL;
610 }
611 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
612 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
613 AES_KEY passwordAesKey;
614 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
615 Blob masterKeyBlob(rawBlob);
616 ResponseCode response = masterKeyBlob.decryptBlob(MASTER_KEY_FILE, &passwordAesKey);
617 if (response == SYSTEM_ERROR) {
618 return SYSTEM_ERROR;
619 }
620 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
621 // if salt was missing, generate one and write a new master key file with the salt.
622 if (salt == NULL) {
623 if (!generateSalt()) {
624 return SYSTEM_ERROR;
625 }
626 response = writeMasterKey(pw);
627 }
628 if (response == NO_ERROR) {
629 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
630 setupMasterKeys();
631 }
632 return response;
633 }
634 if (mRetry <= 0) {
635 reset();
636 return UNINITIALIZED;
637 }
638 --mRetry;
639 switch (mRetry) {
640 case 0: return WRONG_PASSWORD_0;
641 case 1: return WRONG_PASSWORD_1;
642 case 2: return WRONG_PASSWORD_2;
643 case 3: return WRONG_PASSWORD_3;
644 default: return WRONG_PASSWORD_3;
645 }
646 }
647
648 bool reset() {
649 clearMasterKeys();
650 setState(STATE_UNINITIALIZED);
651
652 DIR* dir = opendir(".");
653 struct dirent* file;
654
655 if (!dir) {
656 return false;
657 }
658 while ((file = readdir(dir)) != NULL) {
659 unlink(file->d_name);
660 }
661 closedir(dir);
662 return true;
663 }
664
Kenny Root51878182012-03-13 12:53:19 -0700665 bool isEmpty() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800666 DIR* dir = opendir(".");
667 struct dirent* file;
668 if (!dir) {
669 return true;
670 }
671 bool result = true;
672 while ((file = readdir(dir)) != NULL) {
673 if (isKeyFile(file->d_name)) {
674 result = false;
675 break;
676 }
677 }
678 closedir(dir);
679 return result;
680 }
681
682 void lock() {
683 clearMasterKeys();
684 setState(STATE_LOCKED);
685 }
686
Kenny Root822c3a92012-03-23 16:34:39 -0700687 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type) {
688 ResponseCode rc = keyBlob->decryptBlob(filename, &mMasterKeyDecryption);
689 if (rc != NO_ERROR) {
690 return rc;
691 }
692
693 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -0700694 if (version < CURRENT_BLOB_VERSION) {
Kenny Root822c3a92012-03-23 16:34:39 -0700695 upgrade(filename, keyBlob, version, type);
696 }
697
698 if (keyBlob->getType() != type) {
699 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
700 return KEY_NOT_FOUND;
701 }
702
703 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -0800704 }
705
706 ResponseCode put(const char* filename, Blob* keyBlob) {
707 return keyBlob->encryptBlob(filename, &mMasterKeyEncryption, mEntropy);
708 }
709
Kenny Root07438c82012-11-02 15:41:02 -0700710 void addGrant(const char* filename, uid_t granteeUid) {
711 grant_t *grant = getGrant(filename, granteeUid);
Kenny Root70e3a862012-02-15 17:20:23 -0800712 if (grant == NULL) {
713 grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -0700714 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700715 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root70e3a862012-02-15 17:20:23 -0800716 list_add_tail(&mGrants, &grant->plist);
717 }
718 }
719
Kenny Root07438c82012-11-02 15:41:02 -0700720 bool removeGrant(const char* filename, uid_t granteeUid) {
721 grant_t *grant = getGrant(filename, granteeUid);
Kenny Root70e3a862012-02-15 17:20:23 -0800722 if (grant != NULL) {
723 list_remove(&grant->plist);
724 delete grant;
725 return true;
726 }
727
728 return false;
729 }
730
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700731 bool hasGrant(const char* filename, const uid_t uid) const {
732 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -0800733 }
734
Kenny Root07438c82012-11-02 15:41:02 -0700735 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename) {
Kenny Root822c3a92012-03-23 16:34:39 -0700736 uint8_t* data;
737 size_t dataLength;
738 int rc;
739
740 if (mDevice->import_keypair == NULL) {
741 ALOGE("Keymaster doesn't support import!");
742 return SYSTEM_ERROR;
743 }
744
Kenny Root07438c82012-11-02 15:41:02 -0700745 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700746 if (rc) {
747 ALOGE("Error while importing keypair: %d", rc);
748 return SYSTEM_ERROR;
749 }
750
751 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
752 free(data);
753
754 return put(filename, &keyBlob);
755 }
756
Kenny Roota91203b2012-02-15 15:00:46 -0800757private:
758 static const char* MASTER_KEY_FILE;
759 static const int MASTER_KEY_SIZE_BYTES = 16;
760 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
761
762 static const int MAX_RETRY = 4;
763 static const size_t SALT_SIZE = 16;
764
765 Entropy* mEntropy;
766
Kenny Root70e3a862012-02-15 17:20:23 -0800767 keymaster_device_t* mDevice;
768
Kenny Roota91203b2012-02-15 15:00:46 -0800769 State mState;
770 int8_t mRetry;
771
772 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
773 uint8_t mSalt[SALT_SIZE];
774
775 AES_KEY mMasterKeyEncryption;
776 AES_KEY mMasterKeyDecryption;
777
Kenny Root70e3a862012-02-15 17:20:23 -0800778 struct listnode mGrants;
779
Kenny Roota91203b2012-02-15 15:00:46 -0800780 void setState(State state) {
781 mState = state;
782 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
783 mRetry = MAX_RETRY;
784 }
785 }
786
787 bool generateSalt() {
788 return mEntropy->generate_random_data(mSalt, sizeof(mSalt));
789 }
790
791 bool generateMasterKey() {
792 if (!mEntropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
793 return false;
794 }
795 if (!generateSalt()) {
796 return false;
797 }
798 return true;
799 }
800
801 void setupMasterKeys() {
802 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
803 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
804 setState(STATE_NO_ERROR);
805 }
806
807 void clearMasterKeys() {
808 memset(mMasterKey, 0, sizeof(mMasterKey));
809 memset(mSalt, 0, sizeof(mSalt));
810 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
811 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
812 }
813
Kenny Root07438c82012-11-02 15:41:02 -0700814 static void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
815 uint8_t* salt) {
Kenny Roota91203b2012-02-15 15:00:46 -0800816 size_t saltSize;
817 if (salt != NULL) {
818 saltSize = SALT_SIZE;
819 } else {
820 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
821 salt = (uint8_t*) "keystore";
822 // sizeof = 9, not strlen = 8
823 saltSize = sizeof("keystore");
824 }
Kenny Root07438c82012-11-02 15:41:02 -0700825
826 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
827 saltSize, 8192, keySize, key);
Kenny Roota91203b2012-02-15 15:00:46 -0800828 }
829
830 static bool isKeyFile(const char* filename) {
831 return ((strcmp(filename, MASTER_KEY_FILE) != 0)
832 && (strcmp(filename, ".") != 0)
833 && (strcmp(filename, "..") != 0));
834 }
Kenny Root70e3a862012-02-15 17:20:23 -0800835
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700836 grant_t* getGrant(const char* filename, uid_t uid) const {
Kenny Root70e3a862012-02-15 17:20:23 -0800837 struct listnode *node;
838 grant_t *grant;
839
840 list_for_each(node, &mGrants) {
841 grant = node_to_item(node, grant_t, plist);
842 if (grant->uid == uid
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700843 && !strcmp(reinterpret_cast<const char*>(grant->filename),
844 filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -0800845 return grant;
846 }
847 }
848
849 return NULL;
850 }
851
852 bool convertToUid(const Value* uidValue, uid_t* uid) const {
853 ValueString uidString(uidValue);
854 char* end = NULL;
855 *uid = strtol(uidString.c_str(), &end, 10);
856 return *end == '\0';
857 }
Kenny Root822c3a92012-03-23 16:34:39 -0700858
859 /**
860 * Upgrade code. This will upgrade the key from the current version
861 * to whatever is newest.
862 */
863 void upgrade(const char* filename, Blob* blob, const uint8_t oldVersion, const BlobType type) {
864 bool updated = false;
865 uint8_t version = oldVersion;
866
867 /* From V0 -> V1: All old types were unknown */
868 if (version == 0) {
869 ALOGV("upgrading to version 1 and setting type %d", type);
870
871 blob->setType(type);
872 if (type == TYPE_KEY_PAIR) {
873 importBlobAsKey(blob, filename);
874 }
875 version = 1;
876 updated = true;
877 }
878
879 /*
880 * If we've updated, set the key blob to the right version
881 * and write it.
882 * */
883 if (updated) {
884 ALOGV("updated and writing file %s", filename);
885 blob->setVersion(version);
886 this->put(filename, blob);
887 }
888 }
889
890 /**
891 * Takes a blob that is an PEM-encoded RSA key as a byte array and
892 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
893 * Then it overwrites the original blob with the new blob
894 * format that is returned from the keymaster.
895 */
896 ResponseCode importBlobAsKey(Blob* blob, const char* filename) {
897 // We won't even write to the blob directly with this BIO, so const_cast is okay.
898 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
899 if (b.get() == NULL) {
900 ALOGE("Problem instantiating BIO");
901 return SYSTEM_ERROR;
902 }
903
904 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
905 if (pkey.get() == NULL) {
906 ALOGE("Couldn't read old PEM file");
907 return SYSTEM_ERROR;
908 }
909
910 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
911 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
912 if (len < 0) {
913 ALOGE("Couldn't measure PKCS#8 length");
914 return SYSTEM_ERROR;
915 }
916
917 Value pkcs8key;
918 pkcs8key.length = len;
919 uint8_t* tmp = pkcs8key.value;
920 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
921 ALOGE("Couldn't convert to PKCS#8");
922 return SYSTEM_ERROR;
923 }
924
Kenny Root07438c82012-11-02 15:41:02 -0700925 ResponseCode rc = importKey(pkcs8key.value, pkcs8key.length, filename);
Kenny Root822c3a92012-03-23 16:34:39 -0700926 if (rc != NO_ERROR) {
927 return rc;
928 }
929
930 return get(filename, blob, TYPE_KEY_PAIR);
931 }
Kenny Roota91203b2012-02-15 15:00:46 -0800932};
933
934const char* KeyStore::MASTER_KEY_FILE = ".masterkey";
935
Kenny Root07438c82012-11-02 15:41:02 -0700936static ResponseCode get_key_for_name(KeyStore* keyStore, Blob* keyBlob,
937 const android::String8& keyName, const uid_t uid, const BlobType type) {
Kenny Root70e3a862012-02-15 17:20:23 -0800938 char filename[NAME_MAX];
939
940 encode_key_for_uid(filename, uid, keyName);
Kenny Root822c3a92012-03-23 16:34:39 -0700941 ResponseCode responseCode = keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800942 if (responseCode == NO_ERROR) {
943 return responseCode;
944 }
945
946 // If this is the Wifi or VPN user, they actually want system
947 // UID keys.
948 if (uid == AID_WIFI || uid == AID_VPN) {
949 encode_key_for_uid(filename, AID_SYSTEM, keyName);
Kenny Root822c3a92012-03-23 16:34:39 -0700950 responseCode = keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800951 if (responseCode == NO_ERROR) {
952 return responseCode;
953 }
954 }
955
956 // They might be using a granted key.
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700957 encode_key(filename, keyName);
958 if (!keyStore->hasGrant(filename, uid)) {
Kenny Root70e3a862012-02-15 17:20:23 -0800959 return responseCode;
960 }
961
962 // It is a granted key. Try to load it.
Kenny Root822c3a92012-03-23 16:34:39 -0700963 return keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800964}
965
Kenny Root07438c82012-11-02 15:41:02 -0700966namespace android {
967class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
968public:
969 KeyStoreProxy(KeyStore* keyStore)
970 : mKeyStore(keyStore)
971 {
Kenny Roota91203b2012-02-15 15:00:46 -0800972 }
Kenny Roota91203b2012-02-15 15:00:46 -0800973
Kenny Root07438c82012-11-02 15:41:02 -0700974 void binderDied(const wp<IBinder>&) {
975 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -0700976 }
Kenny Roota91203b2012-02-15 15:00:46 -0800977
Kenny Root07438c82012-11-02 15:41:02 -0700978 int32_t test() {
979 uid_t uid = IPCThreadState::self()->getCallingUid();
980 if (!has_permission(uid, P_TEST)) {
981 ALOGW("permission denied for %d: test", uid);
982 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -0800983 }
Kenny Roota91203b2012-02-15 15:00:46 -0800984
Kenny Root07438c82012-11-02 15:41:02 -0700985 return mKeyStore->getState();
Kenny Root298e7b12012-03-26 13:54:44 -0700986 }
987
Kenny Root07438c82012-11-02 15:41:02 -0700988 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
989 uid_t uid = IPCThreadState::self()->getCallingUid();
990 if (!has_permission(uid, P_GET)) {
991 ALOGW("permission denied for %d: get", uid);
992 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -0800993 }
Kenny Root07438c82012-11-02 15:41:02 -0700994 uid = get_keystore_euid(uid);
995
996 State state = checkState();
997 if (state != STATE_NO_ERROR) {
998 ALOGD("calling get in state: %d", state);
999 return state;
Kenny Roota91203b2012-02-15 15:00:46 -08001000 }
Kenny Root07438c82012-11-02 15:41:02 -07001001
1002 String8 name8(name);
1003 char filename[NAME_MAX];
1004
1005 encode_key_for_uid(filename, uid, name8);
1006
1007 Blob keyBlob;
1008 ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, TYPE_GENERIC);
1009 if (responseCode != ::NO_ERROR) {
1010 *item = NULL;
1011 *itemLength = 0;
1012 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001013 }
Kenny Roota91203b2012-02-15 15:00:46 -08001014
Kenny Root07438c82012-11-02 15:41:02 -07001015 *item = (uint8_t*) malloc(keyBlob.getLength());
1016 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1017 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001018
Kenny Root07438c82012-11-02 15:41:02 -07001019 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001020 }
1021
Kenny Root07438c82012-11-02 15:41:02 -07001022 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength) {
1023 uid_t uid = IPCThreadState::self()->getCallingUid();
1024 if (!has_permission(uid, P_INSERT)) {
1025 ALOGW("permission denied for %d: insert", uid);
1026 return ::PERMISSION_DENIED;
1027 }
1028 uid = get_keystore_euid(uid);
1029
1030 State state = checkState();
1031 if (state != STATE_NO_ERROR) {
1032 ALOGD("calling insert in state: %d", state);
1033 return state;
1034 }
1035
1036 String8 name8(name);
1037 char filename[NAME_MAX];
1038
1039 encode_key_for_uid(filename, uid, name8);
1040
1041 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
1042 return mKeyStore->put(filename, &keyBlob);
Kenny Root70e3a862012-02-15 17:20:23 -08001043 }
1044
Kenny Root07438c82012-11-02 15:41:02 -07001045 int32_t del(const String16& name) {
1046 uid_t uid = IPCThreadState::self()->getCallingUid();
1047 if (!has_permission(uid, P_DELETE)) {
1048 ALOGW("permission denied for %d: del", uid);
1049 return ::PERMISSION_DENIED;
1050 }
1051 uid = get_keystore_euid(uid);
Kenny Root70e3a862012-02-15 17:20:23 -08001052
Kenny Root07438c82012-11-02 15:41:02 -07001053 String8 name8(name);
1054 char filename[NAME_MAX];
1055
1056 encode_key_for_uid(filename, uid, name8);
1057
1058 Blob keyBlob;
1059 ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, TYPE_GENERIC);
1060 if (responseCode != ::NO_ERROR) {
1061 return responseCode;
1062 }
1063 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001064 }
1065
Kenny Root07438c82012-11-02 15:41:02 -07001066 int32_t exist(const String16& name) {
1067 uid_t uid = IPCThreadState::self()->getCallingUid();
1068 if (!has_permission(uid, P_EXIST)) {
1069 ALOGW("permission denied for %d: exist", uid);
1070 return ::PERMISSION_DENIED;
1071 }
1072 uid = get_keystore_euid(uid);
Kenny Root70e3a862012-02-15 17:20:23 -08001073
Kenny Root07438c82012-11-02 15:41:02 -07001074 String8 name8(name);
1075 char filename[NAME_MAX];
Kenny Root70e3a862012-02-15 17:20:23 -08001076
Kenny Root07438c82012-11-02 15:41:02 -07001077 encode_key_for_uid(filename, uid, name8);
Kenny Root70e3a862012-02-15 17:20:23 -08001078
Kenny Root07438c82012-11-02 15:41:02 -07001079 if (access(filename, R_OK) == -1) {
1080 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1081 }
1082 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001083 }
1084
Kenny Root07438c82012-11-02 15:41:02 -07001085 int32_t saw(const String16& prefix, Vector<String16>* matches) {
1086 uid_t uid = IPCThreadState::self()->getCallingUid();
1087 if (!has_permission(uid, P_SAW)) {
1088 ALOGW("permission denied for %d: saw", uid);
1089 return ::PERMISSION_DENIED;
1090 }
1091 uid = get_keystore_euid(uid);
Kenny Root70e3a862012-02-15 17:20:23 -08001092
Kenny Root07438c82012-11-02 15:41:02 -07001093 DIR* dir = opendir(".");
1094 if (!dir) {
1095 return ::SYSTEM_ERROR;
1096 }
Kenny Root70e3a862012-02-15 17:20:23 -08001097
Kenny Root07438c82012-11-02 15:41:02 -07001098 const String8 prefix8(prefix);
1099 char filename[NAME_MAX];
Kenny Root70e3a862012-02-15 17:20:23 -08001100
Kenny Root07438c82012-11-02 15:41:02 -07001101 int n = encode_key_for_uid(filename, uid, prefix8);
Kenny Root70e3a862012-02-15 17:20:23 -08001102
Kenny Root07438c82012-11-02 15:41:02 -07001103 struct dirent* file;
1104 while ((file = readdir(dir)) != NULL) {
1105 if (!strncmp(filename, file->d_name, n)) {
1106 const char* p = &file->d_name[n];
1107 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001108
Kenny Root07438c82012-11-02 15:41:02 -07001109 size_t extra = decode_key_length(p, plen);
1110 char *match = (char*) malloc(extra + 1);
1111 if (match != NULL) {
1112 decode_key(match, p, plen);
1113 matches->push(String16(match, extra));
1114 free(match);
1115 } else {
1116 ALOGW("could not allocate match of size %zd", extra);
1117 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001118 }
1119 }
Kenny Root07438c82012-11-02 15:41:02 -07001120 closedir(dir);
1121
1122 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001123 }
1124
Kenny Root07438c82012-11-02 15:41:02 -07001125 int32_t reset() {
1126 uid_t uid = IPCThreadState::self()->getCallingUid();
1127 if (!has_permission(uid, P_RESET)) {
1128 ALOGW("permission denied for %d: reset", uid);
1129 return ::PERMISSION_DENIED;
1130 }
1131
1132 ResponseCode rc = mKeyStore->reset() ? ::NO_ERROR : ::SYSTEM_ERROR;
1133
1134 const keymaster_device_t* device = mKeyStore->getDevice();
1135 if (device == NULL) {
1136 ALOGE("No keymaster device!");
1137 return ::SYSTEM_ERROR;
1138 }
1139
1140 if (device->delete_all == NULL) {
1141 ALOGV("keymaster device doesn't implement delete_all");
1142 return rc;
1143 }
1144
1145 if (device->delete_all(device)) {
1146 ALOGE("Problem calling keymaster's delete_all");
1147 return ::SYSTEM_ERROR;
1148 }
1149
Kenny Root9a53d3e2012-08-14 10:47:54 -07001150 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001151 }
1152
Kenny Root07438c82012-11-02 15:41:02 -07001153 /*
1154 * Here is the history. To improve the security, the parameters to generate the
1155 * master key has been changed. To make a seamless transition, we update the
1156 * file using the same password when the user unlock it for the first time. If
1157 * any thing goes wrong during the transition, the new file will not overwrite
1158 * the old one. This avoids permanent damages of the existing data.
1159 */
1160 int32_t password(const String16& password) {
1161 uid_t uid = IPCThreadState::self()->getCallingUid();
1162 if (!has_permission(uid, P_PASSWORD)) {
1163 ALOGW("permission denied for %d: password", uid);
1164 return ::PERMISSION_DENIED;
1165 }
Kenny Root70e3a862012-02-15 17:20:23 -08001166
Kenny Root07438c82012-11-02 15:41:02 -07001167 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001168
Kenny Root07438c82012-11-02 15:41:02 -07001169 switch (mKeyStore->getState()) {
1170 case ::STATE_UNINITIALIZED: {
1171 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
1172 return mKeyStore->initialize(password8);
1173 }
1174 case ::STATE_NO_ERROR: {
1175 // rewrite master key with new password.
1176 return mKeyStore->writeMasterKey(password8);
1177 }
1178 case ::STATE_LOCKED: {
1179 // read master key, decrypt with password, initialize mMasterKey*.
1180 return mKeyStore->readMasterKey(password8);
1181 }
1182 }
1183 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001184 }
1185
Kenny Root07438c82012-11-02 15:41:02 -07001186 int32_t lock() {
1187 uid_t uid = IPCThreadState::self()->getCallingUid();
1188 if (!has_permission(uid, P_LOCK)) {
1189 ALOGW("permission denied for %d: lock", uid);
1190 return ::PERMISSION_DENIED;
1191 }
Kenny Root70e3a862012-02-15 17:20:23 -08001192
Kenny Root07438c82012-11-02 15:41:02 -07001193 State state = checkState();
1194 if (state != STATE_NO_ERROR) {
1195 ALOGD("calling lock in state: %d", state);
1196 return state;
1197 }
1198
1199 mKeyStore->lock();
1200 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001201 }
1202
Kenny Root07438c82012-11-02 15:41:02 -07001203 int32_t unlock(const String16& pw) {
1204 uid_t uid = IPCThreadState::self()->getCallingUid();
1205 if (!has_permission(uid, P_UNLOCK)) {
1206 ALOGW("permission denied for %d: unlock", uid);
1207 return ::PERMISSION_DENIED;
1208 }
1209
1210 State state = checkState();
1211 if (state != STATE_LOCKED) {
1212 ALOGD("calling unlock when not locked");
1213 return state;
1214 }
1215
1216 const String8 password8(pw);
1217 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001218 }
1219
Kenny Root07438c82012-11-02 15:41:02 -07001220 int32_t zero() {
1221 uid_t uid = IPCThreadState::self()->getCallingUid();
1222 if (!has_permission(uid, P_ZERO)) {
1223 ALOGW("permission denied for %d: zero", uid);
1224 return -1;
1225 }
Kenny Root70e3a862012-02-15 17:20:23 -08001226
Kenny Root07438c82012-11-02 15:41:02 -07001227 return mKeyStore->isEmpty() ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001228 }
1229
Kenny Root07438c82012-11-02 15:41:02 -07001230 int32_t generate(const String16& name) {
1231 uid_t uid = IPCThreadState::self()->getCallingUid();
1232 if (!has_permission(uid, P_INSERT)) {
1233 ALOGW("permission denied for %d: generate", uid);
1234 return ::PERMISSION_DENIED;
1235 }
1236 uid = get_keystore_euid(uid);
Kenny Root70e3a862012-02-15 17:20:23 -08001237
Kenny Root07438c82012-11-02 15:41:02 -07001238 State state = checkState();
1239 if (state != STATE_NO_ERROR) {
1240 ALOGD("calling generate in state: %d", state);
1241 return state;
1242 }
Kenny Root70e3a862012-02-15 17:20:23 -08001243
Kenny Root07438c82012-11-02 15:41:02 -07001244 String8 name8(name);
1245 char filename[NAME_MAX];
1246
1247 uint8_t* data;
1248 size_t dataLength;
1249 int rc;
1250
1251 const keymaster_device_t* device = mKeyStore->getDevice();
1252 if (device == NULL) {
1253 return ::SYSTEM_ERROR;
1254 }
1255
1256 if (device->generate_keypair == NULL) {
1257 return ::SYSTEM_ERROR;
1258 }
1259
1260 keymaster_rsa_keygen_params_t rsa_params;
1261 rsa_params.modulus_size = 2048;
1262 rsa_params.public_exponent = 0x10001;
1263
1264 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1265 if (rc) {
1266 return ::SYSTEM_ERROR;
1267 }
1268
1269 encode_key_for_uid(filename, uid, name8);
1270
1271 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1272 free(data);
1273
1274 return mKeyStore->put(filename, &keyBlob);
Kenny Root70e3a862012-02-15 17:20:23 -08001275 }
1276
Kenny Root07438c82012-11-02 15:41:02 -07001277 int32_t import(const String16& name, const uint8_t* data, size_t length) {
1278 uid_t uid = IPCThreadState::self()->getCallingUid();
1279 if (!has_permission(uid, P_INSERT)) {
1280 ALOGW("permission denied for %d: import", uid);
1281 return ::PERMISSION_DENIED;
1282 }
1283 uid = get_keystore_euid(uid);
1284
1285 State state = checkState();
1286 if (state != STATE_NO_ERROR) {
1287 ALOGD("calling import in state: %d", state);
1288 return state;
1289 }
1290
1291 String8 name8(name);
1292 char filename[NAME_MAX];
1293
1294 encode_key_for_uid(filename, uid, name8);
1295
1296 return mKeyStore->importKey(data, length, filename);
Kenny Root70e3a862012-02-15 17:20:23 -08001297 }
1298
Kenny Root07438c82012-11-02 15:41:02 -07001299 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1300 size_t* outLength) {
1301 uid_t uid = IPCThreadState::self()->getCallingUid();
1302 if (!has_permission(uid, P_SIGN)) {
1303 ALOGW("permission denied for %d: saw", uid);
1304 return ::PERMISSION_DENIED;
1305 }
1306 uid = get_keystore_euid(uid);
1307
1308 State state = checkState();
1309 if (state != STATE_NO_ERROR) {
1310 ALOGD("calling sign in state: %d", state);
1311 return state;
1312 }
1313
1314 Blob keyBlob;
1315 String8 name8(name);
1316
1317 ALOGV("sign %s from uid %d", name8.string(), uid);
1318 int rc;
1319
1320 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, uid, ::TYPE_KEY_PAIR);
1321 if (responseCode != ::NO_ERROR) {
1322 return responseCode;
1323 }
1324
1325 const keymaster_device_t* device = mKeyStore->getDevice();
1326 if (device == NULL) {
1327 ALOGE("no keymaster device; cannot sign");
1328 return ::SYSTEM_ERROR;
1329 }
1330
1331 if (device->sign_data == NULL) {
1332 ALOGE("device doesn't implement signing");
1333 return ::SYSTEM_ERROR;
1334 }
1335
1336 keymaster_rsa_sign_params_t params;
1337 params.digest_type = DIGEST_NONE;
1338 params.padding_type = PADDING_NONE;
1339
1340 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1341 data, length, out, outLength);
1342 if (rc) {
1343 ALOGW("device couldn't sign data");
1344 return ::SYSTEM_ERROR;
1345 }
1346
1347 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001348 }
1349
Kenny Root07438c82012-11-02 15:41:02 -07001350 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1351 const uint8_t* signature, size_t signatureLength) {
1352 uid_t uid = IPCThreadState::self()->getCallingUid();
1353 if (!has_permission(uid, P_VERIFY)) {
1354 ALOGW("permission denied for %d: verify", uid);
1355 return ::PERMISSION_DENIED;
1356 }
1357 uid = get_keystore_euid(uid);
Kenny Root70e3a862012-02-15 17:20:23 -08001358
Kenny Root07438c82012-11-02 15:41:02 -07001359 State state = checkState();
1360 if (state != STATE_NO_ERROR) {
1361 ALOGD("calling verify in state: %d", state);
1362 return state;
1363 }
Kenny Root70e3a862012-02-15 17:20:23 -08001364
Kenny Root07438c82012-11-02 15:41:02 -07001365 Blob keyBlob;
1366 String8 name8(name);
1367 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001368
Kenny Root07438c82012-11-02 15:41:02 -07001369 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, uid, TYPE_KEY_PAIR);
1370 if (responseCode != ::NO_ERROR) {
1371 return responseCode;
1372 }
Kenny Root70e3a862012-02-15 17:20:23 -08001373
Kenny Root07438c82012-11-02 15:41:02 -07001374 const keymaster_device_t* device = mKeyStore->getDevice();
1375 if (device == NULL) {
1376 return ::SYSTEM_ERROR;
1377 }
Kenny Root70e3a862012-02-15 17:20:23 -08001378
Kenny Root07438c82012-11-02 15:41:02 -07001379 if (device->verify_data == NULL) {
1380 return ::SYSTEM_ERROR;
1381 }
Kenny Root70e3a862012-02-15 17:20:23 -08001382
Kenny Root07438c82012-11-02 15:41:02 -07001383 keymaster_rsa_sign_params_t params;
1384 params.digest_type = DIGEST_NONE;
1385 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001386
Kenny Root07438c82012-11-02 15:41:02 -07001387 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1388 data, dataLength, signature, signatureLength);
1389 if (rc) {
1390 return ::SYSTEM_ERROR;
1391 } else {
1392 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001393 }
1394 }
Kenny Root07438c82012-11-02 15:41:02 -07001395
1396 /*
1397 * TODO: The abstraction between things stored in hardware and regular blobs
1398 * of data stored on the filesystem should be moved down to keystore itself.
1399 * Unfortunately the Java code that calls this has naming conventions that it
1400 * knows about. Ideally keystore shouldn't be used to store random blobs of
1401 * data.
1402 *
1403 * Until that happens, it's necessary to have a separate "get_pubkey" and
1404 * "del_key" since the Java code doesn't really communicate what it's
1405 * intentions are.
1406 */
1407 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
1408 uid_t uid = IPCThreadState::self()->getCallingUid();
1409 if (!has_permission(uid, P_GET)) {
1410 ALOGW("permission denied for %d: get_pubkey", uid);
1411 return ::PERMISSION_DENIED;
1412 }
1413 uid = get_keystore_euid(uid);
1414
1415 State state = checkState();
1416 if (state != STATE_NO_ERROR) {
1417 ALOGD("calling get_pubkey in state: %d", state);
1418 return state;
1419 }
1420
1421 Blob keyBlob;
1422 String8 name8(name);
1423
1424 ALOGV("get_pubkey '%s' from uid %d", name8.string(), uid);
1425
1426 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, uid,
1427 TYPE_KEY_PAIR);
1428 if (responseCode != ::NO_ERROR) {
1429 return responseCode;
1430 }
1431
1432 const keymaster_device_t* device = mKeyStore->getDevice();
1433 if (device == NULL) {
1434 return ::SYSTEM_ERROR;
1435 }
1436
1437 if (device->get_keypair_public == NULL) {
1438 ALOGE("device has no get_keypair_public implementation!");
1439 return ::SYSTEM_ERROR;
1440 }
1441
1442 int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
1443 pubkeyLength);
1444 if (rc) {
1445 return ::SYSTEM_ERROR;
1446 }
1447
1448 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001449 }
Kenny Root07438c82012-11-02 15:41:02 -07001450
1451 int32_t del_key(const String16& name) {
1452 uid_t uid = IPCThreadState::self()->getCallingUid();
1453 if (!has_permission(uid, P_DELETE)) {
1454 ALOGW("permission denied for %d: del_key", uid);
1455 return ::PERMISSION_DENIED;
1456 }
1457 uid = get_keystore_euid(uid);
1458
1459 String8 name8(name);
1460 char filename[NAME_MAX];
1461
1462 encode_key_for_uid(filename, uid, name8);
1463
1464 Blob keyBlob;
1465 ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, ::TYPE_KEY_PAIR);
1466 if (responseCode != ::NO_ERROR) {
1467 return responseCode;
1468 }
1469
1470 ResponseCode rc = ::NO_ERROR;
1471
1472 const keymaster_device_t* device = mKeyStore->getDevice();
1473 if (device == NULL) {
1474 rc = ::SYSTEM_ERROR;
1475 } else {
1476 // A device doesn't have to implement delete_keypair.
1477 if (device->delete_keypair != NULL) {
1478 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1479 rc = ::SYSTEM_ERROR;
1480 }
1481 }
1482 }
1483
1484 if (rc != ::NO_ERROR) {
1485 return rc;
1486 }
1487
1488 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1489 }
1490
1491 int32_t grant(const String16& name, int32_t granteeUid) {
1492 uid_t uid = IPCThreadState::self()->getCallingUid();
1493 if (!has_permission(uid, P_GRANT)) {
1494 ALOGW("permission denied for %d: grant", uid);
1495 return ::PERMISSION_DENIED;
1496 }
1497 uid = get_keystore_euid(uid);
1498
1499 State state = checkState();
1500 if (state != STATE_NO_ERROR) {
1501 ALOGD("calling grant in state: %d", state);
1502 return state;
1503 }
1504
1505 String8 name8(name);
1506 char filename[NAME_MAX];
1507
1508 encode_key_for_uid(filename, uid, name8);
1509
1510 if (access(filename, R_OK) == -1) {
1511 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1512 }
1513
1514 mKeyStore->addGrant(filename, granteeUid);
1515 return ::NO_ERROR;
1516 }
1517
1518 int32_t ungrant(const String16& name, int32_t granteeUid) {
1519 uid_t uid = IPCThreadState::self()->getCallingUid();
1520 if (!has_permission(uid, P_GRANT)) {
1521 ALOGW("permission denied for %d: ungrant", uid);
1522 return ::PERMISSION_DENIED;
1523 }
1524 uid = get_keystore_euid(uid);
1525
1526 State state = checkState();
1527 if (state != STATE_NO_ERROR) {
1528 ALOGD("calling ungrant in state: %d", state);
1529 return state;
1530 }
1531
1532 String8 name8(name);
1533 char filename[NAME_MAX];
1534
1535 encode_key_for_uid(filename, uid, name8);
1536
1537 if (access(filename, R_OK) == -1) {
1538 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1539 }
1540
1541 return mKeyStore->removeGrant(filename, granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
1542 }
1543
1544 int64_t getmtime(const String16& name) {
1545 uid_t uid = IPCThreadState::self()->getCallingUid();
1546 if (!has_permission(uid, P_GET)) {
1547 ALOGW("permission denied for %d: getmtime", uid);
1548 return ::PERMISSION_DENIED;
1549 }
1550 uid = get_keystore_euid(uid);
1551
1552 String8 name8(name);
1553 char filename[NAME_MAX];
1554
1555 encode_key_for_uid(filename, uid, name8);
1556
1557 if (access(filename, R_OK) == -1) {
1558 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1559 }
1560
1561 int fd = open(filename, O_NOFOLLOW, O_RDONLY);
1562 if (fd < 0) {
1563 return ::SYSTEM_ERROR;
1564 }
1565
1566 struct stat s;
1567 int ret = fstat(fd, &s);
1568 close(fd);
1569 if (ret == -1) {
1570 return ::SYSTEM_ERROR;
1571 }
1572
1573 return s.st_mtime;
1574 }
1575
1576private:
1577 inline State checkState() {
1578 return mKeyStore->getState();
1579 }
1580
1581 ::KeyStore* mKeyStore;
1582};
1583
1584}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08001585
1586int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08001587 if (argc < 2) {
1588 ALOGE("A directory must be specified!");
1589 return 1;
1590 }
1591 if (chdir(argv[1]) == -1) {
1592 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
1593 return 1;
1594 }
1595
1596 Entropy entropy;
1597 if (!entropy.open()) {
1598 return 1;
1599 }
Kenny Root70e3a862012-02-15 17:20:23 -08001600
1601 keymaster_device_t* dev;
1602 if (keymaster_device_initialize(&dev)) {
1603 ALOGE("keystore keymaster could not be initialized; exiting");
1604 return 1;
1605 }
1606
Kenny Root70e3a862012-02-15 17:20:23 -08001607 KeyStore keyStore(&entropy, dev);
Kenny Root07438c82012-11-02 15:41:02 -07001608 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
1609 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
1610 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
1611 if (ret != android::OK) {
1612 ALOGE("Couldn't register binder service!");
1613 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08001614 }
Kenny Root07438c82012-11-02 15:41:02 -07001615
1616 /*
1617 * We're the only thread in existence, so we're just going to process
1618 * Binder transaction as a single-threaded program.
1619 */
1620 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08001621
1622 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08001623 return 1;
1624}