blob: 64809ad344ac6c3249fb1cf635c8702aa222166b [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 Root17208e02013-09-04 13:56:03 -070045#include <keymaster/softkeymaster.h>
46
Kenny Root655b9582013-04-04 08:37:42 -070047#include <utils/String8.h>
Kenny Root822c3a92012-03-23 16:34:39 -070048#include <utils/UniquePtr.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 Root96427ba2013-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 Root96427ba2013-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 -0700275/*
276 * Converts from the "escaped" format on disk to actual name.
277 * This will be smaller than the input string.
278 *
279 * Characters that should combine with the next at the end will be truncated.
280 */
281static size_t decode_key_length(const char* in, size_t length) {
282 size_t outLength = 0;
283
284 for (const char* end = in + length; in < end; in++) {
285 /* This combines with the next character. */
286 if (*in < '0' || *in > '~') {
287 continue;
288 }
289
290 outLength++;
291 }
292 return outLength;
293}
294
295static void decode_key(char* out, const char* in, size_t length) {
296 for (const char* end = in + length; in < end; in++) {
297 if (*in < '0' || *in > '~') {
298 /* Truncate combining characters at the end. */
299 if (in + 1 >= end) {
300 break;
301 }
302
303 *out = (*in++ - '+') << 6;
304 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800305 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700306 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800307 }
308 }
309 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800310}
311
312static size_t readFully(int fd, uint8_t* data, size_t size) {
313 size_t remaining = size;
314 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800315 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800316 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800317 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800318 }
319 data += n;
320 remaining -= n;
321 }
322 return size;
323}
324
325static size_t writeFully(int fd, uint8_t* data, size_t size) {
326 size_t remaining = size;
327 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800328 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
329 if (n < 0) {
330 ALOGW("write failed: %s", strerror(errno));
331 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800332 }
333 data += n;
334 remaining -= n;
335 }
336 return size;
337}
338
339class Entropy {
340public:
341 Entropy() : mRandom(-1) {}
342 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800343 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800344 close(mRandom);
345 }
346 }
347
348 bool open() {
349 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800350 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
351 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800352 ALOGE("open: %s: %s", randomDevice, strerror(errno));
353 return false;
354 }
355 return true;
356 }
357
Kenny Root51878182012-03-13 12:53:19 -0700358 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800359 return (readFully(mRandom, data, size) == size);
360 }
361
362private:
363 int mRandom;
364};
365
366/* Here is the file format. There are two parts in blob.value, the secret and
367 * the description. The secret is stored in ciphertext, and its original size
368 * can be found in blob.length. The description is stored after the secret in
369 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700370 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700371 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800372 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
373 * and decryptBlob(). Thus they should not be accessed from outside. */
374
Kenny Root822c3a92012-03-23 16:34:39 -0700375/* ** Note to future implementors of encryption: **
376 * Currently this is the construction:
377 * metadata || Enc(MD5(data) || data)
378 *
379 * This should be the construction used for encrypting if re-implementing:
380 *
381 * Derive independent keys for encryption and MAC:
382 * Kenc = AES_encrypt(masterKey, "Encrypt")
383 * Kmac = AES_encrypt(masterKey, "MAC")
384 *
385 * Store this:
386 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
387 * HMAC(Kmac, metadata || Enc(data))
388 */
Kenny Roota91203b2012-02-15 15:00:46 -0800389struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700390 uint8_t version;
391 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700392 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800393 uint8_t info;
394 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700395 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800396 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700397 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800398 int32_t length; // in network byte order when encrypted
399 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
400};
401
Kenny Root822c3a92012-03-23 16:34:39 -0700402typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700403 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700404 TYPE_GENERIC = 1,
405 TYPE_MASTER_KEY = 2,
406 TYPE_KEY_PAIR = 3,
407} BlobType;
408
Kenny Rootf9119d62013-04-03 09:22:15 -0700409static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700410
Kenny Roota91203b2012-02-15 15:00:46 -0800411class Blob {
412public:
Chad Brubakerb124c9e2015-07-29 13:53:36 -0700413 Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
Kenny Root07438c82012-11-02 15:41:02 -0700414 BlobType type) {
Chad Brubaker0d593522015-08-12 13:40:31 -0700415 if (valueLength > VALUE_SIZE) {
416 valueLength = VALUE_SIZE;
Chad Brubakerb124c9e2015-07-29 13:53:36 -0700417 ALOGW("Provided blob length too large");
418 }
Chad Brubaker0d593522015-08-12 13:40:31 -0700419 if (infoLength + valueLength > VALUE_SIZE) {
420 infoLength = VALUE_SIZE - valueLength;
Chad Brubakerb124c9e2015-07-29 13:53:36 -0700421 ALOGW("Provided info length too large");
422 }
Kenny Roota91203b2012-02-15 15:00:46 -0800423 mBlob.length = valueLength;
424 memcpy(mBlob.value, value, valueLength);
425
426 mBlob.info = infoLength;
427 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700428
Kenny Root07438c82012-11-02 15:41:02 -0700429 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700430 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700431
Kenny Rootee8068b2013-10-07 09:49:15 -0700432 if (type == TYPE_MASTER_KEY) {
433 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
434 } else {
435 mBlob.flags = KEYSTORE_FLAG_NONE;
436 }
Kenny Roota91203b2012-02-15 15:00:46 -0800437 }
438
439 Blob(blob b) {
440 mBlob = b;
441 }
442
443 Blob() {}
444
Kenny Root51878182012-03-13 12:53:19 -0700445 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800446 return mBlob.value;
447 }
448
Kenny Root51878182012-03-13 12:53:19 -0700449 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800450 return mBlob.length;
451 }
452
Kenny Root51878182012-03-13 12:53:19 -0700453 const uint8_t* getInfo() const {
454 return mBlob.value + mBlob.length;
455 }
456
457 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800458 return mBlob.info;
459 }
460
Kenny Root822c3a92012-03-23 16:34:39 -0700461 uint8_t getVersion() const {
462 return mBlob.version;
463 }
464
Kenny Rootf9119d62013-04-03 09:22:15 -0700465 bool isEncrypted() const {
466 if (mBlob.version < 2) {
467 return true;
468 }
469
470 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
471 }
472
473 void setEncrypted(bool encrypted) {
474 if (encrypted) {
475 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
476 } else {
477 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
478 }
479 }
480
Kenny Root17208e02013-09-04 13:56:03 -0700481 bool isFallback() const {
482 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
483 }
484
485 void setFallback(bool fallback) {
486 if (fallback) {
487 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
488 } else {
489 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
490 }
491 }
492
Kenny Root822c3a92012-03-23 16:34:39 -0700493 void setVersion(uint8_t version) {
494 mBlob.version = version;
495 }
496
497 BlobType getType() const {
498 return BlobType(mBlob.type);
499 }
500
501 void setType(BlobType type) {
502 mBlob.type = uint8_t(type);
503 }
504
Kenny Rootf9119d62013-04-03 09:22:15 -0700505 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
506 ALOGV("writing blob %s", filename);
507 if (isEncrypted()) {
508 if (state != STATE_NO_ERROR) {
509 ALOGD("couldn't insert encrypted blob while not unlocked");
510 return LOCKED;
511 }
512
513 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
514 ALOGW("Could not read random data for: %s", filename);
515 return SYSTEM_ERROR;
516 }
Kenny Roota91203b2012-02-15 15:00:46 -0800517 }
518
519 // data includes the value and the value's length
520 size_t dataLength = mBlob.length + sizeof(mBlob.length);
521 // pad data to the AES_BLOCK_SIZE
522 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
523 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
524 // encrypted data includes the digest value
525 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
526 // move info after space for padding
527 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
528 // zero padding area
529 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
530
531 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800532
Kenny Rootf9119d62013-04-03 09:22:15 -0700533 if (isEncrypted()) {
534 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800535
Kenny Rootf9119d62013-04-03 09:22:15 -0700536 uint8_t vector[AES_BLOCK_SIZE];
537 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
538 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
539 aes_key, vector, AES_ENCRYPT);
540 }
541
Kenny Roota91203b2012-02-15 15:00:46 -0800542 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
543 size_t fileLength = encryptedLength + headerLength + mBlob.info;
544
545 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800546 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
547 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
548 if (out < 0) {
549 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800550 return SYSTEM_ERROR;
551 }
552 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
553 if (close(out) != 0) {
554 return SYSTEM_ERROR;
555 }
556 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800557 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800558 unlink(tmpFileName);
559 return SYSTEM_ERROR;
560 }
Kenny Root150ca932012-11-14 14:29:02 -0800561 if (rename(tmpFileName, filename) == -1) {
562 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
563 return SYSTEM_ERROR;
564 }
565 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800566 }
567
Kenny Rootf9119d62013-04-03 09:22:15 -0700568 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
569 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800570 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
571 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800572 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
573 }
574 // fileLength may be less than sizeof(mBlob) since the in
575 // memory version has extra padding to tolerate rounding up to
576 // the AES_BLOCK_SIZE
577 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
578 if (close(in) != 0) {
579 return SYSTEM_ERROR;
580 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700581
582 if (isEncrypted() && (state != STATE_NO_ERROR)) {
583 return LOCKED;
584 }
585
Kenny Roota91203b2012-02-15 15:00:46 -0800586 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
587 if (fileLength < headerLength) {
588 return VALUE_CORRUPTED;
589 }
590
591 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700592 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800593 return VALUE_CORRUPTED;
594 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700595
596 ssize_t digestedLength;
597 if (isEncrypted()) {
598 if (encryptedLength % AES_BLOCK_SIZE != 0) {
599 return VALUE_CORRUPTED;
600 }
601
602 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
603 mBlob.vector, AES_DECRYPT);
604 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
605 uint8_t computedDigest[MD5_DIGEST_LENGTH];
606 MD5(mBlob.digested, digestedLength, computedDigest);
607 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
608 return VALUE_CORRUPTED;
609 }
610 } else {
611 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800612 }
613
614 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
615 mBlob.length = ntohl(mBlob.length);
616 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
617 return VALUE_CORRUPTED;
618 }
619 if (mBlob.info != 0) {
620 // move info from after padding to after data
621 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
622 }
Kenny Root07438c82012-11-02 15:41:02 -0700623 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800624 }
625
626private:
627 struct blob mBlob;
628};
629
Kenny Root655b9582013-04-04 08:37:42 -0700630class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800631public:
Kenny Root655b9582013-04-04 08:37:42 -0700632 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
633 asprintf(&mUserDir, "user_%u", mUserId);
634 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
635 }
636
637 ~UserState() {
638 free(mUserDir);
639 free(mMasterKeyFile);
640 }
641
642 bool initialize() {
643 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
644 ALOGE("Could not create directory '%s'", mUserDir);
645 return false;
646 }
647
648 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800649 setState(STATE_LOCKED);
650 } else {
651 setState(STATE_UNINITIALIZED);
652 }
Kenny Root70e3a862012-02-15 17:20:23 -0800653
Kenny Root655b9582013-04-04 08:37:42 -0700654 return true;
655 }
656
657 uid_t getUserId() const {
658 return mUserId;
659 }
660
661 const char* getUserDirName() const {
662 return mUserDir;
663 }
664
665 const char* getMasterKeyFileName() const {
666 return mMasterKeyFile;
667 }
668
669 void setState(State state) {
670 mState = state;
671 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
672 mRetry = MAX_RETRY;
673 }
Kenny Roota91203b2012-02-15 15:00:46 -0800674 }
675
Kenny Root51878182012-03-13 12:53:19 -0700676 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800677 return mState;
678 }
679
Kenny Root51878182012-03-13 12:53:19 -0700680 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800681 return mRetry;
682 }
683
Kenny Root655b9582013-04-04 08:37:42 -0700684 void zeroizeMasterKeysInMemory() {
685 memset(mMasterKey, 0, sizeof(mMasterKey));
686 memset(mSalt, 0, sizeof(mSalt));
687 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
688 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800689 }
690
Kenny Root655b9582013-04-04 08:37:42 -0700691 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
692 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800693 return SYSTEM_ERROR;
694 }
Kenny Root655b9582013-04-04 08:37:42 -0700695 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800696 if (response != NO_ERROR) {
697 return response;
698 }
699 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700700 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800701 }
702
Kenny Root655b9582013-04-04 08:37:42 -0700703 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800704 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
705 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
706 AES_KEY passwordAesKey;
707 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700708 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700709 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800710 }
711
Kenny Root655b9582013-04-04 08:37:42 -0700712 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
713 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800714 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800715 return SYSTEM_ERROR;
716 }
717
718 // we read the raw blob to just to get the salt to generate
719 // the AES key, then we create the Blob to use with decryptBlob
720 blob rawBlob;
721 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
722 if (close(in) != 0) {
723 return SYSTEM_ERROR;
724 }
725 // find salt at EOF if present, otherwise we have an old file
726 uint8_t* salt;
727 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
728 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
729 } else {
730 salt = NULL;
731 }
732 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
733 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
734 AES_KEY passwordAesKey;
735 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
736 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700737 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
738 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800739 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700740 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800741 }
742 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
743 // if salt was missing, generate one and write a new master key file with the salt.
744 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700745 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800746 return SYSTEM_ERROR;
747 }
Kenny Root655b9582013-04-04 08:37:42 -0700748 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800749 }
750 if (response == NO_ERROR) {
751 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
752 setupMasterKeys();
753 }
754 return response;
755 }
756 if (mRetry <= 0) {
757 reset();
758 return UNINITIALIZED;
759 }
760 --mRetry;
761 switch (mRetry) {
762 case 0: return WRONG_PASSWORD_0;
763 case 1: return WRONG_PASSWORD_1;
764 case 2: return WRONG_PASSWORD_2;
765 case 3: return WRONG_PASSWORD_3;
766 default: return WRONG_PASSWORD_3;
767 }
768 }
769
Kenny Root655b9582013-04-04 08:37:42 -0700770 AES_KEY* getEncryptionKey() {
771 return &mMasterKeyEncryption;
772 }
773
774 AES_KEY* getDecryptionKey() {
775 return &mMasterKeyDecryption;
776 }
777
Kenny Roota91203b2012-02-15 15:00:46 -0800778 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700779 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800780 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700781 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800782 return false;
783 }
Kenny Root655b9582013-04-04 08:37:42 -0700784
785 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800786 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700787 // We only care about files.
788 if (file->d_type != DT_REG) {
789 continue;
790 }
791
792 // Skip anything that starts with a "."
793 if (file->d_name[0] == '.') {
794 continue;
795 }
796
797 // Find the current file's UID.
798 char* end;
799 unsigned long thisUid = strtoul(file->d_name, &end, 10);
800 if (end[0] != '_' || end[1] == 0) {
801 continue;
802 }
803
804 // Skip if this is not our user.
805 if (get_user_id(thisUid) != mUserId) {
806 continue;
807 }
808
809 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800810 }
811 closedir(dir);
812 return true;
813 }
814
Kenny Root655b9582013-04-04 08:37:42 -0700815private:
816 static const int MASTER_KEY_SIZE_BYTES = 16;
817 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
818
819 static const int MAX_RETRY = 4;
820 static const size_t SALT_SIZE = 16;
821
822 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
823 uint8_t* salt) {
824 size_t saltSize;
825 if (salt != NULL) {
826 saltSize = SALT_SIZE;
827 } else {
828 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
829 salt = (uint8_t*) "keystore";
830 // sizeof = 9, not strlen = 8
831 saltSize = sizeof("keystore");
832 }
833
834 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
835 saltSize, 8192, keySize, key);
836 }
837
838 bool generateSalt(Entropy* entropy) {
839 return entropy->generate_random_data(mSalt, sizeof(mSalt));
840 }
841
842 bool generateMasterKey(Entropy* entropy) {
843 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
844 return false;
845 }
846 if (!generateSalt(entropy)) {
847 return false;
848 }
849 return true;
850 }
851
852 void setupMasterKeys() {
853 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
854 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
855 setState(STATE_NO_ERROR);
856 }
857
858 uid_t mUserId;
859
860 char* mUserDir;
861 char* mMasterKeyFile;
862
863 State mState;
864 int8_t mRetry;
865
866 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
867 uint8_t mSalt[SALT_SIZE];
868
869 AES_KEY mMasterKeyEncryption;
870 AES_KEY mMasterKeyDecryption;
871};
872
873typedef struct {
874 uint32_t uid;
875 const uint8_t* filename;
876} grant_t;
877
878class KeyStore {
879public:
880 KeyStore(Entropy* entropy, keymaster_device_t* device)
881 : mEntropy(entropy)
882 , mDevice(device)
883 {
884 memset(&mMetaData, '\0', sizeof(mMetaData));
885 }
886
887 ~KeyStore() {
888 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
889 it != mGrants.end(); it++) {
890 delete *it;
891 mGrants.erase(it);
892 }
893
894 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
895 it != mMasterKeys.end(); it++) {
896 delete *it;
897 mMasterKeys.erase(it);
898 }
899 }
900
901 keymaster_device_t* getDevice() const {
902 return mDevice;
903 }
904
905 ResponseCode initialize() {
906 readMetaData();
907 if (upgradeKeystore()) {
908 writeMetaData();
909 }
910
911 return ::NO_ERROR;
912 }
913
914 State getState(uid_t uid) {
915 return getUserState(uid)->getState();
916 }
917
918 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
919 UserState* userState = getUserState(uid);
920 return userState->initialize(pw, mEntropy);
921 }
922
923 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
924 uid_t user_id = get_user_id(uid);
925 UserState* userState = getUserState(user_id);
926 return userState->writeMasterKey(pw, mEntropy);
927 }
928
929 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
930 uid_t user_id = get_user_id(uid);
931 UserState* userState = getUserState(user_id);
932 return userState->readMasterKey(pw, mEntropy);
933 }
934
935 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700936 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700937 encode_key(encoded, keyName);
938 return android::String8(encoded);
939 }
940
941 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700942 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700943 encode_key(encoded, keyName);
944 return android::String8::format("%u_%s", uid, encoded);
945 }
946
947 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700948 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700949 encode_key(encoded, keyName);
950 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
951 encoded);
952 }
953
954 bool reset(uid_t uid) {
955 UserState* userState = getUserState(uid);
956 userState->zeroizeMasterKeysInMemory();
957 userState->setState(STATE_UNINITIALIZED);
958 return userState->reset();
959 }
960
961 bool isEmpty(uid_t uid) const {
962 const UserState* userState = getUserState(uid);
963 if (userState == NULL) {
964 return true;
965 }
966
967 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800968 struct dirent* file;
969 if (!dir) {
970 return true;
971 }
972 bool result = true;
Kenny Root655b9582013-04-04 08:37:42 -0700973
974 char filename[NAME_MAX];
975 int n = snprintf(filename, sizeof(filename), "%u_", uid);
976
Kenny Roota91203b2012-02-15 15:00:46 -0800977 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700978 // We only care about files.
979 if (file->d_type != DT_REG) {
980 continue;
981 }
982
983 // Skip anything that starts with a "."
984 if (file->d_name[0] == '.') {
985 continue;
986 }
987
988 if (!strncmp(file->d_name, filename, n)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800989 result = false;
990 break;
991 }
992 }
993 closedir(dir);
994 return result;
995 }
996
Kenny Root655b9582013-04-04 08:37:42 -0700997 void lock(uid_t uid) {
998 UserState* userState = getUserState(uid);
999 userState->zeroizeMasterKeysInMemory();
1000 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001001 }
1002
Kenny Root655b9582013-04-04 08:37:42 -07001003 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1004 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001005 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1006 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001007 if (rc != NO_ERROR) {
1008 return rc;
1009 }
1010
1011 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001012 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001013 /* If we upgrade the key, we need to write it to disk again. Then
1014 * it must be read it again since the blob is encrypted each time
1015 * it's written.
1016 */
Kenny Root655b9582013-04-04 08:37:42 -07001017 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1018 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001019 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1020 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001021 return rc;
1022 }
1023 }
Kenny Root822c3a92012-03-23 16:34:39 -07001024 }
1025
Kenny Root17208e02013-09-04 13:56:03 -07001026 /*
1027 * This will upgrade software-backed keys to hardware-backed keys when
1028 * the HAL for the device supports the newer key types.
1029 */
1030 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1031 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1032 && keyBlob->isFallback()) {
1033 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1034 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1035
1036 // The HAL allowed the import, reget the key to have the "fresh"
1037 // version.
1038 if (imported == NO_ERROR) {
1039 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1040 }
1041 }
1042
Kenny Rootd53bc922013-03-21 14:10:15 -07001043 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001044 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1045 return KEY_NOT_FOUND;
1046 }
1047
1048 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001049 }
1050
Kenny Root655b9582013-04-04 08:37:42 -07001051 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1052 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001053 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1054 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001055 }
1056
Kenny Root07438c82012-11-02 15:41:02 -07001057 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001058 const grant_t* existing = getGrant(filename, granteeUid);
1059 if (existing == NULL) {
1060 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001061 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001062 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001063 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001064 }
1065 }
1066
Kenny Root07438c82012-11-02 15:41:02 -07001067 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001068 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1069 it != mGrants.end(); it++) {
1070 grant_t* grant = *it;
1071 if (grant->uid == granteeUid
1072 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1073 mGrants.erase(it);
1074 return true;
1075 }
Kenny Root70e3a862012-02-15 17:20:23 -08001076 }
Kenny Root70e3a862012-02-15 17:20:23 -08001077 return false;
1078 }
1079
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001080 bool hasGrant(const char* filename, const uid_t uid) const {
1081 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001082 }
1083
Kenny Rootf9119d62013-04-03 09:22:15 -07001084 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1085 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001086 uint8_t* data;
1087 size_t dataLength;
1088 int rc;
1089
1090 if (mDevice->import_keypair == NULL) {
1091 ALOGE("Keymaster doesn't support import!");
1092 return SYSTEM_ERROR;
1093 }
1094
Kenny Root17208e02013-09-04 13:56:03 -07001095 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001096 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001097 if (rc) {
Kenny Root17208e02013-09-04 13:56:03 -07001098 // If this is an old device HAL, try to fall back to an old version
1099 if (mDevice->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_2) {
1100 rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength);
1101 isFallback = true;
1102 }
1103
1104 if (rc) {
1105 ALOGE("Error while importing keypair: %d", rc);
1106 return SYSTEM_ERROR;
1107 }
Kenny Root822c3a92012-03-23 16:34:39 -07001108 }
1109
1110 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1111 free(data);
1112
Kenny Rootf9119d62013-04-03 09:22:15 -07001113 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001114 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001115
Kenny Root655b9582013-04-04 08:37:42 -07001116 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001117 }
1118
Kenny Root1b0e3932013-09-05 13:06:32 -07001119 bool isHardwareBacked(const android::String16& keyType) const {
1120 if (mDevice == NULL) {
1121 ALOGW("can't get keymaster device");
1122 return false;
1123 }
1124
1125 if (sRSAKeyType == keyType) {
1126 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1127 } else {
1128 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1129 && (mDevice->common.module->module_api_version
1130 >= KEYMASTER_MODULE_API_VERSION_0_2);
1131 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001132 }
1133
Kenny Root655b9582013-04-04 08:37:42 -07001134 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1135 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001136 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001137
1138 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1139 if (responseCode == NO_ERROR) {
1140 return responseCode;
1141 }
1142
1143 // If this is one of the legacy UID->UID mappings, use it.
1144 uid_t euid = get_keystore_euid(uid);
1145 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001146 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001147 responseCode = get(filepath8.string(), keyBlob, type, uid);
1148 if (responseCode == NO_ERROR) {
1149 return responseCode;
1150 }
1151 }
1152
1153 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001154 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001155 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001156 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001157 if (end[0] != '_' || end[1] == 0) {
1158 return KEY_NOT_FOUND;
1159 }
Kenny Root86b16e82013-09-09 11:15:54 -07001160 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1161 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001162 if (!hasGrant(filepath8.string(), uid)) {
1163 return responseCode;
1164 }
1165
1166 // It is a granted key. Try to load it.
1167 return get(filepath8.string(), keyBlob, type, uid);
1168 }
1169
1170 /**
1171 * Returns any existing UserState or creates it if it doesn't exist.
1172 */
1173 UserState* getUserState(uid_t uid) {
1174 uid_t userId = get_user_id(uid);
1175
1176 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1177 it != mMasterKeys.end(); it++) {
1178 UserState* state = *it;
1179 if (state->getUserId() == userId) {
1180 return state;
1181 }
1182 }
1183
1184 UserState* userState = new UserState(userId);
1185 if (!userState->initialize()) {
1186 /* There's not much we can do if initialization fails. Trying to
1187 * unlock the keystore for that user will fail as well, so any
1188 * subsequent request for this user will just return SYSTEM_ERROR.
1189 */
1190 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1191 }
1192 mMasterKeys.add(userState);
1193 return userState;
1194 }
1195
1196 /**
1197 * Returns NULL if the UserState doesn't already exist.
1198 */
1199 const UserState* getUserState(uid_t uid) const {
1200 uid_t userId = get_user_id(uid);
1201
1202 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1203 it != mMasterKeys.end(); it++) {
1204 UserState* state = *it;
1205 if (state->getUserId() == userId) {
1206 return state;
1207 }
1208 }
1209
1210 return NULL;
1211 }
1212
Kenny Roota91203b2012-02-15 15:00:46 -08001213private:
Kenny Root655b9582013-04-04 08:37:42 -07001214 static const char* sOldMasterKey;
1215 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001216 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001217 Entropy* mEntropy;
1218
Kenny Root70e3a862012-02-15 17:20:23 -08001219 keymaster_device_t* mDevice;
1220
Kenny Root655b9582013-04-04 08:37:42 -07001221 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001222
Kenny Root655b9582013-04-04 08:37:42 -07001223 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001224
Kenny Root655b9582013-04-04 08:37:42 -07001225 typedef struct {
1226 uint32_t version;
1227 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001228
Kenny Root655b9582013-04-04 08:37:42 -07001229 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001230
Kenny Root655b9582013-04-04 08:37:42 -07001231 const grant_t* getGrant(const char* filename, uid_t uid) const {
1232 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1233 it != mGrants.end(); it++) {
1234 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001235 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001236 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001237 return grant;
1238 }
1239 }
Kenny Root70e3a862012-02-15 17:20:23 -08001240 return NULL;
1241 }
1242
Kenny Root822c3a92012-03-23 16:34:39 -07001243 /**
1244 * Upgrade code. This will upgrade the key from the current version
1245 * to whatever is newest.
1246 */
Kenny Root655b9582013-04-04 08:37:42 -07001247 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1248 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001249 bool updated = false;
1250 uint8_t version = oldVersion;
1251
1252 /* From V0 -> V1: All old types were unknown */
1253 if (version == 0) {
1254 ALOGV("upgrading to version 1 and setting type %d", type);
1255
1256 blob->setType(type);
1257 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001258 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001259 }
1260 version = 1;
1261 updated = true;
1262 }
1263
Kenny Rootf9119d62013-04-03 09:22:15 -07001264 /* From V1 -> V2: All old keys were encrypted */
1265 if (version == 1) {
1266 ALOGV("upgrading to version 2");
1267
1268 blob->setEncrypted(true);
1269 version = 2;
1270 updated = true;
1271 }
1272
Kenny Root822c3a92012-03-23 16:34:39 -07001273 /*
1274 * If we've updated, set the key blob to the right version
1275 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001276 */
Kenny Root822c3a92012-03-23 16:34:39 -07001277 if (updated) {
1278 ALOGV("updated and writing file %s", filename);
1279 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001280 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001281
1282 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001283 }
1284
1285 /**
1286 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1287 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1288 * Then it overwrites the original blob with the new blob
1289 * format that is returned from the keymaster.
1290 */
Kenny Root655b9582013-04-04 08:37:42 -07001291 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001292 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1293 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1294 if (b.get() == NULL) {
1295 ALOGE("Problem instantiating BIO");
1296 return SYSTEM_ERROR;
1297 }
1298
1299 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1300 if (pkey.get() == NULL) {
1301 ALOGE("Couldn't read old PEM file");
1302 return SYSTEM_ERROR;
1303 }
1304
1305 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1306 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1307 if (len < 0) {
1308 ALOGE("Couldn't measure PKCS#8 length");
1309 return SYSTEM_ERROR;
1310 }
1311
Kenny Root70c98892013-02-07 09:10:36 -08001312 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1313 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001314 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1315 ALOGE("Couldn't convert to PKCS#8");
1316 return SYSTEM_ERROR;
1317 }
1318
Kenny Rootf9119d62013-04-03 09:22:15 -07001319 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1320 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001321 if (rc != NO_ERROR) {
1322 return rc;
1323 }
1324
Kenny Root655b9582013-04-04 08:37:42 -07001325 return get(filename, blob, TYPE_KEY_PAIR, uid);
1326 }
1327
1328 void readMetaData() {
1329 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1330 if (in < 0) {
1331 return;
1332 }
1333 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1334 if (fileLength != sizeof(mMetaData)) {
1335 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1336 sizeof(mMetaData));
1337 }
1338 close(in);
1339 }
1340
1341 void writeMetaData() {
1342 const char* tmpFileName = ".metadata.tmp";
1343 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1344 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1345 if (out < 0) {
1346 ALOGE("couldn't write metadata file: %s", strerror(errno));
1347 return;
1348 }
1349 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1350 if (fileLength != sizeof(mMetaData)) {
1351 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1352 sizeof(mMetaData));
1353 }
1354 close(out);
1355 rename(tmpFileName, sMetaDataFile);
1356 }
1357
1358 bool upgradeKeystore() {
1359 bool upgraded = false;
1360
1361 if (mMetaData.version == 0) {
1362 UserState* userState = getUserState(0);
1363
1364 // Initialize first so the directory is made.
1365 userState->initialize();
1366
1367 // Migrate the old .masterkey file to user 0.
1368 if (access(sOldMasterKey, R_OK) == 0) {
1369 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1370 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1371 return false;
1372 }
1373 }
1374
1375 // Initialize again in case we had a key.
1376 userState->initialize();
1377
1378 // Try to migrate existing keys.
1379 DIR* dir = opendir(".");
1380 if (!dir) {
1381 // Give up now; maybe we can upgrade later.
1382 ALOGE("couldn't open keystore's directory; something is wrong");
1383 return false;
1384 }
1385
1386 struct dirent* file;
1387 while ((file = readdir(dir)) != NULL) {
1388 // We only care about files.
1389 if (file->d_type != DT_REG) {
1390 continue;
1391 }
1392
1393 // Skip anything that starts with a "."
1394 if (file->d_name[0] == '.') {
1395 continue;
1396 }
1397
1398 // Find the current file's user.
1399 char* end;
1400 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1401 if (end[0] != '_' || end[1] == 0) {
1402 continue;
1403 }
1404 UserState* otherUser = getUserState(thisUid);
1405 if (otherUser->getUserId() != 0) {
1406 unlinkat(dirfd(dir), file->d_name, 0);
1407 }
1408
1409 // Rename the file into user directory.
1410 DIR* otherdir = opendir(otherUser->getUserDirName());
1411 if (otherdir == NULL) {
1412 ALOGW("couldn't open user directory for rename");
1413 continue;
1414 }
1415 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1416 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1417 }
1418 closedir(otherdir);
1419 }
1420 closedir(dir);
1421
1422 mMetaData.version = 1;
1423 upgraded = true;
1424 }
1425
1426 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001427 }
Kenny Roota91203b2012-02-15 15:00:46 -08001428};
1429
Kenny Root655b9582013-04-04 08:37:42 -07001430const char* KeyStore::sOldMasterKey = ".masterkey";
1431const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001432
Kenny Root1b0e3932013-09-05 13:06:32 -07001433const android::String16 KeyStore::sRSAKeyType("RSA");
1434
Kenny Root07438c82012-11-02 15:41:02 -07001435namespace android {
1436class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1437public:
1438 KeyStoreProxy(KeyStore* keyStore)
1439 : mKeyStore(keyStore)
1440 {
Kenny Roota91203b2012-02-15 15:00:46 -08001441 }
Kenny Roota91203b2012-02-15 15:00:46 -08001442
Kenny Root07438c82012-11-02 15:41:02 -07001443 void binderDied(const wp<IBinder>&) {
1444 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001445 }
Kenny Roota91203b2012-02-15 15:00:46 -08001446
Kenny Root07438c82012-11-02 15:41:02 -07001447 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001448 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1449 if (!has_permission(callingUid, P_TEST)) {
1450 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001451 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001452 }
Kenny Roota91203b2012-02-15 15:00:46 -08001453
Kenny Root655b9582013-04-04 08:37:42 -07001454 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001455 }
1456
Kenny Root07438c82012-11-02 15:41:02 -07001457 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001458 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1459 if (!has_permission(callingUid, P_GET)) {
1460 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001461 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001462 }
Kenny Root07438c82012-11-02 15:41:02 -07001463
Kenny Root07438c82012-11-02 15:41:02 -07001464 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001465 Blob keyBlob;
Kenny Root49468902013-03-19 13:41:33 -07001466
Kenny Root655b9582013-04-04 08:37:42 -07001467 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001468 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001469 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001470 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001471 *item = NULL;
1472 *itemLength = 0;
1473 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001474 }
Kenny Roota91203b2012-02-15 15:00:46 -08001475
Kenny Root07438c82012-11-02 15:41:02 -07001476 *item = (uint8_t*) malloc(keyBlob.getLength());
1477 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1478 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001479
Kenny Root07438c82012-11-02 15:41:02 -07001480 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001481 }
1482
Kenny Rootf9119d62013-04-03 09:22:15 -07001483 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1484 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001485 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1486 if (!has_permission(callingUid, P_INSERT)) {
1487 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001488 return ::PERMISSION_DENIED;
1489 }
Kenny Root07438c82012-11-02 15:41:02 -07001490
Kenny Rootf9119d62013-04-03 09:22:15 -07001491 State state = mKeyStore->getState(callingUid);
1492 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1493 ALOGD("calling get in state: %d", state);
1494 return state;
1495 }
1496
Kenny Root49468902013-03-19 13:41:33 -07001497 if (targetUid == -1) {
1498 targetUid = callingUid;
1499 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001500 return ::PERMISSION_DENIED;
1501 }
1502
Kenny Root07438c82012-11-02 15:41:02 -07001503 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001504 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001505
1506 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001507 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1508
Kenny Root655b9582013-04-04 08:37:42 -07001509 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001510 }
1511
Kenny Root49468902013-03-19 13:41:33 -07001512 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001513 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1514 if (!has_permission(callingUid, P_DELETE)) {
1515 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001516 return ::PERMISSION_DENIED;
1517 }
Kenny Root70e3a862012-02-15 17:20:23 -08001518
Kenny Root49468902013-03-19 13:41:33 -07001519 if (targetUid == -1) {
1520 targetUid = callingUid;
1521 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001522 return ::PERMISSION_DENIED;
1523 }
1524
Kenny Root07438c82012-11-02 15:41:02 -07001525 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001526 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001527
1528 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001529 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
1530 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001531 if (responseCode != ::NO_ERROR) {
1532 return responseCode;
1533 }
1534 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001535 }
1536
Kenny Root49468902013-03-19 13:41:33 -07001537 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001538 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1539 if (!has_permission(callingUid, P_EXIST)) {
1540 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001541 return ::PERMISSION_DENIED;
1542 }
Kenny Root70e3a862012-02-15 17:20:23 -08001543
Kenny Root49468902013-03-19 13:41:33 -07001544 if (targetUid == -1) {
1545 targetUid = callingUid;
1546 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001547 return ::PERMISSION_DENIED;
1548 }
1549
Kenny Root07438c82012-11-02 15:41:02 -07001550 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001551 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001552
Kenny Root655b9582013-04-04 08:37:42 -07001553 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001554 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1555 }
1556 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001557 }
1558
Kenny Root49468902013-03-19 13:41:33 -07001559 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001560 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1561 if (!has_permission(callingUid, P_SAW)) {
1562 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001563 return ::PERMISSION_DENIED;
1564 }
Kenny Root70e3a862012-02-15 17:20:23 -08001565
Kenny Root49468902013-03-19 13:41:33 -07001566 if (targetUid == -1) {
1567 targetUid = callingUid;
1568 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001569 return ::PERMISSION_DENIED;
1570 }
1571
Kenny Root655b9582013-04-04 08:37:42 -07001572 UserState* userState = mKeyStore->getUserState(targetUid);
1573 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001574 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07001575 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001576 return ::SYSTEM_ERROR;
1577 }
Kenny Root70e3a862012-02-15 17:20:23 -08001578
Kenny Root07438c82012-11-02 15:41:02 -07001579 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001580 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1581 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001582
Kenny Root07438c82012-11-02 15:41:02 -07001583 struct dirent* file;
1584 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001585 // We only care about files.
1586 if (file->d_type != DT_REG) {
1587 continue;
1588 }
1589
1590 // Skip anything that starts with a "."
1591 if (file->d_name[0] == '.') {
1592 continue;
1593 }
1594
1595 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001596 const char* p = &file->d_name[n];
1597 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001598
Kenny Root07438c82012-11-02 15:41:02 -07001599 size_t extra = decode_key_length(p, plen);
1600 char *match = (char*) malloc(extra + 1);
1601 if (match != NULL) {
1602 decode_key(match, p, plen);
1603 matches->push(String16(match, extra));
1604 free(match);
1605 } else {
1606 ALOGW("could not allocate match of size %zd", extra);
1607 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001608 }
1609 }
Kenny Root07438c82012-11-02 15:41:02 -07001610 closedir(dir);
1611
1612 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001613 }
1614
Kenny Root07438c82012-11-02 15:41:02 -07001615 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001616 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1617 if (!has_permission(callingUid, P_RESET)) {
1618 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001619 return ::PERMISSION_DENIED;
1620 }
1621
Kenny Root655b9582013-04-04 08:37:42 -07001622 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001623
1624 const keymaster_device_t* device = mKeyStore->getDevice();
1625 if (device == NULL) {
1626 ALOGE("No keymaster device!");
1627 return ::SYSTEM_ERROR;
1628 }
1629
1630 if (device->delete_all == NULL) {
1631 ALOGV("keymaster device doesn't implement delete_all");
1632 return rc;
1633 }
1634
1635 if (device->delete_all(device)) {
1636 ALOGE("Problem calling keymaster's delete_all");
1637 return ::SYSTEM_ERROR;
1638 }
1639
Kenny Root9a53d3e2012-08-14 10:47:54 -07001640 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001641 }
1642
Kenny Root07438c82012-11-02 15:41:02 -07001643 /*
1644 * Here is the history. To improve the security, the parameters to generate the
1645 * master key has been changed. To make a seamless transition, we update the
1646 * file using the same password when the user unlock it for the first time. If
1647 * any thing goes wrong during the transition, the new file will not overwrite
1648 * the old one. This avoids permanent damages of the existing data.
1649 */
1650 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001651 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1652 if (!has_permission(callingUid, P_PASSWORD)) {
1653 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001654 return ::PERMISSION_DENIED;
1655 }
Kenny Root70e3a862012-02-15 17:20:23 -08001656
Kenny Root07438c82012-11-02 15:41:02 -07001657 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001658
Kenny Root655b9582013-04-04 08:37:42 -07001659 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001660 case ::STATE_UNINITIALIZED: {
1661 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001662 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001663 }
1664 case ::STATE_NO_ERROR: {
1665 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001666 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001667 }
1668 case ::STATE_LOCKED: {
1669 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001670 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001671 }
1672 }
1673 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001674 }
1675
Kenny Root07438c82012-11-02 15:41:02 -07001676 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001677 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1678 if (!has_permission(callingUid, P_LOCK)) {
1679 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001680 return ::PERMISSION_DENIED;
1681 }
Kenny Root70e3a862012-02-15 17:20:23 -08001682
Kenny Root655b9582013-04-04 08:37:42 -07001683 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001684 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001685 ALOGD("calling lock in state: %d", state);
1686 return state;
1687 }
1688
Kenny Root655b9582013-04-04 08:37:42 -07001689 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001690 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001691 }
1692
Kenny Root07438c82012-11-02 15:41:02 -07001693 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001694 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1695 if (!has_permission(callingUid, P_UNLOCK)) {
1696 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001697 return ::PERMISSION_DENIED;
1698 }
1699
Kenny Root655b9582013-04-04 08:37:42 -07001700 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001701 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001702 ALOGD("calling unlock when not locked");
1703 return state;
1704 }
1705
1706 const String8 password8(pw);
1707 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001708 }
1709
Kenny Root07438c82012-11-02 15:41:02 -07001710 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001711 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1712 if (!has_permission(callingUid, P_ZERO)) {
1713 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001714 return -1;
1715 }
Kenny Root70e3a862012-02-15 17:20:23 -08001716
Kenny Root655b9582013-04-04 08:37:42 -07001717 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001718 }
1719
Kenny Root96427ba2013-08-16 14:02:41 -07001720 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1721 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001722 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1723 if (!has_permission(callingUid, P_INSERT)) {
1724 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001725 return ::PERMISSION_DENIED;
1726 }
Kenny Root70e3a862012-02-15 17:20:23 -08001727
Kenny Root49468902013-03-19 13:41:33 -07001728 if (targetUid == -1) {
1729 targetUid = callingUid;
1730 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001731 return ::PERMISSION_DENIED;
1732 }
1733
Kenny Root655b9582013-04-04 08:37:42 -07001734 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001735 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1736 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001737 return state;
1738 }
Kenny Root70e3a862012-02-15 17:20:23 -08001739
Kenny Root07438c82012-11-02 15:41:02 -07001740 uint8_t* data;
1741 size_t dataLength;
1742 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001743 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001744
1745 const keymaster_device_t* device = mKeyStore->getDevice();
1746 if (device == NULL) {
1747 return ::SYSTEM_ERROR;
1748 }
1749
1750 if (device->generate_keypair == NULL) {
1751 return ::SYSTEM_ERROR;
1752 }
1753
Kenny Root17208e02013-09-04 13:56:03 -07001754 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001755 keymaster_dsa_keygen_params_t dsa_params;
1756 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001757
Kenny Root96427ba2013-08-16 14:02:41 -07001758 if (keySize == -1) {
1759 keySize = DSA_DEFAULT_KEY_SIZE;
1760 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1761 || keySize > DSA_MAX_KEY_SIZE) {
1762 ALOGI("invalid key size %d", keySize);
1763 return ::SYSTEM_ERROR;
1764 }
1765 dsa_params.key_size = keySize;
1766
1767 if (args->size() == 3) {
1768 sp<KeystoreArg> gArg = args->itemAt(0);
1769 sp<KeystoreArg> pArg = args->itemAt(1);
1770 sp<KeystoreArg> qArg = args->itemAt(2);
1771
1772 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1773 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1774 dsa_params.generator_len = gArg->size();
1775
1776 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1777 dsa_params.prime_p_len = pArg->size();
1778
1779 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1780 dsa_params.prime_q_len = qArg->size();
1781 } else {
1782 ALOGI("not all DSA parameters were read");
1783 return ::SYSTEM_ERROR;
1784 }
1785 } else if (args->size() != 0) {
1786 ALOGI("DSA args must be 3");
1787 return ::SYSTEM_ERROR;
1788 }
1789
Kenny Root17208e02013-09-04 13:56:03 -07001790 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2) {
1791 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1792 } else {
1793 isFallback = true;
1794 rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1795 }
1796 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001797 keymaster_ec_keygen_params_t ec_params;
1798 memset(&ec_params, '\0', sizeof(ec_params));
1799
1800 if (keySize == -1) {
1801 keySize = EC_DEFAULT_KEY_SIZE;
1802 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1803 ALOGI("invalid key size %d", keySize);
1804 return ::SYSTEM_ERROR;
1805 }
1806 ec_params.field_size = keySize;
1807
Kenny Root17208e02013-09-04 13:56:03 -07001808 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2) {
1809 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1810 } else {
1811 isFallback = true;
1812 rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1813 }
Kenny Root96427ba2013-08-16 14:02:41 -07001814 } else if (keyType == EVP_PKEY_RSA) {
1815 keymaster_rsa_keygen_params_t rsa_params;
1816 memset(&rsa_params, '\0', sizeof(rsa_params));
1817 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1818
1819 if (keySize == -1) {
1820 keySize = RSA_DEFAULT_KEY_SIZE;
1821 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1822 ALOGI("invalid key size %d", keySize);
1823 return ::SYSTEM_ERROR;
1824 }
1825 rsa_params.modulus_size = keySize;
1826
1827 if (args->size() > 1) {
1828 ALOGI("invalid number of arguments: %d", args->size());
1829 return ::SYSTEM_ERROR;
1830 } else if (args->size() == 1) {
1831 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1832 if (pubExpBlob != NULL) {
1833 Unique_BIGNUM pubExpBn(
1834 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1835 pubExpBlob->size(), NULL));
1836 if (pubExpBn.get() == NULL) {
1837 ALOGI("Could not convert public exponent to BN");
1838 return ::SYSTEM_ERROR;
1839 }
1840 unsigned long pubExp = BN_get_word(pubExpBn.get());
1841 if (pubExp == 0xFFFFFFFFL) {
1842 ALOGI("cannot represent public exponent as a long value");
1843 return ::SYSTEM_ERROR;
1844 }
1845 rsa_params.public_exponent = pubExp;
1846 }
1847 }
1848
1849 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1850 } else {
1851 ALOGW("Unsupported key type %d", keyType);
1852 rc = -1;
1853 }
1854
Kenny Root07438c82012-11-02 15:41:02 -07001855 if (rc) {
1856 return ::SYSTEM_ERROR;
1857 }
1858
Kenny Root655b9582013-04-04 08:37:42 -07001859 String8 name8(name);
1860 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001861
1862 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1863 free(data);
1864
Kenny Rootee8068b2013-10-07 09:49:15 -07001865 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001866 keyBlob.setFallback(isFallback);
1867
Kenny Root655b9582013-04-04 08:37:42 -07001868 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001869 }
1870
Kenny Rootf9119d62013-04-03 09:22:15 -07001871 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1872 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001873 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1874 if (!has_permission(callingUid, P_INSERT)) {
1875 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001876 return ::PERMISSION_DENIED;
1877 }
Kenny Root07438c82012-11-02 15:41:02 -07001878
Kenny Root49468902013-03-19 13:41:33 -07001879 if (targetUid == -1) {
1880 targetUid = callingUid;
1881 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001882 return ::PERMISSION_DENIED;
1883 }
1884
Kenny Root655b9582013-04-04 08:37:42 -07001885 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001886 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001887 ALOGD("calling import in state: %d", state);
1888 return state;
1889 }
1890
1891 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001892 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001893
Kenny Rootf9119d62013-04-03 09:22:15 -07001894 return mKeyStore->importKey(data, length, filename.string(), callingUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001895 }
1896
Kenny Root07438c82012-11-02 15:41:02 -07001897 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1898 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001899 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1900 if (!has_permission(callingUid, P_SIGN)) {
1901 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001902 return ::PERMISSION_DENIED;
1903 }
Kenny Root07438c82012-11-02 15:41:02 -07001904
Kenny Root07438c82012-11-02 15:41:02 -07001905 Blob keyBlob;
1906 String8 name8(name);
1907
Kenny Rootd38a0b02013-02-13 12:59:14 -08001908 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001909 int rc;
1910
Kenny Root655b9582013-04-04 08:37:42 -07001911 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001912 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001913 if (responseCode != ::NO_ERROR) {
1914 return responseCode;
1915 }
1916
1917 const keymaster_device_t* device = mKeyStore->getDevice();
1918 if (device == NULL) {
1919 ALOGE("no keymaster device; cannot sign");
1920 return ::SYSTEM_ERROR;
1921 }
1922
1923 if (device->sign_data == NULL) {
1924 ALOGE("device doesn't implement signing");
1925 return ::SYSTEM_ERROR;
1926 }
1927
1928 keymaster_rsa_sign_params_t params;
1929 params.digest_type = DIGEST_NONE;
1930 params.padding_type = PADDING_NONE;
1931
Kenny Root17208e02013-09-04 13:56:03 -07001932 if (keyBlob.isFallback()) {
1933 rc = openssl_sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1934 length, out, outLength);
1935 } else {
1936 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1937 length, out, outLength);
1938 }
Kenny Root07438c82012-11-02 15:41:02 -07001939 if (rc) {
1940 ALOGW("device couldn't sign data");
1941 return ::SYSTEM_ERROR;
1942 }
1943
1944 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001945 }
1946
Kenny Root07438c82012-11-02 15:41:02 -07001947 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1948 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001949 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1950 if (!has_permission(callingUid, P_VERIFY)) {
1951 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001952 return ::PERMISSION_DENIED;
1953 }
Kenny Root70e3a862012-02-15 17:20:23 -08001954
Kenny Root655b9582013-04-04 08:37:42 -07001955 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001956 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001957 ALOGD("calling verify in state: %d", state);
1958 return state;
1959 }
Kenny Root70e3a862012-02-15 17:20:23 -08001960
Kenny Root07438c82012-11-02 15:41:02 -07001961 Blob keyBlob;
1962 String8 name8(name);
1963 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001964
Kenny Root655b9582013-04-04 08:37:42 -07001965 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001966 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001967 if (responseCode != ::NO_ERROR) {
1968 return responseCode;
1969 }
Kenny Root70e3a862012-02-15 17:20:23 -08001970
Kenny Root07438c82012-11-02 15:41:02 -07001971 const keymaster_device_t* device = mKeyStore->getDevice();
1972 if (device == NULL) {
1973 return ::SYSTEM_ERROR;
1974 }
Kenny Root70e3a862012-02-15 17:20:23 -08001975
Kenny Root07438c82012-11-02 15:41:02 -07001976 if (device->verify_data == NULL) {
1977 return ::SYSTEM_ERROR;
1978 }
Kenny Root70e3a862012-02-15 17:20:23 -08001979
Kenny Root07438c82012-11-02 15:41:02 -07001980 keymaster_rsa_sign_params_t params;
1981 params.digest_type = DIGEST_NONE;
1982 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001983
Kenny Root17208e02013-09-04 13:56:03 -07001984 if (keyBlob.isFallback()) {
1985 rc = openssl_verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1986 dataLength, signature, signatureLength);
1987 } else {
1988 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1989 dataLength, signature, signatureLength);
1990 }
Kenny Root07438c82012-11-02 15:41:02 -07001991 if (rc) {
1992 return ::SYSTEM_ERROR;
1993 } else {
1994 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001995 }
1996 }
Kenny Root07438c82012-11-02 15:41:02 -07001997
1998 /*
1999 * TODO: The abstraction between things stored in hardware and regular blobs
2000 * of data stored on the filesystem should be moved down to keystore itself.
2001 * Unfortunately the Java code that calls this has naming conventions that it
2002 * knows about. Ideally keystore shouldn't be used to store random blobs of
2003 * data.
2004 *
2005 * Until that happens, it's necessary to have a separate "get_pubkey" and
2006 * "del_key" since the Java code doesn't really communicate what it's
2007 * intentions are.
2008 */
2009 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002010 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2011 if (!has_permission(callingUid, P_GET)) {
2012 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002013 return ::PERMISSION_DENIED;
2014 }
Kenny Root07438c82012-11-02 15:41:02 -07002015
Kenny Root07438c82012-11-02 15:41:02 -07002016 Blob keyBlob;
2017 String8 name8(name);
2018
Kenny Rootd38a0b02013-02-13 12:59:14 -08002019 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002020
Kenny Root655b9582013-04-04 08:37:42 -07002021 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002022 TYPE_KEY_PAIR);
2023 if (responseCode != ::NO_ERROR) {
2024 return responseCode;
2025 }
2026
2027 const keymaster_device_t* device = mKeyStore->getDevice();
2028 if (device == NULL) {
2029 return ::SYSTEM_ERROR;
2030 }
2031
2032 if (device->get_keypair_public == NULL) {
2033 ALOGE("device has no get_keypair_public implementation!");
2034 return ::SYSTEM_ERROR;
2035 }
2036
Kenny Root17208e02013-09-04 13:56:03 -07002037 int rc;
2038 if (keyBlob.isFallback()) {
2039 rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2040 pubkeyLength);
2041 } else {
2042 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2043 pubkeyLength);
2044 }
Kenny Root07438c82012-11-02 15:41:02 -07002045 if (rc) {
2046 return ::SYSTEM_ERROR;
2047 }
2048
2049 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002050 }
Kenny Root07438c82012-11-02 15:41:02 -07002051
Kenny Root49468902013-03-19 13:41:33 -07002052 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002053 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2054 if (!has_permission(callingUid, P_DELETE)) {
2055 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002056 return ::PERMISSION_DENIED;
2057 }
Kenny Root07438c82012-11-02 15:41:02 -07002058
Kenny Root49468902013-03-19 13:41:33 -07002059 if (targetUid == -1) {
2060 targetUid = callingUid;
2061 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002062 return ::PERMISSION_DENIED;
2063 }
2064
Kenny Root07438c82012-11-02 15:41:02 -07002065 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002066 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002067
2068 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002069 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
2070 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002071 if (responseCode != ::NO_ERROR) {
2072 return responseCode;
2073 }
2074
2075 ResponseCode rc = ::NO_ERROR;
2076
2077 const keymaster_device_t* device = mKeyStore->getDevice();
2078 if (device == NULL) {
2079 rc = ::SYSTEM_ERROR;
2080 } else {
2081 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002082 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Root07438c82012-11-02 15:41:02 -07002083 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2084 rc = ::SYSTEM_ERROR;
2085 }
2086 }
2087 }
2088
2089 if (rc != ::NO_ERROR) {
2090 return rc;
2091 }
2092
2093 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
2094 }
2095
2096 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002097 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2098 if (!has_permission(callingUid, P_GRANT)) {
2099 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002100 return ::PERMISSION_DENIED;
2101 }
Kenny Root07438c82012-11-02 15:41:02 -07002102
Kenny Root655b9582013-04-04 08:37:42 -07002103 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002104 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002105 ALOGD("calling grant in state: %d", state);
2106 return state;
2107 }
2108
2109 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002110 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002111
Kenny Root655b9582013-04-04 08:37:42 -07002112 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002113 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2114 }
2115
Kenny Root655b9582013-04-04 08:37:42 -07002116 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002117 return ::NO_ERROR;
2118 }
2119
2120 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002121 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2122 if (!has_permission(callingUid, P_GRANT)) {
2123 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002124 return ::PERMISSION_DENIED;
2125 }
Kenny Root07438c82012-11-02 15:41:02 -07002126
Kenny Root655b9582013-04-04 08:37:42 -07002127 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002128 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002129 ALOGD("calling ungrant in state: %d", state);
2130 return state;
2131 }
2132
2133 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002134 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002135
Kenny Root655b9582013-04-04 08:37:42 -07002136 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002137 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2138 }
2139
Kenny Root655b9582013-04-04 08:37:42 -07002140 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002141 }
2142
2143 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002144 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2145 if (!has_permission(callingUid, P_GET)) {
2146 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002147 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002148 }
Kenny Root07438c82012-11-02 15:41:02 -07002149
2150 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002151 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002152
Kenny Root655b9582013-04-04 08:37:42 -07002153 if (access(filename.string(), R_OK) == -1) {
2154 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002155 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002156 }
2157
Kenny Root655b9582013-04-04 08:37:42 -07002158 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002159 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002160 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002161 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002162 }
2163
2164 struct stat s;
2165 int ret = fstat(fd, &s);
2166 close(fd);
2167 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002168 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002169 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002170 }
2171
Kenny Root36a9e232013-02-04 14:24:15 -08002172 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002173 }
2174
Kenny Rootd53bc922013-03-21 14:10:15 -07002175 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2176 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002177 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Rootd53bc922013-03-21 14:10:15 -07002178 if (!has_permission(callingUid, P_DUPLICATE)) {
2179 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002180 return -1L;
2181 }
2182
Kenny Root655b9582013-04-04 08:37:42 -07002183 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002184 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002185 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002186 return state;
2187 }
2188
Kenny Rootd53bc922013-03-21 14:10:15 -07002189 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2190 srcUid = callingUid;
2191 } else if (!is_granted_to(callingUid, srcUid)) {
2192 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002193 return ::PERMISSION_DENIED;
2194 }
2195
Kenny Rootd53bc922013-03-21 14:10:15 -07002196 if (destUid == -1) {
2197 destUid = callingUid;
2198 }
2199
2200 if (srcUid != destUid) {
2201 if (static_cast<uid_t>(srcUid) != callingUid) {
2202 ALOGD("can only duplicate from caller to other or to same uid: "
2203 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2204 return ::PERMISSION_DENIED;
2205 }
2206
2207 if (!is_granted_to(callingUid, destUid)) {
2208 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2209 return ::PERMISSION_DENIED;
2210 }
2211 }
2212
2213 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002214 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002215
Kenny Rootd53bc922013-03-21 14:10:15 -07002216 String8 target8(destKey);
Kenny Root655b9582013-04-04 08:37:42 -07002217 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002218
Kenny Root655b9582013-04-04 08:37:42 -07002219 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2220 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002221 return ::SYSTEM_ERROR;
2222 }
2223
Kenny Rootd53bc922013-03-21 14:10:15 -07002224 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002225 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
2226 callingUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002227 if (responseCode != ::NO_ERROR) {
2228 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002229 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002230
Kenny Root655b9582013-04-04 08:37:42 -07002231 return mKeyStore->put(targetFile.string(), &keyBlob, callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002232 }
2233
Kenny Root1b0e3932013-09-05 13:06:32 -07002234 int32_t is_hardware_backed(const String16& keyType) {
2235 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002236 }
2237
Kenny Roota9bb5492013-04-01 16:29:11 -07002238 int32_t clear_uid(int64_t targetUid) {
2239 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2240 if (!has_permission(callingUid, P_CLEAR_UID)) {
2241 ALOGW("permission denied for %d: clear_uid", callingUid);
2242 return ::PERMISSION_DENIED;
2243 }
2244
Kenny Root655b9582013-04-04 08:37:42 -07002245 State state = mKeyStore->getState(callingUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002246 if (!isKeystoreUnlocked(state)) {
2247 ALOGD("calling clear_uid in state: %d", state);
2248 return state;
2249 }
2250
2251 const keymaster_device_t* device = mKeyStore->getDevice();
2252 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002253 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002254 return ::SYSTEM_ERROR;
2255 }
2256
Kenny Root655b9582013-04-04 08:37:42 -07002257 UserState* userState = mKeyStore->getUserState(callingUid);
2258 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota9bb5492013-04-01 16:29:11 -07002259 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07002260 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Roota9bb5492013-04-01 16:29:11 -07002261 return ::SYSTEM_ERROR;
2262 }
2263
Kenny Root655b9582013-04-04 08:37:42 -07002264 char prefix[NAME_MAX];
2265 int n = snprintf(prefix, NAME_MAX, "%u_", static_cast<uid_t>(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002266
2267 ResponseCode rc = ::NO_ERROR;
2268
2269 struct dirent* file;
2270 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002271 // We only care about files.
2272 if (file->d_type != DT_REG) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002273 continue;
2274 }
2275
Kenny Root655b9582013-04-04 08:37:42 -07002276 // Skip anything that starts with a "."
2277 if (file->d_name[0] == '.') {
2278 continue;
2279 }
Kenny Roota9bb5492013-04-01 16:29:11 -07002280
Kenny Root655b9582013-04-04 08:37:42 -07002281 if (strncmp(prefix, file->d_name, n)) {
2282 continue;
2283 }
2284
2285 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Roota9bb5492013-04-01 16:29:11 -07002286 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002287 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, callingUid)
2288 != ::NO_ERROR) {
2289 ALOGW("couldn't open %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002290 continue;
2291 }
2292
2293 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2294 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002295 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002296 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2297 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002298 ALOGW("device couldn't remove %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002299 }
2300 }
2301 }
2302
Kenny Root5f531242013-04-12 11:31:50 -07002303 if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002304 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002305 ALOGW("couldn't unlink %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002306 }
2307 }
2308 closedir(dir);
2309
2310 return rc;
2311 }
2312
Kenny Root07438c82012-11-02 15:41:02 -07002313private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002314 inline bool isKeystoreUnlocked(State state) {
2315 switch (state) {
2316 case ::STATE_NO_ERROR:
2317 return true;
2318 case ::STATE_UNINITIALIZED:
2319 case ::STATE_LOCKED:
2320 return false;
2321 }
2322 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002323 }
2324
2325 ::KeyStore* mKeyStore;
2326};
2327
2328}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002329
2330int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002331 if (argc < 2) {
2332 ALOGE("A directory must be specified!");
2333 return 1;
2334 }
2335 if (chdir(argv[1]) == -1) {
2336 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2337 return 1;
2338 }
2339
2340 Entropy entropy;
2341 if (!entropy.open()) {
2342 return 1;
2343 }
Kenny Root70e3a862012-02-15 17:20:23 -08002344
2345 keymaster_device_t* dev;
2346 if (keymaster_device_initialize(&dev)) {
2347 ALOGE("keystore keymaster could not be initialized; exiting");
2348 return 1;
2349 }
2350
Kenny Root70e3a862012-02-15 17:20:23 -08002351 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002352 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002353 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2354 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2355 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2356 if (ret != android::OK) {
2357 ALOGE("Couldn't register binder service!");
2358 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002359 }
Kenny Root07438c82012-11-02 15:41:02 -07002360
2361 /*
2362 * We're the only thread in existence, so we're just going to process
2363 * Binder transaction as a single-threaded program.
2364 */
2365 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002366
2367 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002368 return 1;
2369}