blob: 23d51c422af1e29437cd3ec54da93868ed0806ae [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>
Kenny Root655b9582013-04-04 08:37:42 -070027#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080028#include <fcntl.h>
29#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070030#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080031#include <sys/types.h>
32#include <sys/socket.h>
33#include <sys/stat.h>
34#include <sys/time.h>
35#include <arpa/inet.h>
36
37#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070038#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080039#include <openssl/evp.h>
40#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070041#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080042
Kenny Root70e3a862012-02-15 17:20:23 -080043#include <hardware/keymaster.h>
44
Kenny Rootb4d2e022013-09-04 13:56:03 -070045#include <keymaster/softkeymaster.h>
46
Kenny Root26cfc082013-09-11 14:38:56 -070047#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070048#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070049#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080050
Kenny Root07438c82012-11-02 15:41:02 -070051#include <keystore/IKeystoreService.h>
52#include <binder/IPCThreadState.h>
53#include <binder/IServiceManager.h>
54
Kenny Roota91203b2012-02-15 15:00:46 -080055#include <cutils/log.h>
56#include <cutils/sockets.h>
57#include <private/android_filesystem_config.h>
58
Kenny Root07438c82012-11-02 15:41:02 -070059#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080060
Kenny Root60711792013-08-16 14:02:41 -070061#include "defaults.h"
62
Kenny Roota91203b2012-02-15 15:00:46 -080063/* KeyStore is a secured storage for key-value pairs. In this implementation,
64 * each file stores one key-value pair. Keys are encoded in file names, and
65 * values are encrypted with checksums. The encryption key is protected by a
66 * user-defined password. To keep things simple, buffers are always larger than
67 * the maximum space we needed, so boundary checks on buffers are omitted. */
68
69#define KEY_SIZE ((NAME_MAX - 15) / 2)
70#define VALUE_SIZE 32768
71#define PASSWORD_SIZE VALUE_SIZE
72
Kenny Root822c3a92012-03-23 16:34:39 -070073
Kenny Root60711792013-08-16 14:02:41 -070074struct BIGNUM_Delete {
75 void operator()(BIGNUM* p) const {
76 BN_free(p);
77 }
78};
79typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
80
Kenny Root822c3a92012-03-23 16:34:39 -070081struct BIO_Delete {
82 void operator()(BIO* p) const {
83 BIO_free(p);
84 }
85};
86typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
87
88struct EVP_PKEY_Delete {
89 void operator()(EVP_PKEY* p) const {
90 EVP_PKEY_free(p);
91 }
92};
93typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
94
95struct PKCS8_PRIV_KEY_INFO_Delete {
96 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
97 PKCS8_PRIV_KEY_INFO_free(p);
98 }
99};
100typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
101
102
Kenny Root70e3a862012-02-15 17:20:23 -0800103static int keymaster_device_initialize(keymaster_device_t** dev) {
104 int rc;
105
106 const hw_module_t* mod;
107 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
108 if (rc) {
109 ALOGE("could not find any keystore module");
110 goto out;
111 }
112
113 rc = keymaster_open(mod, dev);
114 if (rc) {
115 ALOGE("could not open keymaster device in %s (%s)",
116 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
117 goto out;
118 }
119
120 return 0;
121
122out:
123 *dev = NULL;
124 return rc;
125}
126
127static void keymaster_device_release(keymaster_device_t* dev) {
128 keymaster_close(dev);
129}
130
Kenny Root07438c82012-11-02 15:41:02 -0700131/***************
132 * PERMISSIONS *
133 ***************/
134
135/* Here are the permissions, actions, users, and the main function. */
136typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700137 P_TEST = 1 << 0,
138 P_GET = 1 << 1,
139 P_INSERT = 1 << 2,
140 P_DELETE = 1 << 3,
141 P_EXIST = 1 << 4,
142 P_SAW = 1 << 5,
143 P_RESET = 1 << 6,
144 P_PASSWORD = 1 << 7,
145 P_LOCK = 1 << 8,
146 P_UNLOCK = 1 << 9,
147 P_ZERO = 1 << 10,
148 P_SIGN = 1 << 11,
149 P_VERIFY = 1 << 12,
150 P_GRANT = 1 << 13,
151 P_DUPLICATE = 1 << 14,
Kenny Roota9bb5492013-04-01 16:29:11 -0700152 P_CLEAR_UID = 1 << 15,
Kenny Root07438c82012-11-02 15:41:02 -0700153} perm_t;
154
155static struct user_euid {
156 uid_t uid;
157 uid_t euid;
158} user_euids[] = {
159 {AID_VPN, AID_SYSTEM},
160 {AID_WIFI, AID_SYSTEM},
161 {AID_ROOT, AID_SYSTEM},
162};
163
164static struct user_perm {
165 uid_t uid;
166 perm_t perms;
167} user_perms[] = {
168 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
169 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
170 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
171 {AID_ROOT, static_cast<perm_t>(P_GET) },
172};
173
174static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
175 | P_VERIFY);
176
Kenny Root655b9582013-04-04 08:37:42 -0700177/**
178 * Returns the app ID (in the Android multi-user sense) for the current
179 * UNIX UID.
180 */
181static uid_t get_app_id(uid_t uid) {
182 return uid % AID_USER;
183}
184
185/**
186 * Returns the user ID (in the Android multi-user sense) for the current
187 * UNIX UID.
188 */
189static uid_t get_user_id(uid_t uid) {
190 return uid / AID_USER;
191}
192
193
Kenny Root07438c82012-11-02 15:41:02 -0700194static bool has_permission(uid_t uid, perm_t perm) {
Kenny Root655b9582013-04-04 08:37:42 -0700195 // All system users are equivalent for multi-user support.
196 if (get_app_id(uid) == AID_SYSTEM) {
197 uid = AID_SYSTEM;
198 }
199
Kenny Root07438c82012-11-02 15:41:02 -0700200 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
201 struct user_perm user = user_perms[i];
202 if (user.uid == uid) {
203 return user.perms & perm;
204 }
205 }
206
207 return DEFAULT_PERMS & perm;
208}
209
Kenny Root49468902013-03-19 13:41:33 -0700210/**
211 * Returns the UID that the callingUid should act as. This is here for
212 * legacy support of the WiFi and VPN systems and should be removed
213 * when WiFi can operate in its own namespace.
214 */
Kenny Root07438c82012-11-02 15:41:02 -0700215static uid_t get_keystore_euid(uid_t uid) {
216 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
217 struct user_euid user = user_euids[i];
218 if (user.uid == uid) {
219 return user.euid;
220 }
221 }
222
223 return uid;
224}
225
Kenny Root49468902013-03-19 13:41:33 -0700226/**
227 * Returns true if the callingUid is allowed to interact in the targetUid's
228 * namespace.
229 */
230static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
231 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
232 struct user_euid user = user_euids[i];
233 if (user.euid == callingUid && user.uid == targetUid) {
234 return true;
235 }
236 }
237
238 return false;
239}
240
Kenny Roota91203b2012-02-15 15:00:46 -0800241/* Here is the encoding of keys. This is necessary in order to allow arbitrary
242 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
243 * into two bytes. The first byte is one of [+-.] which represents the first
244 * two bits of the character. The second byte encodes the rest of the bits into
245 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
246 * that Base64 cannot be used here due to the need of prefix match on keys. */
247
Kenny Root655b9582013-04-04 08:37:42 -0700248static size_t encode_key_length(const android::String8& keyName) {
249 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
250 size_t length = keyName.length();
251 for (int i = length; i > 0; --i, ++in) {
252 if (*in < '0' || *in > '~') {
253 ++length;
254 }
255 }
256 return length;
257}
258
Kenny Root07438c82012-11-02 15:41:02 -0700259static int encode_key(char* out, const android::String8& keyName) {
260 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
261 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800262 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700263 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800264 *out = '+' + (*in >> 6);
265 *++out = '0' + (*in & 0x3F);
266 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700267 } else {
268 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800269 }
270 }
271 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800272 return length;
273}
274
Kenny Root07438c82012-11-02 15:41:02 -0700275static int encode_key_for_uid(char* out, uid_t uid, const android::String8& keyName) {
Kenny Root70e3a862012-02-15 17:20:23 -0800276 int n = snprintf(out, NAME_MAX, "%u_", uid);
277 out += n;
278
Kenny Root07438c82012-11-02 15:41:02 -0700279 return n + encode_key(out, keyName);
Kenny Roota91203b2012-02-15 15:00:46 -0800280}
281
Kenny Root07438c82012-11-02 15:41:02 -0700282/*
283 * Converts from the "escaped" format on disk to actual name.
284 * This will be smaller than the input string.
285 *
286 * Characters that should combine with the next at the end will be truncated.
287 */
288static size_t decode_key_length(const char* in, size_t length) {
289 size_t outLength = 0;
290
291 for (const char* end = in + length; in < end; in++) {
292 /* This combines with the next character. */
293 if (*in < '0' || *in > '~') {
294 continue;
295 }
296
297 outLength++;
298 }
299 return outLength;
300}
301
302static void decode_key(char* out, const char* in, size_t length) {
303 for (const char* end = in + length; in < end; in++) {
304 if (*in < '0' || *in > '~') {
305 /* Truncate combining characters at the end. */
306 if (in + 1 >= end) {
307 break;
308 }
309
310 *out = (*in++ - '+') << 6;
311 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800312 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700313 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800314 }
315 }
316 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800317}
318
319static size_t readFully(int fd, uint8_t* data, size_t size) {
320 size_t remaining = size;
321 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800322 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800323 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800324 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800325 }
326 data += n;
327 remaining -= n;
328 }
329 return size;
330}
331
332static size_t writeFully(int fd, uint8_t* data, size_t size) {
333 size_t remaining = size;
334 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800335 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
336 if (n < 0) {
337 ALOGW("write failed: %s", strerror(errno));
338 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800339 }
340 data += n;
341 remaining -= n;
342 }
343 return size;
344}
345
346class Entropy {
347public:
348 Entropy() : mRandom(-1) {}
349 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800350 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800351 close(mRandom);
352 }
353 }
354
355 bool open() {
356 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800357 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
358 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800359 ALOGE("open: %s: %s", randomDevice, strerror(errno));
360 return false;
361 }
362 return true;
363 }
364
Kenny Root51878182012-03-13 12:53:19 -0700365 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800366 return (readFully(mRandom, data, size) == size);
367 }
368
369private:
370 int mRandom;
371};
372
373/* Here is the file format. There are two parts in blob.value, the secret and
374 * the description. The secret is stored in ciphertext, and its original size
375 * can be found in blob.length. The description is stored after the secret in
376 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700377 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700378 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800379 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
380 * and decryptBlob(). Thus they should not be accessed from outside. */
381
Kenny Root822c3a92012-03-23 16:34:39 -0700382/* ** Note to future implementors of encryption: **
383 * Currently this is the construction:
384 * metadata || Enc(MD5(data) || data)
385 *
386 * This should be the construction used for encrypting if re-implementing:
387 *
388 * Derive independent keys for encryption and MAC:
389 * Kenc = AES_encrypt(masterKey, "Encrypt")
390 * Kmac = AES_encrypt(masterKey, "MAC")
391 *
392 * Store this:
393 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
394 * HMAC(Kmac, metadata || Enc(data))
395 */
Kenny Roota91203b2012-02-15 15:00:46 -0800396struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700397 uint8_t version;
398 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700399 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800400 uint8_t info;
401 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700402 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800403 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700404 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800405 int32_t length; // in network byte order when encrypted
406 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
407};
408
Kenny Root822c3a92012-03-23 16:34:39 -0700409typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700410 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700411 TYPE_GENERIC = 1,
412 TYPE_MASTER_KEY = 2,
413 TYPE_KEY_PAIR = 3,
414} BlobType;
415
Kenny Rootf9119d62013-04-03 09:22:15 -0700416static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700417
Kenny Roota91203b2012-02-15 15:00:46 -0800418class Blob {
419public:
Kenny Root07438c82012-11-02 15:41:02 -0700420 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
421 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800422 mBlob.length = valueLength;
423 memcpy(mBlob.value, value, valueLength);
424
425 mBlob.info = infoLength;
426 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700427
Kenny Root07438c82012-11-02 15:41:02 -0700428 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700429 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700430
431 mBlob.flags = KEYSTORE_FLAG_NONE;
Kenny Roota91203b2012-02-15 15:00:46 -0800432 }
433
434 Blob(blob b) {
435 mBlob = b;
436 }
437
438 Blob() {}
439
Kenny Root51878182012-03-13 12:53:19 -0700440 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800441 return mBlob.value;
442 }
443
Kenny Root51878182012-03-13 12:53:19 -0700444 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800445 return mBlob.length;
446 }
447
Kenny Root51878182012-03-13 12:53:19 -0700448 const uint8_t* getInfo() const {
449 return mBlob.value + mBlob.length;
450 }
451
452 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800453 return mBlob.info;
454 }
455
Kenny Root822c3a92012-03-23 16:34:39 -0700456 uint8_t getVersion() const {
457 return mBlob.version;
458 }
459
Kenny Rootf9119d62013-04-03 09:22:15 -0700460 bool isEncrypted() const {
461 if (mBlob.version < 2) {
462 return true;
463 }
464
465 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
466 }
467
468 void setEncrypted(bool encrypted) {
469 if (encrypted) {
470 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
471 } else {
472 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
473 }
474 }
475
Kenny Rootb4d2e022013-09-04 13:56:03 -0700476 bool isFallback() const {
477 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
478 }
479
480 void setFallback(bool fallback) {
481 if (fallback) {
482 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
483 } else {
484 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
485 }
486 }
487
Kenny Root822c3a92012-03-23 16:34:39 -0700488 void setVersion(uint8_t version) {
489 mBlob.version = version;
490 }
491
492 BlobType getType() const {
493 return BlobType(mBlob.type);
494 }
495
496 void setType(BlobType type) {
497 mBlob.type = uint8_t(type);
498 }
499
Kenny Rootf9119d62013-04-03 09:22:15 -0700500 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
501 ALOGV("writing blob %s", filename);
502 if (isEncrypted()) {
503 if (state != STATE_NO_ERROR) {
504 ALOGD("couldn't insert encrypted blob while not unlocked");
505 return LOCKED;
506 }
507
508 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
509 ALOGW("Could not read random data for: %s", filename);
510 return SYSTEM_ERROR;
511 }
Kenny Roota91203b2012-02-15 15:00:46 -0800512 }
513
514 // data includes the value and the value's length
515 size_t dataLength = mBlob.length + sizeof(mBlob.length);
516 // pad data to the AES_BLOCK_SIZE
517 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
518 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
519 // encrypted data includes the digest value
520 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
521 // move info after space for padding
522 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
523 // zero padding area
524 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
525
526 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800527
Kenny Rootf9119d62013-04-03 09:22:15 -0700528 if (isEncrypted()) {
529 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800530
Kenny Rootf9119d62013-04-03 09:22:15 -0700531 uint8_t vector[AES_BLOCK_SIZE];
532 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
533 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
534 aes_key, vector, AES_ENCRYPT);
535 }
536
Kenny Roota91203b2012-02-15 15:00:46 -0800537 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
538 size_t fileLength = encryptedLength + headerLength + mBlob.info;
539
540 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800541 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
542 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
543 if (out < 0) {
544 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800545 return SYSTEM_ERROR;
546 }
547 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
548 if (close(out) != 0) {
549 return SYSTEM_ERROR;
550 }
551 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800552 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800553 unlink(tmpFileName);
554 return SYSTEM_ERROR;
555 }
Kenny Root150ca932012-11-14 14:29:02 -0800556 if (rename(tmpFileName, filename) == -1) {
557 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
558 return SYSTEM_ERROR;
559 }
560 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800561 }
562
Kenny Rootf9119d62013-04-03 09:22:15 -0700563 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
564 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800565 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
566 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800567 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
568 }
569 // fileLength may be less than sizeof(mBlob) since the in
570 // memory version has extra padding to tolerate rounding up to
571 // the AES_BLOCK_SIZE
572 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
573 if (close(in) != 0) {
574 return SYSTEM_ERROR;
575 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700576
577 if (isEncrypted() && (state != STATE_NO_ERROR)) {
578 return LOCKED;
579 }
580
Kenny Roota91203b2012-02-15 15:00:46 -0800581 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
582 if (fileLength < headerLength) {
583 return VALUE_CORRUPTED;
584 }
585
586 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700587 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800588 return VALUE_CORRUPTED;
589 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700590
591 ssize_t digestedLength;
592 if (isEncrypted()) {
593 if (encryptedLength % AES_BLOCK_SIZE != 0) {
594 return VALUE_CORRUPTED;
595 }
596
597 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
598 mBlob.vector, AES_DECRYPT);
599 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
600 uint8_t computedDigest[MD5_DIGEST_LENGTH];
601 MD5(mBlob.digested, digestedLength, computedDigest);
602 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
603 return VALUE_CORRUPTED;
604 }
605 } else {
606 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800607 }
608
609 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
610 mBlob.length = ntohl(mBlob.length);
611 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
612 return VALUE_CORRUPTED;
613 }
614 if (mBlob.info != 0) {
615 // move info from after padding to after data
616 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
617 }
Kenny Root07438c82012-11-02 15:41:02 -0700618 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800619 }
620
621private:
622 struct blob mBlob;
623};
624
Kenny Root655b9582013-04-04 08:37:42 -0700625class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800626public:
Kenny Root655b9582013-04-04 08:37:42 -0700627 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
628 asprintf(&mUserDir, "user_%u", mUserId);
629 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
630 }
631
632 ~UserState() {
633 free(mUserDir);
634 free(mMasterKeyFile);
635 }
636
637 bool initialize() {
638 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
639 ALOGE("Could not create directory '%s'", mUserDir);
640 return false;
641 }
642
643 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800644 setState(STATE_LOCKED);
645 } else {
646 setState(STATE_UNINITIALIZED);
647 }
Kenny Root70e3a862012-02-15 17:20:23 -0800648
Kenny Root655b9582013-04-04 08:37:42 -0700649 return true;
650 }
651
652 uid_t getUserId() const {
653 return mUserId;
654 }
655
656 const char* getUserDirName() const {
657 return mUserDir;
658 }
659
660 const char* getMasterKeyFileName() const {
661 return mMasterKeyFile;
662 }
663
664 void setState(State state) {
665 mState = state;
666 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
667 mRetry = MAX_RETRY;
668 }
Kenny Roota91203b2012-02-15 15:00:46 -0800669 }
670
Kenny Root51878182012-03-13 12:53:19 -0700671 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800672 return mState;
673 }
674
Kenny Root51878182012-03-13 12:53:19 -0700675 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800676 return mRetry;
677 }
678
Kenny Root655b9582013-04-04 08:37:42 -0700679 void zeroizeMasterKeysInMemory() {
680 memset(mMasterKey, 0, sizeof(mMasterKey));
681 memset(mSalt, 0, sizeof(mSalt));
682 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
683 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800684 }
685
Kenny Root655b9582013-04-04 08:37:42 -0700686 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
687 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800688 return SYSTEM_ERROR;
689 }
Kenny Root655b9582013-04-04 08:37:42 -0700690 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800691 if (response != NO_ERROR) {
692 return response;
693 }
694 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700695 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800696 }
697
Kenny Root655b9582013-04-04 08:37:42 -0700698 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800699 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
700 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
701 AES_KEY passwordAesKey;
702 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700703 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700704 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800705 }
706
Kenny Root655b9582013-04-04 08:37:42 -0700707 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
708 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800709 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800710 return SYSTEM_ERROR;
711 }
712
713 // we read the raw blob to just to get the salt to generate
714 // the AES key, then we create the Blob to use with decryptBlob
715 blob rawBlob;
716 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
717 if (close(in) != 0) {
718 return SYSTEM_ERROR;
719 }
720 // find salt at EOF if present, otherwise we have an old file
721 uint8_t* salt;
722 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
723 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
724 } else {
725 salt = NULL;
726 }
727 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
728 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
729 AES_KEY passwordAesKey;
730 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
731 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700732 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
733 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800734 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700735 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800736 }
737 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
738 // if salt was missing, generate one and write a new master key file with the salt.
739 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700740 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800741 return SYSTEM_ERROR;
742 }
Kenny Root655b9582013-04-04 08:37:42 -0700743 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800744 }
745 if (response == NO_ERROR) {
746 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
747 setupMasterKeys();
748 }
749 return response;
750 }
751 if (mRetry <= 0) {
752 reset();
753 return UNINITIALIZED;
754 }
755 --mRetry;
756 switch (mRetry) {
757 case 0: return WRONG_PASSWORD_0;
758 case 1: return WRONG_PASSWORD_1;
759 case 2: return WRONG_PASSWORD_2;
760 case 3: return WRONG_PASSWORD_3;
761 default: return WRONG_PASSWORD_3;
762 }
763 }
764
Kenny Root655b9582013-04-04 08:37:42 -0700765 AES_KEY* getEncryptionKey() {
766 return &mMasterKeyEncryption;
767 }
768
769 AES_KEY* getDecryptionKey() {
770 return &mMasterKeyDecryption;
771 }
772
Kenny Roota91203b2012-02-15 15:00:46 -0800773 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700774 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800775 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700776 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800777 return false;
778 }
Kenny Root655b9582013-04-04 08:37:42 -0700779
780 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800781 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700782 // We only care about files.
783 if (file->d_type != DT_REG) {
784 continue;
785 }
786
787 // Skip anything that starts with a "."
788 if (file->d_name[0] == '.') {
789 continue;
790 }
791
792 // Find the current file's UID.
793 char* end;
794 unsigned long thisUid = strtoul(file->d_name, &end, 10);
795 if (end[0] != '_' || end[1] == 0) {
796 continue;
797 }
798
799 // Skip if this is not our user.
800 if (get_user_id(thisUid) != mUserId) {
801 continue;
802 }
803
804 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800805 }
806 closedir(dir);
807 return true;
808 }
809
Kenny Root655b9582013-04-04 08:37:42 -0700810private:
811 static const int MASTER_KEY_SIZE_BYTES = 16;
812 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
813
814 static const int MAX_RETRY = 4;
815 static const size_t SALT_SIZE = 16;
816
817 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
818 uint8_t* salt) {
819 size_t saltSize;
820 if (salt != NULL) {
821 saltSize = SALT_SIZE;
822 } else {
823 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
824 salt = (uint8_t*) "keystore";
825 // sizeof = 9, not strlen = 8
826 saltSize = sizeof("keystore");
827 }
828
829 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
830 saltSize, 8192, keySize, key);
831 }
832
833 bool generateSalt(Entropy* entropy) {
834 return entropy->generate_random_data(mSalt, sizeof(mSalt));
835 }
836
837 bool generateMasterKey(Entropy* entropy) {
838 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
839 return false;
840 }
841 if (!generateSalt(entropy)) {
842 return false;
843 }
844 return true;
845 }
846
847 void setupMasterKeys() {
848 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
849 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
850 setState(STATE_NO_ERROR);
851 }
852
853 uid_t mUserId;
854
855 char* mUserDir;
856 char* mMasterKeyFile;
857
858 State mState;
859 int8_t mRetry;
860
861 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
862 uint8_t mSalt[SALT_SIZE];
863
864 AES_KEY mMasterKeyEncryption;
865 AES_KEY mMasterKeyDecryption;
866};
867
868typedef struct {
869 uint32_t uid;
870 const uint8_t* filename;
871} grant_t;
872
873class KeyStore {
874public:
875 KeyStore(Entropy* entropy, keymaster_device_t* device)
876 : mEntropy(entropy)
877 , mDevice(device)
878 {
879 memset(&mMetaData, '\0', sizeof(mMetaData));
880 }
881
882 ~KeyStore() {
883 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
884 it != mGrants.end(); it++) {
885 delete *it;
886 mGrants.erase(it);
887 }
888
889 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
890 it != mMasterKeys.end(); it++) {
891 delete *it;
892 mMasterKeys.erase(it);
893 }
894 }
895
896 keymaster_device_t* getDevice() const {
897 return mDevice;
898 }
899
900 ResponseCode initialize() {
901 readMetaData();
902 if (upgradeKeystore()) {
903 writeMetaData();
904 }
905
906 return ::NO_ERROR;
907 }
908
909 State getState(uid_t uid) {
910 return getUserState(uid)->getState();
911 }
912
913 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
914 UserState* userState = getUserState(uid);
915 return userState->initialize(pw, mEntropy);
916 }
917
918 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
919 uid_t user_id = get_user_id(uid);
920 UserState* userState = getUserState(user_id);
921 return userState->writeMasterKey(pw, mEntropy);
922 }
923
924 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
925 uid_t user_id = get_user_id(uid);
926 UserState* userState = getUserState(user_id);
927 return userState->readMasterKey(pw, mEntropy);
928 }
929
930 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700931 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700932 encode_key(encoded, keyName);
933 return android::String8(encoded);
934 }
935
936 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700937 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700938 encode_key(encoded, keyName);
939 return android::String8::format("%u_%s", uid, encoded);
940 }
941
942 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700943 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700944 encode_key(encoded, keyName);
945 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
946 encoded);
947 }
948
949 bool reset(uid_t uid) {
950 UserState* userState = getUserState(uid);
951 userState->zeroizeMasterKeysInMemory();
952 userState->setState(STATE_UNINITIALIZED);
953 return userState->reset();
954 }
955
956 bool isEmpty(uid_t uid) const {
957 const UserState* userState = getUserState(uid);
958 if (userState == NULL) {
959 return true;
960 }
961
962 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800963 struct dirent* file;
964 if (!dir) {
965 return true;
966 }
967 bool result = true;
Kenny Root655b9582013-04-04 08:37:42 -0700968
969 char filename[NAME_MAX];
970 int n = snprintf(filename, sizeof(filename), "%u_", uid);
971
Kenny Roota91203b2012-02-15 15:00:46 -0800972 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700973 // We only care about files.
974 if (file->d_type != DT_REG) {
975 continue;
976 }
977
978 // Skip anything that starts with a "."
979 if (file->d_name[0] == '.') {
980 continue;
981 }
982
983 if (!strncmp(file->d_name, filename, n)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800984 result = false;
985 break;
986 }
987 }
988 closedir(dir);
989 return result;
990 }
991
Kenny Root655b9582013-04-04 08:37:42 -0700992 void lock(uid_t uid) {
993 UserState* userState = getUserState(uid);
994 userState->zeroizeMasterKeysInMemory();
995 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -0800996 }
997
Kenny Root655b9582013-04-04 08:37:42 -0700998 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
999 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001000 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1001 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001002 if (rc != NO_ERROR) {
1003 return rc;
1004 }
1005
1006 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001007 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001008 /* If we upgrade the key, we need to write it to disk again. Then
1009 * it must be read it again since the blob is encrypted each time
1010 * it's written.
1011 */
Kenny Root655b9582013-04-04 08:37:42 -07001012 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1013 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001014 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1015 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001016 return rc;
1017 }
1018 }
Kenny Root822c3a92012-03-23 16:34:39 -07001019 }
1020
Kenny Rootb4d2e022013-09-04 13:56:03 -07001021 /*
1022 * This will upgrade software-backed keys to hardware-backed keys when
1023 * the HAL for the device supports the newer key types.
1024 */
1025 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1026 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1027 && keyBlob->isFallback()) {
1028 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1029 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1030
1031 // The HAL allowed the import, reget the key to have the "fresh"
1032 // version.
1033 if (imported == NO_ERROR) {
1034 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1035 }
1036 }
1037
Kenny Rootd53bc922013-03-21 14:10:15 -07001038 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001039 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1040 return KEY_NOT_FOUND;
1041 }
1042
1043 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001044 }
1045
Kenny Root655b9582013-04-04 08:37:42 -07001046 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1047 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001048 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1049 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001050 }
1051
Kenny Root07438c82012-11-02 15:41:02 -07001052 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001053 const grant_t* existing = getGrant(filename, granteeUid);
1054 if (existing == NULL) {
1055 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001056 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001057 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001058 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001059 }
1060 }
1061
Kenny Root07438c82012-11-02 15:41:02 -07001062 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001063 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1064 it != mGrants.end(); it++) {
1065 grant_t* grant = *it;
1066 if (grant->uid == granteeUid
1067 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1068 mGrants.erase(it);
1069 return true;
1070 }
Kenny Root70e3a862012-02-15 17:20:23 -08001071 }
Kenny Root70e3a862012-02-15 17:20:23 -08001072 return false;
1073 }
1074
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001075 bool hasGrant(const char* filename, const uid_t uid) const {
1076 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001077 }
1078
Kenny Rootf9119d62013-04-03 09:22:15 -07001079 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1080 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001081 uint8_t* data;
1082 size_t dataLength;
1083 int rc;
1084
1085 if (mDevice->import_keypair == NULL) {
1086 ALOGE("Keymaster doesn't support import!");
1087 return SYSTEM_ERROR;
1088 }
1089
Kenny Rootb4d2e022013-09-04 13:56:03 -07001090 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001091 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001092 if (rc) {
Kenny Rootb4d2e022013-09-04 13:56:03 -07001093 // If this is an old device HAL, try to fall back to an old version
1094 if (mDevice->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_2) {
1095 rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength);
1096 isFallback = true;
1097 }
1098
1099 if (rc) {
1100 ALOGE("Error while importing keypair: %d", rc);
1101 return SYSTEM_ERROR;
1102 }
Kenny Root822c3a92012-03-23 16:34:39 -07001103 }
1104
1105 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1106 free(data);
1107
Kenny Rootf9119d62013-04-03 09:22:15 -07001108 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Rootb4d2e022013-09-04 13:56:03 -07001109 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001110
Kenny Root655b9582013-04-04 08:37:42 -07001111 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001112 }
1113
Kenny Root70f16c12013-09-05 13:06:32 -07001114 bool isHardwareBacked(const android::String16& keyType) const {
1115 if (mDevice == NULL) {
1116 ALOGW("can't get keymaster device");
1117 return false;
1118 }
1119
1120 if (sRSAKeyType == keyType) {
1121 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1122 } else {
1123 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1124 && (mDevice->common.module->module_api_version
1125 >= KEYMASTER_MODULE_API_VERSION_0_2);
1126 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001127 }
1128
Kenny Root655b9582013-04-04 08:37:42 -07001129 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1130 const BlobType type) {
1131 char filename[NAME_MAX];
1132 encode_key_for_uid(filename, uid, keyName);
1133
1134 UserState* userState = getUserState(uid);
1135 android::String8 filepath8;
1136
1137 filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1138 if (filepath8.string() == NULL) {
1139 ALOGW("can't create filepath for key %s", filename);
1140 return SYSTEM_ERROR;
1141 }
1142
1143 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1144 if (responseCode == NO_ERROR) {
1145 return responseCode;
1146 }
1147
1148 // If this is one of the legacy UID->UID mappings, use it.
1149 uid_t euid = get_keystore_euid(uid);
1150 if (euid != uid) {
1151 encode_key_for_uid(filename, euid, keyName);
1152 filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1153 responseCode = get(filepath8.string(), keyBlob, type, uid);
1154 if (responseCode == NO_ERROR) {
1155 return responseCode;
1156 }
1157 }
1158
1159 // They might be using a granted key.
1160 encode_key(filename, keyName);
1161 char* end;
1162 strtoul(filename, &end, 10);
1163 if (end[0] != '_' || end[1] == 0) {
1164 return KEY_NOT_FOUND;
1165 }
1166 filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1167 if (!hasGrant(filepath8.string(), uid)) {
1168 return responseCode;
1169 }
1170
1171 // It is a granted key. Try to load it.
1172 return get(filepath8.string(), keyBlob, type, uid);
1173 }
1174
1175 /**
1176 * Returns any existing UserState or creates it if it doesn't exist.
1177 */
1178 UserState* getUserState(uid_t uid) {
1179 uid_t userId = get_user_id(uid);
1180
1181 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1182 it != mMasterKeys.end(); it++) {
1183 UserState* state = *it;
1184 if (state->getUserId() == userId) {
1185 return state;
1186 }
1187 }
1188
1189 UserState* userState = new UserState(userId);
1190 if (!userState->initialize()) {
1191 /* There's not much we can do if initialization fails. Trying to
1192 * unlock the keystore for that user will fail as well, so any
1193 * subsequent request for this user will just return SYSTEM_ERROR.
1194 */
1195 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1196 }
1197 mMasterKeys.add(userState);
1198 return userState;
1199 }
1200
1201 /**
1202 * Returns NULL if the UserState doesn't already exist.
1203 */
1204 const UserState* getUserState(uid_t uid) const {
1205 uid_t userId = get_user_id(uid);
1206
1207 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1208 it != mMasterKeys.end(); it++) {
1209 UserState* state = *it;
1210 if (state->getUserId() == userId) {
1211 return state;
1212 }
1213 }
1214
1215 return NULL;
1216 }
1217
Kenny Roota91203b2012-02-15 15:00:46 -08001218private:
Kenny Root655b9582013-04-04 08:37:42 -07001219 static const char* sOldMasterKey;
1220 static const char* sMetaDataFile;
Kenny Root70f16c12013-09-05 13:06:32 -07001221 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001222 Entropy* mEntropy;
1223
Kenny Root70e3a862012-02-15 17:20:23 -08001224 keymaster_device_t* mDevice;
1225
Kenny Root655b9582013-04-04 08:37:42 -07001226 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001227
Kenny Root655b9582013-04-04 08:37:42 -07001228 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001229
Kenny Root655b9582013-04-04 08:37:42 -07001230 typedef struct {
1231 uint32_t version;
1232 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001233
Kenny Root655b9582013-04-04 08:37:42 -07001234 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001235
Kenny Root655b9582013-04-04 08:37:42 -07001236 const grant_t* getGrant(const char* filename, uid_t uid) const {
1237 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1238 it != mGrants.end(); it++) {
1239 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001240 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001241 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001242 return grant;
1243 }
1244 }
Kenny Root70e3a862012-02-15 17:20:23 -08001245 return NULL;
1246 }
1247
Kenny Root822c3a92012-03-23 16:34:39 -07001248 /**
1249 * Upgrade code. This will upgrade the key from the current version
1250 * to whatever is newest.
1251 */
Kenny Root655b9582013-04-04 08:37:42 -07001252 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1253 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001254 bool updated = false;
1255 uint8_t version = oldVersion;
1256
1257 /* From V0 -> V1: All old types were unknown */
1258 if (version == 0) {
1259 ALOGV("upgrading to version 1 and setting type %d", type);
1260
1261 blob->setType(type);
1262 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001263 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001264 }
1265 version = 1;
1266 updated = true;
1267 }
1268
Kenny Rootf9119d62013-04-03 09:22:15 -07001269 /* From V1 -> V2: All old keys were encrypted */
1270 if (version == 1) {
1271 ALOGV("upgrading to version 2");
1272
1273 blob->setEncrypted(true);
1274 version = 2;
1275 updated = true;
1276 }
1277
Kenny Root822c3a92012-03-23 16:34:39 -07001278 /*
1279 * If we've updated, set the key blob to the right version
1280 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001281 */
Kenny Root822c3a92012-03-23 16:34:39 -07001282 if (updated) {
1283 ALOGV("updated and writing file %s", filename);
1284 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001285 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001286
1287 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001288 }
1289
1290 /**
1291 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1292 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1293 * Then it overwrites the original blob with the new blob
1294 * format that is returned from the keymaster.
1295 */
Kenny Root655b9582013-04-04 08:37:42 -07001296 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001297 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1298 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1299 if (b.get() == NULL) {
1300 ALOGE("Problem instantiating BIO");
1301 return SYSTEM_ERROR;
1302 }
1303
1304 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1305 if (pkey.get() == NULL) {
1306 ALOGE("Couldn't read old PEM file");
1307 return SYSTEM_ERROR;
1308 }
1309
1310 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1311 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1312 if (len < 0) {
1313 ALOGE("Couldn't measure PKCS#8 length");
1314 return SYSTEM_ERROR;
1315 }
1316
Kenny Root70c98892013-02-07 09:10:36 -08001317 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1318 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001319 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1320 ALOGE("Couldn't convert to PKCS#8");
1321 return SYSTEM_ERROR;
1322 }
1323
Kenny Rootf9119d62013-04-03 09:22:15 -07001324 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1325 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001326 if (rc != NO_ERROR) {
1327 return rc;
1328 }
1329
Kenny Root655b9582013-04-04 08:37:42 -07001330 return get(filename, blob, TYPE_KEY_PAIR, uid);
1331 }
1332
1333 void readMetaData() {
1334 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1335 if (in < 0) {
1336 return;
1337 }
1338 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1339 if (fileLength != sizeof(mMetaData)) {
1340 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1341 sizeof(mMetaData));
1342 }
1343 close(in);
1344 }
1345
1346 void writeMetaData() {
1347 const char* tmpFileName = ".metadata.tmp";
1348 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1349 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1350 if (out < 0) {
1351 ALOGE("couldn't write metadata file: %s", strerror(errno));
1352 return;
1353 }
1354 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1355 if (fileLength != sizeof(mMetaData)) {
1356 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1357 sizeof(mMetaData));
1358 }
1359 close(out);
1360 rename(tmpFileName, sMetaDataFile);
1361 }
1362
1363 bool upgradeKeystore() {
1364 bool upgraded = false;
1365
1366 if (mMetaData.version == 0) {
1367 UserState* userState = getUserState(0);
1368
1369 // Initialize first so the directory is made.
1370 userState->initialize();
1371
1372 // Migrate the old .masterkey file to user 0.
1373 if (access(sOldMasterKey, R_OK) == 0) {
1374 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1375 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1376 return false;
1377 }
1378 }
1379
1380 // Initialize again in case we had a key.
1381 userState->initialize();
1382
1383 // Try to migrate existing keys.
1384 DIR* dir = opendir(".");
1385 if (!dir) {
1386 // Give up now; maybe we can upgrade later.
1387 ALOGE("couldn't open keystore's directory; something is wrong");
1388 return false;
1389 }
1390
1391 struct dirent* file;
1392 while ((file = readdir(dir)) != NULL) {
1393 // We only care about files.
1394 if (file->d_type != DT_REG) {
1395 continue;
1396 }
1397
1398 // Skip anything that starts with a "."
1399 if (file->d_name[0] == '.') {
1400 continue;
1401 }
1402
1403 // Find the current file's user.
1404 char* end;
1405 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1406 if (end[0] != '_' || end[1] == 0) {
1407 continue;
1408 }
1409 UserState* otherUser = getUserState(thisUid);
1410 if (otherUser->getUserId() != 0) {
1411 unlinkat(dirfd(dir), file->d_name, 0);
1412 }
1413
1414 // Rename the file into user directory.
1415 DIR* otherdir = opendir(otherUser->getUserDirName());
1416 if (otherdir == NULL) {
1417 ALOGW("couldn't open user directory for rename");
1418 continue;
1419 }
1420 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1421 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1422 }
1423 closedir(otherdir);
1424 }
1425 closedir(dir);
1426
1427 mMetaData.version = 1;
1428 upgraded = true;
1429 }
1430
1431 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001432 }
Kenny Roota91203b2012-02-15 15:00:46 -08001433};
1434
Kenny Root655b9582013-04-04 08:37:42 -07001435const char* KeyStore::sOldMasterKey = ".masterkey";
1436const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001437
Kenny Root70f16c12013-09-05 13:06:32 -07001438const android::String16 KeyStore::sRSAKeyType("RSA");
1439
Kenny Root07438c82012-11-02 15:41:02 -07001440namespace android {
1441class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1442public:
1443 KeyStoreProxy(KeyStore* keyStore)
1444 : mKeyStore(keyStore)
1445 {
Kenny Roota91203b2012-02-15 15:00:46 -08001446 }
Kenny Roota91203b2012-02-15 15:00:46 -08001447
Kenny Root07438c82012-11-02 15:41:02 -07001448 void binderDied(const wp<IBinder>&) {
1449 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001450 }
Kenny Roota91203b2012-02-15 15:00:46 -08001451
Kenny Root07438c82012-11-02 15:41:02 -07001452 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001453 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1454 if (!has_permission(callingUid, P_TEST)) {
1455 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001456 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001457 }
Kenny Roota91203b2012-02-15 15:00:46 -08001458
Kenny Root655b9582013-04-04 08:37:42 -07001459 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001460 }
1461
Kenny Root07438c82012-11-02 15:41:02 -07001462 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001463 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1464 if (!has_permission(callingUid, P_GET)) {
1465 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001466 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001467 }
Kenny Root07438c82012-11-02 15:41:02 -07001468
Kenny Root07438c82012-11-02 15:41:02 -07001469 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001470 Blob keyBlob;
Kenny Root49468902013-03-19 13:41:33 -07001471
Kenny Root655b9582013-04-04 08:37:42 -07001472 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001473 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001474 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001475 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001476 *item = NULL;
1477 *itemLength = 0;
1478 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001479 }
Kenny Roota91203b2012-02-15 15:00:46 -08001480
Kenny Root07438c82012-11-02 15:41:02 -07001481 *item = (uint8_t*) malloc(keyBlob.getLength());
1482 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1483 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001484
Kenny Root07438c82012-11-02 15:41:02 -07001485 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001486 }
1487
Kenny Rootf9119d62013-04-03 09:22:15 -07001488 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1489 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001490 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1491 if (!has_permission(callingUid, P_INSERT)) {
1492 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001493 return ::PERMISSION_DENIED;
1494 }
Kenny Root07438c82012-11-02 15:41:02 -07001495
Kenny Rootf9119d62013-04-03 09:22:15 -07001496 State state = mKeyStore->getState(callingUid);
1497 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1498 ALOGD("calling get in state: %d", state);
1499 return state;
1500 }
1501
Kenny Root49468902013-03-19 13:41:33 -07001502 if (targetUid == -1) {
1503 targetUid = callingUid;
1504 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001505 return ::PERMISSION_DENIED;
1506 }
1507
Kenny Root07438c82012-11-02 15:41:02 -07001508 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001509 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001510
1511 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Root655b9582013-04-04 08:37:42 -07001512 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001513 }
1514
Kenny Root49468902013-03-19 13:41:33 -07001515 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001516 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1517 if (!has_permission(callingUid, P_DELETE)) {
1518 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001519 return ::PERMISSION_DENIED;
1520 }
Kenny Root70e3a862012-02-15 17:20:23 -08001521
Kenny Root49468902013-03-19 13:41:33 -07001522 if (targetUid == -1) {
1523 targetUid = callingUid;
1524 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001525 return ::PERMISSION_DENIED;
1526 }
1527
Kenny Root07438c82012-11-02 15:41:02 -07001528 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001529 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001530
1531 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001532 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
1533 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001534 if (responseCode != ::NO_ERROR) {
1535 return responseCode;
1536 }
1537 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001538 }
1539
Kenny Root49468902013-03-19 13:41:33 -07001540 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001541 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1542 if (!has_permission(callingUid, P_EXIST)) {
1543 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001544 return ::PERMISSION_DENIED;
1545 }
Kenny Root70e3a862012-02-15 17:20:23 -08001546
Kenny Root49468902013-03-19 13:41:33 -07001547 if (targetUid == -1) {
1548 targetUid = callingUid;
1549 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001550 return ::PERMISSION_DENIED;
1551 }
1552
Kenny Root07438c82012-11-02 15:41:02 -07001553 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001554 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001555
Kenny Root655b9582013-04-04 08:37:42 -07001556 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001557 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1558 }
1559 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001560 }
1561
Kenny Root49468902013-03-19 13:41:33 -07001562 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001563 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1564 if (!has_permission(callingUid, P_SAW)) {
1565 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001566 return ::PERMISSION_DENIED;
1567 }
Kenny Root70e3a862012-02-15 17:20:23 -08001568
Kenny Root49468902013-03-19 13:41:33 -07001569 if (targetUid == -1) {
1570 targetUid = callingUid;
1571 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001572 return ::PERMISSION_DENIED;
1573 }
1574
Kenny Root655b9582013-04-04 08:37:42 -07001575 UserState* userState = mKeyStore->getUserState(targetUid);
1576 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001577 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07001578 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001579 return ::SYSTEM_ERROR;
1580 }
Kenny Root70e3a862012-02-15 17:20:23 -08001581
Kenny Root07438c82012-11-02 15:41:02 -07001582 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001583 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1584 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001585
Kenny Root07438c82012-11-02 15:41:02 -07001586 struct dirent* file;
1587 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001588 // We only care about files.
1589 if (file->d_type != DT_REG) {
1590 continue;
1591 }
1592
1593 // Skip anything that starts with a "."
1594 if (file->d_name[0] == '.') {
1595 continue;
1596 }
1597
1598 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001599 const char* p = &file->d_name[n];
1600 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001601
Kenny Root07438c82012-11-02 15:41:02 -07001602 size_t extra = decode_key_length(p, plen);
1603 char *match = (char*) malloc(extra + 1);
1604 if (match != NULL) {
1605 decode_key(match, p, plen);
1606 matches->push(String16(match, extra));
1607 free(match);
1608 } else {
1609 ALOGW("could not allocate match of size %zd", extra);
1610 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001611 }
1612 }
Kenny Root07438c82012-11-02 15:41:02 -07001613 closedir(dir);
1614
1615 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001616 }
1617
Kenny Root07438c82012-11-02 15:41:02 -07001618 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001619 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1620 if (!has_permission(callingUid, P_RESET)) {
1621 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001622 return ::PERMISSION_DENIED;
1623 }
1624
Kenny Root655b9582013-04-04 08:37:42 -07001625 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001626
1627 const keymaster_device_t* device = mKeyStore->getDevice();
1628 if (device == NULL) {
1629 ALOGE("No keymaster device!");
1630 return ::SYSTEM_ERROR;
1631 }
1632
1633 if (device->delete_all == NULL) {
1634 ALOGV("keymaster device doesn't implement delete_all");
1635 return rc;
1636 }
1637
1638 if (device->delete_all(device)) {
1639 ALOGE("Problem calling keymaster's delete_all");
1640 return ::SYSTEM_ERROR;
1641 }
1642
Kenny Root9a53d3e2012-08-14 10:47:54 -07001643 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001644 }
1645
Kenny Root07438c82012-11-02 15:41:02 -07001646 /*
1647 * Here is the history. To improve the security, the parameters to generate the
1648 * master key has been changed. To make a seamless transition, we update the
1649 * file using the same password when the user unlock it for the first time. If
1650 * any thing goes wrong during the transition, the new file will not overwrite
1651 * the old one. This avoids permanent damages of the existing data.
1652 */
1653 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001654 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1655 if (!has_permission(callingUid, P_PASSWORD)) {
1656 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001657 return ::PERMISSION_DENIED;
1658 }
Kenny Root70e3a862012-02-15 17:20:23 -08001659
Kenny Root07438c82012-11-02 15:41:02 -07001660 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001661
Kenny Root655b9582013-04-04 08:37:42 -07001662 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001663 case ::STATE_UNINITIALIZED: {
1664 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001665 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001666 }
1667 case ::STATE_NO_ERROR: {
1668 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001669 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001670 }
1671 case ::STATE_LOCKED: {
1672 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001673 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001674 }
1675 }
1676 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001677 }
1678
Kenny Root07438c82012-11-02 15:41:02 -07001679 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001680 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1681 if (!has_permission(callingUid, P_LOCK)) {
1682 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001683 return ::PERMISSION_DENIED;
1684 }
Kenny Root70e3a862012-02-15 17:20:23 -08001685
Kenny Root655b9582013-04-04 08:37:42 -07001686 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001687 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001688 ALOGD("calling lock in state: %d", state);
1689 return state;
1690 }
1691
Kenny Root655b9582013-04-04 08:37:42 -07001692 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001693 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001694 }
1695
Kenny Root07438c82012-11-02 15:41:02 -07001696 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001697 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1698 if (!has_permission(callingUid, P_UNLOCK)) {
1699 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001700 return ::PERMISSION_DENIED;
1701 }
1702
Kenny Root655b9582013-04-04 08:37:42 -07001703 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001704 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001705 ALOGD("calling unlock when not locked");
1706 return state;
1707 }
1708
1709 const String8 password8(pw);
1710 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001711 }
1712
Kenny Root07438c82012-11-02 15:41:02 -07001713 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001714 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1715 if (!has_permission(callingUid, P_ZERO)) {
1716 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001717 return -1;
1718 }
Kenny Root70e3a862012-02-15 17:20:23 -08001719
Kenny Root655b9582013-04-04 08:37:42 -07001720 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001721 }
1722
Kenny Root60711792013-08-16 14:02:41 -07001723 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1724 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001725 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1726 if (!has_permission(callingUid, P_INSERT)) {
1727 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001728 return ::PERMISSION_DENIED;
1729 }
Kenny Root70e3a862012-02-15 17:20:23 -08001730
Kenny Root49468902013-03-19 13:41:33 -07001731 if (targetUid == -1) {
1732 targetUid = callingUid;
1733 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001734 return ::PERMISSION_DENIED;
1735 }
1736
Kenny Root655b9582013-04-04 08:37:42 -07001737 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001738 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1739 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001740 return state;
1741 }
Kenny Root70e3a862012-02-15 17:20:23 -08001742
Kenny Root07438c82012-11-02 15:41:02 -07001743 uint8_t* data;
1744 size_t dataLength;
1745 int rc;
Kenny Rootb4d2e022013-09-04 13:56:03 -07001746 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001747
1748 const keymaster_device_t* device = mKeyStore->getDevice();
1749 if (device == NULL) {
1750 return ::SYSTEM_ERROR;
1751 }
1752
1753 if (device->generate_keypair == NULL) {
1754 return ::SYSTEM_ERROR;
1755 }
1756
Kenny Rootb4d2e022013-09-04 13:56:03 -07001757 if (keyType == EVP_PKEY_DSA) {
Kenny Root60711792013-08-16 14:02:41 -07001758 keymaster_dsa_keygen_params_t dsa_params;
1759 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001760
Kenny Root60711792013-08-16 14:02:41 -07001761 if (keySize == -1) {
1762 keySize = DSA_DEFAULT_KEY_SIZE;
1763 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1764 || keySize > DSA_MAX_KEY_SIZE) {
1765 ALOGI("invalid key size %d", keySize);
1766 return ::SYSTEM_ERROR;
1767 }
1768 dsa_params.key_size = keySize;
1769
1770 if (args->size() == 3) {
1771 sp<KeystoreArg> gArg = args->itemAt(0);
1772 sp<KeystoreArg> pArg = args->itemAt(1);
1773 sp<KeystoreArg> qArg = args->itemAt(2);
1774
1775 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1776 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1777 dsa_params.generator_len = gArg->size();
1778
1779 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1780 dsa_params.prime_p_len = pArg->size();
1781
1782 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1783 dsa_params.prime_q_len = qArg->size();
1784 } else {
1785 ALOGI("not all DSA parameters were read");
1786 return ::SYSTEM_ERROR;
1787 }
1788 } else if (args->size() != 0) {
1789 ALOGI("DSA args must be 3");
1790 return ::SYSTEM_ERROR;
1791 }
1792
Kenny Rootb4d2e022013-09-04 13:56:03 -07001793 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2) {
1794 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1795 } else {
1796 isFallback = true;
1797 rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1798 }
1799 } else if (keyType == EVP_PKEY_EC) {
Kenny Root60711792013-08-16 14:02:41 -07001800 keymaster_ec_keygen_params_t ec_params;
1801 memset(&ec_params, '\0', sizeof(ec_params));
1802
1803 if (keySize == -1) {
1804 keySize = EC_DEFAULT_KEY_SIZE;
1805 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1806 ALOGI("invalid key size %d", keySize);
1807 return ::SYSTEM_ERROR;
1808 }
1809 ec_params.field_size = keySize;
1810
Kenny Rootb4d2e022013-09-04 13:56:03 -07001811 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2) {
1812 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1813 } else {
1814 isFallback = true;
1815 rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1816 }
Kenny Root60711792013-08-16 14:02:41 -07001817 } else if (keyType == EVP_PKEY_RSA) {
1818 keymaster_rsa_keygen_params_t rsa_params;
1819 memset(&rsa_params, '\0', sizeof(rsa_params));
1820 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1821
1822 if (keySize == -1) {
1823 keySize = RSA_DEFAULT_KEY_SIZE;
1824 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1825 ALOGI("invalid key size %d", keySize);
1826 return ::SYSTEM_ERROR;
1827 }
1828 rsa_params.modulus_size = keySize;
1829
1830 if (args->size() > 1) {
1831 ALOGI("invalid number of arguments: %d", args->size());
1832 return ::SYSTEM_ERROR;
1833 } else if (args->size() == 1) {
1834 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1835 if (pubExpBlob != NULL) {
1836 Unique_BIGNUM pubExpBn(
1837 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1838 pubExpBlob->size(), NULL));
1839 if (pubExpBn.get() == NULL) {
1840 ALOGI("Could not convert public exponent to BN");
1841 return ::SYSTEM_ERROR;
1842 }
1843 unsigned long pubExp = BN_get_word(pubExpBn.get());
1844 if (pubExp == 0xFFFFFFFFL) {
1845 ALOGI("cannot represent public exponent as a long value");
1846 return ::SYSTEM_ERROR;
1847 }
1848 rsa_params.public_exponent = pubExp;
1849 }
1850 }
1851
1852 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1853 } else {
1854 ALOGW("Unsupported key type %d", keyType);
1855 rc = -1;
1856 }
1857
Kenny Root07438c82012-11-02 15:41:02 -07001858 if (rc) {
1859 return ::SYSTEM_ERROR;
1860 }
1861
Kenny Root655b9582013-04-04 08:37:42 -07001862 String8 name8(name);
1863 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001864
1865 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1866 free(data);
1867
Kenny Rootb4d2e022013-09-04 13:56:03 -07001868 keyBlob.setFallback(isFallback);
1869
Kenny Root655b9582013-04-04 08:37:42 -07001870 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001871 }
1872
Kenny Rootf9119d62013-04-03 09:22:15 -07001873 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1874 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001875 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1876 if (!has_permission(callingUid, P_INSERT)) {
1877 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001878 return ::PERMISSION_DENIED;
1879 }
Kenny Root07438c82012-11-02 15:41:02 -07001880
Kenny Root49468902013-03-19 13:41:33 -07001881 if (targetUid == -1) {
1882 targetUid = callingUid;
1883 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001884 return ::PERMISSION_DENIED;
1885 }
1886
Kenny Root655b9582013-04-04 08:37:42 -07001887 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001888 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001889 ALOGD("calling import in state: %d", state);
1890 return state;
1891 }
1892
1893 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001894 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001895
Kenny Rootf9119d62013-04-03 09:22:15 -07001896 return mKeyStore->importKey(data, length, filename.string(), callingUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001897 }
1898
Kenny Root07438c82012-11-02 15:41:02 -07001899 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1900 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001901 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1902 if (!has_permission(callingUid, P_SIGN)) {
1903 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001904 return ::PERMISSION_DENIED;
1905 }
Kenny Root07438c82012-11-02 15:41:02 -07001906
Kenny Root07438c82012-11-02 15:41:02 -07001907 Blob keyBlob;
1908 String8 name8(name);
1909
Kenny Rootd38a0b02013-02-13 12:59:14 -08001910 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001911 int rc;
1912
Kenny Root655b9582013-04-04 08:37:42 -07001913 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001914 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001915 if (responseCode != ::NO_ERROR) {
1916 return responseCode;
1917 }
1918
1919 const keymaster_device_t* device = mKeyStore->getDevice();
1920 if (device == NULL) {
1921 ALOGE("no keymaster device; cannot sign");
1922 return ::SYSTEM_ERROR;
1923 }
1924
1925 if (device->sign_data == NULL) {
1926 ALOGE("device doesn't implement signing");
1927 return ::SYSTEM_ERROR;
1928 }
1929
1930 keymaster_rsa_sign_params_t params;
1931 params.digest_type = DIGEST_NONE;
1932 params.padding_type = PADDING_NONE;
1933
Kenny Rootb4d2e022013-09-04 13:56:03 -07001934 if (keyBlob.isFallback()) {
1935 rc = openssl_sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1936 length, out, outLength);
1937 } else {
1938 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1939 length, out, outLength);
1940 }
Kenny Root07438c82012-11-02 15:41:02 -07001941 if (rc) {
1942 ALOGW("device couldn't sign data");
1943 return ::SYSTEM_ERROR;
1944 }
1945
1946 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001947 }
1948
Kenny Root07438c82012-11-02 15:41:02 -07001949 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1950 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001951 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1952 if (!has_permission(callingUid, P_VERIFY)) {
1953 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001954 return ::PERMISSION_DENIED;
1955 }
Kenny Root70e3a862012-02-15 17:20:23 -08001956
Kenny Root655b9582013-04-04 08:37:42 -07001957 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001958 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001959 ALOGD("calling verify in state: %d", state);
1960 return state;
1961 }
Kenny Root70e3a862012-02-15 17:20:23 -08001962
Kenny Root07438c82012-11-02 15:41:02 -07001963 Blob keyBlob;
1964 String8 name8(name);
1965 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001966
Kenny Root655b9582013-04-04 08:37:42 -07001967 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001968 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001969 if (responseCode != ::NO_ERROR) {
1970 return responseCode;
1971 }
Kenny Root70e3a862012-02-15 17:20:23 -08001972
Kenny Root07438c82012-11-02 15:41:02 -07001973 const keymaster_device_t* device = mKeyStore->getDevice();
1974 if (device == NULL) {
1975 return ::SYSTEM_ERROR;
1976 }
Kenny Root70e3a862012-02-15 17:20:23 -08001977
Kenny Root07438c82012-11-02 15:41:02 -07001978 if (device->verify_data == NULL) {
1979 return ::SYSTEM_ERROR;
1980 }
Kenny Root70e3a862012-02-15 17:20:23 -08001981
Kenny Root07438c82012-11-02 15:41:02 -07001982 keymaster_rsa_sign_params_t params;
1983 params.digest_type = DIGEST_NONE;
1984 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001985
Kenny Rootb4d2e022013-09-04 13:56:03 -07001986 if (keyBlob.isFallback()) {
1987 rc = openssl_verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1988 dataLength, signature, signatureLength);
1989 } else {
1990 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1991 dataLength, signature, signatureLength);
1992 }
Kenny Root07438c82012-11-02 15:41:02 -07001993 if (rc) {
1994 return ::SYSTEM_ERROR;
1995 } else {
1996 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001997 }
1998 }
Kenny Root07438c82012-11-02 15:41:02 -07001999
2000 /*
2001 * TODO: The abstraction between things stored in hardware and regular blobs
2002 * of data stored on the filesystem should be moved down to keystore itself.
2003 * Unfortunately the Java code that calls this has naming conventions that it
2004 * knows about. Ideally keystore shouldn't be used to store random blobs of
2005 * data.
2006 *
2007 * Until that happens, it's necessary to have a separate "get_pubkey" and
2008 * "del_key" since the Java code doesn't really communicate what it's
2009 * intentions are.
2010 */
2011 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002012 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2013 if (!has_permission(callingUid, P_GET)) {
2014 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002015 return ::PERMISSION_DENIED;
2016 }
Kenny Root07438c82012-11-02 15:41:02 -07002017
Kenny Root07438c82012-11-02 15:41:02 -07002018 Blob keyBlob;
2019 String8 name8(name);
2020
Kenny Rootd38a0b02013-02-13 12:59:14 -08002021 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002022
Kenny Root655b9582013-04-04 08:37:42 -07002023 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002024 TYPE_KEY_PAIR);
2025 if (responseCode != ::NO_ERROR) {
2026 return responseCode;
2027 }
2028
2029 const keymaster_device_t* device = mKeyStore->getDevice();
2030 if (device == NULL) {
2031 return ::SYSTEM_ERROR;
2032 }
2033
2034 if (device->get_keypair_public == NULL) {
2035 ALOGE("device has no get_keypair_public implementation!");
2036 return ::SYSTEM_ERROR;
2037 }
2038
Kenny Rootb4d2e022013-09-04 13:56:03 -07002039 int rc;
2040 if (keyBlob.isFallback()) {
2041 rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2042 pubkeyLength);
2043 } else {
2044 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2045 pubkeyLength);
2046 }
Kenny Root07438c82012-11-02 15:41:02 -07002047 if (rc) {
2048 return ::SYSTEM_ERROR;
2049 }
2050
2051 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002052 }
Kenny Root07438c82012-11-02 15:41:02 -07002053
Kenny Root49468902013-03-19 13:41:33 -07002054 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002055 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2056 if (!has_permission(callingUid, P_DELETE)) {
2057 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002058 return ::PERMISSION_DENIED;
2059 }
Kenny Root07438c82012-11-02 15:41:02 -07002060
Kenny Root49468902013-03-19 13:41:33 -07002061 if (targetUid == -1) {
2062 targetUid = callingUid;
2063 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002064 return ::PERMISSION_DENIED;
2065 }
2066
Kenny Root07438c82012-11-02 15:41:02 -07002067 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002068 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002069
2070 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002071 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
2072 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002073 if (responseCode != ::NO_ERROR) {
2074 return responseCode;
2075 }
2076
2077 ResponseCode rc = ::NO_ERROR;
2078
2079 const keymaster_device_t* device = mKeyStore->getDevice();
2080 if (device == NULL) {
2081 rc = ::SYSTEM_ERROR;
2082 } else {
2083 // A device doesn't have to implement delete_keypair.
Kenny Rootb4d2e022013-09-04 13:56:03 -07002084 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Root07438c82012-11-02 15:41:02 -07002085 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2086 rc = ::SYSTEM_ERROR;
2087 }
2088 }
2089 }
2090
2091 if (rc != ::NO_ERROR) {
2092 return rc;
2093 }
2094
2095 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
2096 }
2097
2098 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002099 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2100 if (!has_permission(callingUid, P_GRANT)) {
2101 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002102 return ::PERMISSION_DENIED;
2103 }
Kenny Root07438c82012-11-02 15:41:02 -07002104
Kenny Root655b9582013-04-04 08:37:42 -07002105 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002106 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002107 ALOGD("calling grant in state: %d", state);
2108 return state;
2109 }
2110
2111 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002112 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002113
Kenny Root655b9582013-04-04 08:37:42 -07002114 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002115 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2116 }
2117
Kenny Root655b9582013-04-04 08:37:42 -07002118 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002119 return ::NO_ERROR;
2120 }
2121
2122 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002123 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2124 if (!has_permission(callingUid, P_GRANT)) {
2125 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002126 return ::PERMISSION_DENIED;
2127 }
Kenny Root07438c82012-11-02 15:41:02 -07002128
Kenny Root655b9582013-04-04 08:37:42 -07002129 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002130 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002131 ALOGD("calling ungrant in state: %d", state);
2132 return state;
2133 }
2134
2135 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002136 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002137
Kenny Root655b9582013-04-04 08:37:42 -07002138 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002139 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2140 }
2141
Kenny Root655b9582013-04-04 08:37:42 -07002142 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002143 }
2144
2145 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002146 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2147 if (!has_permission(callingUid, P_GET)) {
2148 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002149 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002150 }
Kenny Root07438c82012-11-02 15:41:02 -07002151
2152 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002153 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002154
Kenny Root655b9582013-04-04 08:37:42 -07002155 if (access(filename.string(), R_OK) == -1) {
2156 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002157 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002158 }
2159
Kenny Root655b9582013-04-04 08:37:42 -07002160 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002161 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002162 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002163 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002164 }
2165
2166 struct stat s;
2167 int ret = fstat(fd, &s);
2168 close(fd);
2169 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002170 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002171 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002172 }
2173
Kenny Root36a9e232013-02-04 14:24:15 -08002174 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002175 }
2176
Kenny Rootd53bc922013-03-21 14:10:15 -07002177 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2178 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002179 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Rootd53bc922013-03-21 14:10:15 -07002180 if (!has_permission(callingUid, P_DUPLICATE)) {
2181 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002182 return -1L;
2183 }
2184
Kenny Root655b9582013-04-04 08:37:42 -07002185 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002186 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002187 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002188 return state;
2189 }
2190
Kenny Rootd53bc922013-03-21 14:10:15 -07002191 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2192 srcUid = callingUid;
2193 } else if (!is_granted_to(callingUid, srcUid)) {
2194 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002195 return ::PERMISSION_DENIED;
2196 }
2197
Kenny Rootd53bc922013-03-21 14:10:15 -07002198 if (destUid == -1) {
2199 destUid = callingUid;
2200 }
2201
2202 if (srcUid != destUid) {
2203 if (static_cast<uid_t>(srcUid) != callingUid) {
2204 ALOGD("can only duplicate from caller to other or to same uid: "
2205 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2206 return ::PERMISSION_DENIED;
2207 }
2208
2209 if (!is_granted_to(callingUid, destUid)) {
2210 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2211 return ::PERMISSION_DENIED;
2212 }
2213 }
2214
2215 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002216 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002217
Kenny Rootd53bc922013-03-21 14:10:15 -07002218 String8 target8(destKey);
Kenny Root655b9582013-04-04 08:37:42 -07002219 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002220
Kenny Root655b9582013-04-04 08:37:42 -07002221 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2222 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002223 return ::SYSTEM_ERROR;
2224 }
2225
Kenny Rootd53bc922013-03-21 14:10:15 -07002226 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002227 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
2228 callingUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002229 if (responseCode != ::NO_ERROR) {
2230 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002231 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002232
Kenny Root655b9582013-04-04 08:37:42 -07002233 return mKeyStore->put(targetFile.string(), &keyBlob, callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002234 }
2235
Kenny Root70f16c12013-09-05 13:06:32 -07002236 int32_t is_hardware_backed(const String16& keyType) {
2237 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002238 }
2239
Kenny Roota9bb5492013-04-01 16:29:11 -07002240 int32_t clear_uid(int64_t targetUid) {
2241 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2242 if (!has_permission(callingUid, P_CLEAR_UID)) {
2243 ALOGW("permission denied for %d: clear_uid", callingUid);
2244 return ::PERMISSION_DENIED;
2245 }
2246
Kenny Root655b9582013-04-04 08:37:42 -07002247 State state = mKeyStore->getState(callingUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002248 if (!isKeystoreUnlocked(state)) {
2249 ALOGD("calling clear_uid in state: %d", state);
2250 return state;
2251 }
2252
2253 const keymaster_device_t* device = mKeyStore->getDevice();
2254 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002255 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002256 return ::SYSTEM_ERROR;
2257 }
2258
Kenny Root655b9582013-04-04 08:37:42 -07002259 UserState* userState = mKeyStore->getUserState(callingUid);
2260 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota9bb5492013-04-01 16:29:11 -07002261 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07002262 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Roota9bb5492013-04-01 16:29:11 -07002263 return ::SYSTEM_ERROR;
2264 }
2265
Kenny Root655b9582013-04-04 08:37:42 -07002266 char prefix[NAME_MAX];
2267 int n = snprintf(prefix, NAME_MAX, "%u_", static_cast<uid_t>(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002268
2269 ResponseCode rc = ::NO_ERROR;
2270
2271 struct dirent* file;
2272 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002273 // We only care about files.
2274 if (file->d_type != DT_REG) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002275 continue;
2276 }
2277
Kenny Root655b9582013-04-04 08:37:42 -07002278 // Skip anything that starts with a "."
2279 if (file->d_name[0] == '.') {
2280 continue;
2281 }
Kenny Roota9bb5492013-04-01 16:29:11 -07002282
Kenny Root655b9582013-04-04 08:37:42 -07002283 if (strncmp(prefix, file->d_name, n)) {
2284 continue;
2285 }
2286
2287 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Roota9bb5492013-04-01 16:29:11 -07002288 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002289 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, callingUid)
2290 != ::NO_ERROR) {
2291 ALOGW("couldn't open %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002292 continue;
2293 }
2294
2295 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2296 // A device doesn't have to implement delete_keypair.
Kenny Rootb4d2e022013-09-04 13:56:03 -07002297 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002298 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2299 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002300 ALOGW("device couldn't remove %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002301 }
2302 }
2303 }
2304
Kenny Root5f531242013-04-12 11:31:50 -07002305 if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002306 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002307 ALOGW("couldn't unlink %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002308 }
2309 }
2310 closedir(dir);
2311
2312 return rc;
2313 }
2314
Kenny Root07438c82012-11-02 15:41:02 -07002315private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002316 inline bool isKeystoreUnlocked(State state) {
2317 switch (state) {
2318 case ::STATE_NO_ERROR:
2319 return true;
2320 case ::STATE_UNINITIALIZED:
2321 case ::STATE_LOCKED:
2322 return false;
2323 }
2324 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002325 }
2326
2327 ::KeyStore* mKeyStore;
2328};
2329
2330}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002331
2332int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002333 if (argc < 2) {
2334 ALOGE("A directory must be specified!");
2335 return 1;
2336 }
2337 if (chdir(argv[1]) == -1) {
2338 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2339 return 1;
2340 }
2341
2342 Entropy entropy;
2343 if (!entropy.open()) {
2344 return 1;
2345 }
Kenny Root70e3a862012-02-15 17:20:23 -08002346
2347 keymaster_device_t* dev;
2348 if (keymaster_device_initialize(&dev)) {
2349 ALOGE("keystore keymaster could not be initialized; exiting");
2350 return 1;
2351 }
2352
Kenny Root70e3a862012-02-15 17:20:23 -08002353 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002354 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002355 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2356 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2357 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2358 if (ret != android::OK) {
2359 ALOGE("Couldn't register binder service!");
2360 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002361 }
Kenny Root07438c82012-11-02 15:41:02 -07002362
2363 /*
2364 * We're the only thread in existence, so we're just going to process
2365 * Binder transaction as a single-threaded program.
2366 */
2367 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002368
2369 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002370 return 1;
2371}