blob: 987e306795384b72ea5040a7dc0b968fb7f476da [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 Root26cfc082013-09-11 14:38:56 -070047#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070048#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070049#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080050
Kenny Root07438c82012-11-02 15:41:02 -070051#include <keystore/IKeystoreService.h>
52#include <binder/IPCThreadState.h>
53#include <binder/IServiceManager.h>
54
Kenny Roota91203b2012-02-15 15:00:46 -080055#include <cutils/log.h>
56#include <cutils/sockets.h>
57#include <private/android_filesystem_config.h>
58
Kenny Root07438c82012-11-02 15:41:02 -070059#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080060
Kenny 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:
Kenny Root07438c82012-11-02 15:41:02 -0700413 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
414 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800415 mBlob.length = valueLength;
416 memcpy(mBlob.value, value, valueLength);
417
418 mBlob.info = infoLength;
419 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700420
Kenny Root07438c82012-11-02 15:41:02 -0700421 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700422 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700423
Kenny Rootee8068b2013-10-07 09:49:15 -0700424 if (type == TYPE_MASTER_KEY) {
425 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
426 } else {
427 mBlob.flags = KEYSTORE_FLAG_NONE;
428 }
Kenny Roota91203b2012-02-15 15:00:46 -0800429 }
430
431 Blob(blob b) {
432 mBlob = b;
433 }
434
435 Blob() {}
436
Kenny Root51878182012-03-13 12:53:19 -0700437 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800438 return mBlob.value;
439 }
440
Kenny Root51878182012-03-13 12:53:19 -0700441 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800442 return mBlob.length;
443 }
444
Kenny Root51878182012-03-13 12:53:19 -0700445 const uint8_t* getInfo() const {
446 return mBlob.value + mBlob.length;
447 }
448
449 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800450 return mBlob.info;
451 }
452
Kenny Root822c3a92012-03-23 16:34:39 -0700453 uint8_t getVersion() const {
454 return mBlob.version;
455 }
456
Kenny Rootf9119d62013-04-03 09:22:15 -0700457 bool isEncrypted() const {
458 if (mBlob.version < 2) {
459 return true;
460 }
461
462 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
463 }
464
465 void setEncrypted(bool encrypted) {
466 if (encrypted) {
467 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
468 } else {
469 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
470 }
471 }
472
Kenny Root17208e02013-09-04 13:56:03 -0700473 bool isFallback() const {
474 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
475 }
476
477 void setFallback(bool fallback) {
478 if (fallback) {
479 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
480 } else {
481 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
482 }
483 }
484
Kenny Root822c3a92012-03-23 16:34:39 -0700485 void setVersion(uint8_t version) {
486 mBlob.version = version;
487 }
488
489 BlobType getType() const {
490 return BlobType(mBlob.type);
491 }
492
493 void setType(BlobType type) {
494 mBlob.type = uint8_t(type);
495 }
496
Kenny Rootf9119d62013-04-03 09:22:15 -0700497 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
498 ALOGV("writing blob %s", filename);
499 if (isEncrypted()) {
500 if (state != STATE_NO_ERROR) {
501 ALOGD("couldn't insert encrypted blob while not unlocked");
502 return LOCKED;
503 }
504
505 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
506 ALOGW("Could not read random data for: %s", filename);
507 return SYSTEM_ERROR;
508 }
Kenny Roota91203b2012-02-15 15:00:46 -0800509 }
510
511 // data includes the value and the value's length
512 size_t dataLength = mBlob.length + sizeof(mBlob.length);
513 // pad data to the AES_BLOCK_SIZE
514 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
515 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
516 // encrypted data includes the digest value
517 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
518 // move info after space for padding
519 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
520 // zero padding area
521 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
522
523 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800524
Kenny Rootf9119d62013-04-03 09:22:15 -0700525 if (isEncrypted()) {
526 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800527
Kenny Rootf9119d62013-04-03 09:22:15 -0700528 uint8_t vector[AES_BLOCK_SIZE];
529 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
530 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
531 aes_key, vector, AES_ENCRYPT);
532 }
533
Kenny Roota91203b2012-02-15 15:00:46 -0800534 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
535 size_t fileLength = encryptedLength + headerLength + mBlob.info;
536
537 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800538 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
539 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
540 if (out < 0) {
541 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800542 return SYSTEM_ERROR;
543 }
544 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
545 if (close(out) != 0) {
546 return SYSTEM_ERROR;
547 }
548 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800549 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800550 unlink(tmpFileName);
551 return SYSTEM_ERROR;
552 }
Kenny Root150ca932012-11-14 14:29:02 -0800553 if (rename(tmpFileName, filename) == -1) {
554 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
555 return SYSTEM_ERROR;
556 }
557 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800558 }
559
Kenny Rootf9119d62013-04-03 09:22:15 -0700560 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
561 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800562 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
563 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800564 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
565 }
566 // fileLength may be less than sizeof(mBlob) since the in
567 // memory version has extra padding to tolerate rounding up to
568 // the AES_BLOCK_SIZE
569 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
570 if (close(in) != 0) {
571 return SYSTEM_ERROR;
572 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700573
574 if (isEncrypted() && (state != STATE_NO_ERROR)) {
575 return LOCKED;
576 }
577
Kenny Roota91203b2012-02-15 15:00:46 -0800578 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
579 if (fileLength < headerLength) {
580 return VALUE_CORRUPTED;
581 }
582
583 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700584 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800585 return VALUE_CORRUPTED;
586 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700587
588 ssize_t digestedLength;
589 if (isEncrypted()) {
590 if (encryptedLength % AES_BLOCK_SIZE != 0) {
591 return VALUE_CORRUPTED;
592 }
593
594 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
595 mBlob.vector, AES_DECRYPT);
596 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
597 uint8_t computedDigest[MD5_DIGEST_LENGTH];
598 MD5(mBlob.digested, digestedLength, computedDigest);
599 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
600 return VALUE_CORRUPTED;
601 }
602 } else {
603 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800604 }
605
606 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
607 mBlob.length = ntohl(mBlob.length);
608 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
609 return VALUE_CORRUPTED;
610 }
611 if (mBlob.info != 0) {
612 // move info from after padding to after data
613 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
614 }
Kenny Root07438c82012-11-02 15:41:02 -0700615 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800616 }
617
618private:
619 struct blob mBlob;
620};
621
Kenny Root655b9582013-04-04 08:37:42 -0700622class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800623public:
Kenny Root655b9582013-04-04 08:37:42 -0700624 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
625 asprintf(&mUserDir, "user_%u", mUserId);
626 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
627 }
628
629 ~UserState() {
630 free(mUserDir);
631 free(mMasterKeyFile);
632 }
633
634 bool initialize() {
635 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
636 ALOGE("Could not create directory '%s'", mUserDir);
637 return false;
638 }
639
640 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800641 setState(STATE_LOCKED);
642 } else {
643 setState(STATE_UNINITIALIZED);
644 }
Kenny Root70e3a862012-02-15 17:20:23 -0800645
Kenny Root655b9582013-04-04 08:37:42 -0700646 return true;
647 }
648
649 uid_t getUserId() const {
650 return mUserId;
651 }
652
653 const char* getUserDirName() const {
654 return mUserDir;
655 }
656
657 const char* getMasterKeyFileName() const {
658 return mMasterKeyFile;
659 }
660
661 void setState(State state) {
662 mState = state;
663 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
664 mRetry = MAX_RETRY;
665 }
Kenny Roota91203b2012-02-15 15:00:46 -0800666 }
667
Kenny Root51878182012-03-13 12:53:19 -0700668 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800669 return mState;
670 }
671
Kenny Root51878182012-03-13 12:53:19 -0700672 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800673 return mRetry;
674 }
675
Kenny Root655b9582013-04-04 08:37:42 -0700676 void zeroizeMasterKeysInMemory() {
677 memset(mMasterKey, 0, sizeof(mMasterKey));
678 memset(mSalt, 0, sizeof(mSalt));
679 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
680 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800681 }
682
Kenny Root655b9582013-04-04 08:37:42 -0700683 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
684 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800685 return SYSTEM_ERROR;
686 }
Kenny Root655b9582013-04-04 08:37:42 -0700687 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800688 if (response != NO_ERROR) {
689 return response;
690 }
691 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700692 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800693 }
694
Kenny Root655b9582013-04-04 08:37:42 -0700695 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800696 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
697 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
698 AES_KEY passwordAesKey;
699 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700700 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700701 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800702 }
703
Kenny Root655b9582013-04-04 08:37:42 -0700704 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
705 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800706 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800707 return SYSTEM_ERROR;
708 }
709
710 // we read the raw blob to just to get the salt to generate
711 // the AES key, then we create the Blob to use with decryptBlob
712 blob rawBlob;
713 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
714 if (close(in) != 0) {
715 return SYSTEM_ERROR;
716 }
717 // find salt at EOF if present, otherwise we have an old file
718 uint8_t* salt;
719 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
720 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
721 } else {
722 salt = NULL;
723 }
724 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
725 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
726 AES_KEY passwordAesKey;
727 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
728 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700729 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
730 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800731 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700732 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800733 }
734 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
735 // if salt was missing, generate one and write a new master key file with the salt.
736 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700737 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800738 return SYSTEM_ERROR;
739 }
Kenny Root655b9582013-04-04 08:37:42 -0700740 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800741 }
742 if (response == NO_ERROR) {
743 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
744 setupMasterKeys();
745 }
746 return response;
747 }
748 if (mRetry <= 0) {
749 reset();
750 return UNINITIALIZED;
751 }
752 --mRetry;
753 switch (mRetry) {
754 case 0: return WRONG_PASSWORD_0;
755 case 1: return WRONG_PASSWORD_1;
756 case 2: return WRONG_PASSWORD_2;
757 case 3: return WRONG_PASSWORD_3;
758 default: return WRONG_PASSWORD_3;
759 }
760 }
761
Kenny Root655b9582013-04-04 08:37:42 -0700762 AES_KEY* getEncryptionKey() {
763 return &mMasterKeyEncryption;
764 }
765
766 AES_KEY* getDecryptionKey() {
767 return &mMasterKeyDecryption;
768 }
769
Kenny Roota91203b2012-02-15 15:00:46 -0800770 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700771 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800772 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700773 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800774 return false;
775 }
Kenny Root655b9582013-04-04 08:37:42 -0700776
777 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800778 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700779 // We only care about files.
780 if (file->d_type != DT_REG) {
781 continue;
782 }
783
784 // Skip anything that starts with a "."
785 if (file->d_name[0] == '.') {
786 continue;
787 }
788
789 // Find the current file's UID.
790 char* end;
791 unsigned long thisUid = strtoul(file->d_name, &end, 10);
792 if (end[0] != '_' || end[1] == 0) {
793 continue;
794 }
795
796 // Skip if this is not our user.
797 if (get_user_id(thisUid) != mUserId) {
798 continue;
799 }
800
801 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800802 }
803 closedir(dir);
804 return true;
805 }
806
Kenny Root655b9582013-04-04 08:37:42 -0700807private:
808 static const int MASTER_KEY_SIZE_BYTES = 16;
809 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
810
811 static const int MAX_RETRY = 4;
812 static const size_t SALT_SIZE = 16;
813
814 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
815 uint8_t* salt) {
816 size_t saltSize;
817 if (salt != NULL) {
818 saltSize = SALT_SIZE;
819 } else {
820 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
821 salt = (uint8_t*) "keystore";
822 // sizeof = 9, not strlen = 8
823 saltSize = sizeof("keystore");
824 }
825
826 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
827 saltSize, 8192, keySize, key);
828 }
829
830 bool generateSalt(Entropy* entropy) {
831 return entropy->generate_random_data(mSalt, sizeof(mSalt));
832 }
833
834 bool generateMasterKey(Entropy* entropy) {
835 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
836 return false;
837 }
838 if (!generateSalt(entropy)) {
839 return false;
840 }
841 return true;
842 }
843
844 void setupMasterKeys() {
845 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
846 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
847 setState(STATE_NO_ERROR);
848 }
849
850 uid_t mUserId;
851
852 char* mUserDir;
853 char* mMasterKeyFile;
854
855 State mState;
856 int8_t mRetry;
857
858 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
859 uint8_t mSalt[SALT_SIZE];
860
861 AES_KEY mMasterKeyEncryption;
862 AES_KEY mMasterKeyDecryption;
863};
864
865typedef struct {
866 uint32_t uid;
867 const uint8_t* filename;
868} grant_t;
869
870class KeyStore {
871public:
872 KeyStore(Entropy* entropy, keymaster_device_t* device)
873 : mEntropy(entropy)
874 , mDevice(device)
875 {
876 memset(&mMetaData, '\0', sizeof(mMetaData));
877 }
878
879 ~KeyStore() {
880 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
881 it != mGrants.end(); it++) {
882 delete *it;
883 mGrants.erase(it);
884 }
885
886 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
887 it != mMasterKeys.end(); it++) {
888 delete *it;
889 mMasterKeys.erase(it);
890 }
891 }
892
893 keymaster_device_t* getDevice() const {
894 return mDevice;
895 }
896
897 ResponseCode initialize() {
898 readMetaData();
899 if (upgradeKeystore()) {
900 writeMetaData();
901 }
902
903 return ::NO_ERROR;
904 }
905
906 State getState(uid_t uid) {
907 return getUserState(uid)->getState();
908 }
909
910 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
911 UserState* userState = getUserState(uid);
912 return userState->initialize(pw, mEntropy);
913 }
914
915 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
916 uid_t user_id = get_user_id(uid);
917 UserState* userState = getUserState(user_id);
918 return userState->writeMasterKey(pw, mEntropy);
919 }
920
921 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
922 uid_t user_id = get_user_id(uid);
923 UserState* userState = getUserState(user_id);
924 return userState->readMasterKey(pw, mEntropy);
925 }
926
927 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700928 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700929 encode_key(encoded, keyName);
930 return android::String8(encoded);
931 }
932
933 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700934 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700935 encode_key(encoded, keyName);
936 return android::String8::format("%u_%s", uid, encoded);
937 }
938
939 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700940 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700941 encode_key(encoded, keyName);
942 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
943 encoded);
944 }
945
946 bool reset(uid_t uid) {
947 UserState* userState = getUserState(uid);
948 userState->zeroizeMasterKeysInMemory();
949 userState->setState(STATE_UNINITIALIZED);
950 return userState->reset();
951 }
952
953 bool isEmpty(uid_t uid) const {
954 const UserState* userState = getUserState(uid);
955 if (userState == NULL) {
956 return true;
957 }
958
959 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800960 struct dirent* file;
961 if (!dir) {
962 return true;
963 }
964 bool result = true;
Kenny Root655b9582013-04-04 08:37:42 -0700965
966 char filename[NAME_MAX];
967 int n = snprintf(filename, sizeof(filename), "%u_", uid);
968
Kenny Roota91203b2012-02-15 15:00:46 -0800969 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700970 // We only care about files.
971 if (file->d_type != DT_REG) {
972 continue;
973 }
974
975 // Skip anything that starts with a "."
976 if (file->d_name[0] == '.') {
977 continue;
978 }
979
980 if (!strncmp(file->d_name, filename, n)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800981 result = false;
982 break;
983 }
984 }
985 closedir(dir);
986 return result;
987 }
988
Kenny Root655b9582013-04-04 08:37:42 -0700989 void lock(uid_t uid) {
990 UserState* userState = getUserState(uid);
991 userState->zeroizeMasterKeysInMemory();
992 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -0800993 }
994
Kenny Root655b9582013-04-04 08:37:42 -0700995 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
996 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -0700997 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
998 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -0700999 if (rc != NO_ERROR) {
1000 return rc;
1001 }
1002
1003 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001004 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001005 /* If we upgrade the key, we need to write it to disk again. Then
1006 * it must be read it again since the blob is encrypted each time
1007 * it's written.
1008 */
Kenny Root655b9582013-04-04 08:37:42 -07001009 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1010 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001011 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1012 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001013 return rc;
1014 }
1015 }
Kenny Root822c3a92012-03-23 16:34:39 -07001016 }
1017
Kenny Root17208e02013-09-04 13:56:03 -07001018 /*
1019 * This will upgrade software-backed keys to hardware-backed keys when
1020 * the HAL for the device supports the newer key types.
1021 */
1022 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1023 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1024 && keyBlob->isFallback()) {
1025 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1026 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1027
1028 // The HAL allowed the import, reget the key to have the "fresh"
1029 // version.
1030 if (imported == NO_ERROR) {
1031 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1032 }
1033 }
1034
Kenny Rootd53bc922013-03-21 14:10:15 -07001035 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001036 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1037 return KEY_NOT_FOUND;
1038 }
1039
1040 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001041 }
1042
Kenny Root655b9582013-04-04 08:37:42 -07001043 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1044 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001045 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1046 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001047 }
1048
Kenny Root07438c82012-11-02 15:41:02 -07001049 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001050 const grant_t* existing = getGrant(filename, granteeUid);
1051 if (existing == NULL) {
1052 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001053 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001054 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001055 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001056 }
1057 }
1058
Kenny Root07438c82012-11-02 15:41:02 -07001059 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001060 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1061 it != mGrants.end(); it++) {
1062 grant_t* grant = *it;
1063 if (grant->uid == granteeUid
1064 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1065 mGrants.erase(it);
1066 return true;
1067 }
Kenny Root70e3a862012-02-15 17:20:23 -08001068 }
Kenny Root70e3a862012-02-15 17:20:23 -08001069 return false;
1070 }
1071
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001072 bool hasGrant(const char* filename, const uid_t uid) const {
1073 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001074 }
1075
Kenny Rootf9119d62013-04-03 09:22:15 -07001076 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1077 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001078 uint8_t* data;
1079 size_t dataLength;
1080 int rc;
1081
1082 if (mDevice->import_keypair == NULL) {
1083 ALOGE("Keymaster doesn't support import!");
1084 return SYSTEM_ERROR;
1085 }
1086
Kenny Root17208e02013-09-04 13:56:03 -07001087 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001088 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001089 if (rc) {
Kenny Root17208e02013-09-04 13:56:03 -07001090 // If this is an old device HAL, try to fall back to an old version
1091 if (mDevice->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_2) {
1092 rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength);
1093 isFallback = true;
1094 }
1095
1096 if (rc) {
1097 ALOGE("Error while importing keypair: %d", rc);
1098 return SYSTEM_ERROR;
1099 }
Kenny Root822c3a92012-03-23 16:34:39 -07001100 }
1101
1102 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1103 free(data);
1104
Kenny Rootf9119d62013-04-03 09:22:15 -07001105 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001106 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001107
Kenny Root655b9582013-04-04 08:37:42 -07001108 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001109 }
1110
Kenny Root1b0e3932013-09-05 13:06:32 -07001111 bool isHardwareBacked(const android::String16& keyType) const {
1112 if (mDevice == NULL) {
1113 ALOGW("can't get keymaster device");
1114 return false;
1115 }
1116
1117 if (sRSAKeyType == keyType) {
1118 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1119 } else {
1120 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1121 && (mDevice->common.module->module_api_version
1122 >= KEYMASTER_MODULE_API_VERSION_0_2);
1123 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001124 }
1125
Kenny Root655b9582013-04-04 08:37:42 -07001126 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1127 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001128 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001129
1130 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1131 if (responseCode == NO_ERROR) {
1132 return responseCode;
1133 }
1134
1135 // If this is one of the legacy UID->UID mappings, use it.
1136 uid_t euid = get_keystore_euid(uid);
1137 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001138 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001139 responseCode = get(filepath8.string(), keyBlob, type, uid);
1140 if (responseCode == NO_ERROR) {
1141 return responseCode;
1142 }
1143 }
1144
1145 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001146 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001147 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001148 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001149 if (end[0] != '_' || end[1] == 0) {
1150 return KEY_NOT_FOUND;
1151 }
Kenny Root86b16e82013-09-09 11:15:54 -07001152 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1153 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001154 if (!hasGrant(filepath8.string(), uid)) {
1155 return responseCode;
1156 }
1157
1158 // It is a granted key. Try to load it.
1159 return get(filepath8.string(), keyBlob, type, uid);
1160 }
1161
1162 /**
1163 * Returns any existing UserState or creates it if it doesn't exist.
1164 */
1165 UserState* getUserState(uid_t uid) {
1166 uid_t userId = get_user_id(uid);
1167
1168 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1169 it != mMasterKeys.end(); it++) {
1170 UserState* state = *it;
1171 if (state->getUserId() == userId) {
1172 return state;
1173 }
1174 }
1175
1176 UserState* userState = new UserState(userId);
1177 if (!userState->initialize()) {
1178 /* There's not much we can do if initialization fails. Trying to
1179 * unlock the keystore for that user will fail as well, so any
1180 * subsequent request for this user will just return SYSTEM_ERROR.
1181 */
1182 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1183 }
1184 mMasterKeys.add(userState);
1185 return userState;
1186 }
1187
1188 /**
1189 * Returns NULL if the UserState doesn't already exist.
1190 */
1191 const UserState* getUserState(uid_t uid) const {
1192 uid_t userId = get_user_id(uid);
1193
1194 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1195 it != mMasterKeys.end(); it++) {
1196 UserState* state = *it;
1197 if (state->getUserId() == userId) {
1198 return state;
1199 }
1200 }
1201
1202 return NULL;
1203 }
1204
Kenny Roota91203b2012-02-15 15:00:46 -08001205private:
Kenny Root655b9582013-04-04 08:37:42 -07001206 static const char* sOldMasterKey;
1207 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001208 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001209 Entropy* mEntropy;
1210
Kenny Root70e3a862012-02-15 17:20:23 -08001211 keymaster_device_t* mDevice;
1212
Kenny Root655b9582013-04-04 08:37:42 -07001213 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001214
Kenny Root655b9582013-04-04 08:37:42 -07001215 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001216
Kenny Root655b9582013-04-04 08:37:42 -07001217 typedef struct {
1218 uint32_t version;
1219 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001220
Kenny Root655b9582013-04-04 08:37:42 -07001221 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001222
Kenny Root655b9582013-04-04 08:37:42 -07001223 const grant_t* getGrant(const char* filename, uid_t uid) const {
1224 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1225 it != mGrants.end(); it++) {
1226 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001227 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001228 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001229 return grant;
1230 }
1231 }
Kenny Root70e3a862012-02-15 17:20:23 -08001232 return NULL;
1233 }
1234
Kenny Root822c3a92012-03-23 16:34:39 -07001235 /**
1236 * Upgrade code. This will upgrade the key from the current version
1237 * to whatever is newest.
1238 */
Kenny Root655b9582013-04-04 08:37:42 -07001239 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1240 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001241 bool updated = false;
1242 uint8_t version = oldVersion;
1243
1244 /* From V0 -> V1: All old types were unknown */
1245 if (version == 0) {
1246 ALOGV("upgrading to version 1 and setting type %d", type);
1247
1248 blob->setType(type);
1249 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001250 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001251 }
1252 version = 1;
1253 updated = true;
1254 }
1255
Kenny Rootf9119d62013-04-03 09:22:15 -07001256 /* From V1 -> V2: All old keys were encrypted */
1257 if (version == 1) {
1258 ALOGV("upgrading to version 2");
1259
1260 blob->setEncrypted(true);
1261 version = 2;
1262 updated = true;
1263 }
1264
Kenny Root822c3a92012-03-23 16:34:39 -07001265 /*
1266 * If we've updated, set the key blob to the right version
1267 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001268 */
Kenny Root822c3a92012-03-23 16:34:39 -07001269 if (updated) {
1270 ALOGV("updated and writing file %s", filename);
1271 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001272 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001273
1274 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001275 }
1276
1277 /**
1278 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1279 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1280 * Then it overwrites the original blob with the new blob
1281 * format that is returned from the keymaster.
1282 */
Kenny Root655b9582013-04-04 08:37:42 -07001283 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001284 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1285 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1286 if (b.get() == NULL) {
1287 ALOGE("Problem instantiating BIO");
1288 return SYSTEM_ERROR;
1289 }
1290
1291 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1292 if (pkey.get() == NULL) {
1293 ALOGE("Couldn't read old PEM file");
1294 return SYSTEM_ERROR;
1295 }
1296
1297 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1298 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1299 if (len < 0) {
1300 ALOGE("Couldn't measure PKCS#8 length");
1301 return SYSTEM_ERROR;
1302 }
1303
Kenny Root70c98892013-02-07 09:10:36 -08001304 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1305 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001306 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1307 ALOGE("Couldn't convert to PKCS#8");
1308 return SYSTEM_ERROR;
1309 }
1310
Kenny Rootf9119d62013-04-03 09:22:15 -07001311 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1312 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001313 if (rc != NO_ERROR) {
1314 return rc;
1315 }
1316
Kenny Root655b9582013-04-04 08:37:42 -07001317 return get(filename, blob, TYPE_KEY_PAIR, uid);
1318 }
1319
1320 void readMetaData() {
1321 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1322 if (in < 0) {
1323 return;
1324 }
1325 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1326 if (fileLength != sizeof(mMetaData)) {
1327 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1328 sizeof(mMetaData));
1329 }
1330 close(in);
1331 }
1332
1333 void writeMetaData() {
1334 const char* tmpFileName = ".metadata.tmp";
1335 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1336 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1337 if (out < 0) {
1338 ALOGE("couldn't write metadata file: %s", strerror(errno));
1339 return;
1340 }
1341 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1342 if (fileLength != sizeof(mMetaData)) {
1343 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1344 sizeof(mMetaData));
1345 }
1346 close(out);
1347 rename(tmpFileName, sMetaDataFile);
1348 }
1349
1350 bool upgradeKeystore() {
1351 bool upgraded = false;
1352
1353 if (mMetaData.version == 0) {
1354 UserState* userState = getUserState(0);
1355
1356 // Initialize first so the directory is made.
1357 userState->initialize();
1358
1359 // Migrate the old .masterkey file to user 0.
1360 if (access(sOldMasterKey, R_OK) == 0) {
1361 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1362 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1363 return false;
1364 }
1365 }
1366
1367 // Initialize again in case we had a key.
1368 userState->initialize();
1369
1370 // Try to migrate existing keys.
1371 DIR* dir = opendir(".");
1372 if (!dir) {
1373 // Give up now; maybe we can upgrade later.
1374 ALOGE("couldn't open keystore's directory; something is wrong");
1375 return false;
1376 }
1377
1378 struct dirent* file;
1379 while ((file = readdir(dir)) != NULL) {
1380 // We only care about files.
1381 if (file->d_type != DT_REG) {
1382 continue;
1383 }
1384
1385 // Skip anything that starts with a "."
1386 if (file->d_name[0] == '.') {
1387 continue;
1388 }
1389
1390 // Find the current file's user.
1391 char* end;
1392 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1393 if (end[0] != '_' || end[1] == 0) {
1394 continue;
1395 }
1396 UserState* otherUser = getUserState(thisUid);
1397 if (otherUser->getUserId() != 0) {
1398 unlinkat(dirfd(dir), file->d_name, 0);
1399 }
1400
1401 // Rename the file into user directory.
1402 DIR* otherdir = opendir(otherUser->getUserDirName());
1403 if (otherdir == NULL) {
1404 ALOGW("couldn't open user directory for rename");
1405 continue;
1406 }
1407 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1408 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1409 }
1410 closedir(otherdir);
1411 }
1412 closedir(dir);
1413
1414 mMetaData.version = 1;
1415 upgraded = true;
1416 }
1417
1418 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001419 }
Kenny Roota91203b2012-02-15 15:00:46 -08001420};
1421
Kenny Root655b9582013-04-04 08:37:42 -07001422const char* KeyStore::sOldMasterKey = ".masterkey";
1423const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001424
Kenny Root1b0e3932013-09-05 13:06:32 -07001425const android::String16 KeyStore::sRSAKeyType("RSA");
1426
Kenny Root07438c82012-11-02 15:41:02 -07001427namespace android {
1428class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1429public:
1430 KeyStoreProxy(KeyStore* keyStore)
1431 : mKeyStore(keyStore)
1432 {
Kenny Roota91203b2012-02-15 15:00:46 -08001433 }
Kenny Roota91203b2012-02-15 15:00:46 -08001434
Kenny Root07438c82012-11-02 15:41:02 -07001435 void binderDied(const wp<IBinder>&) {
1436 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001437 }
Kenny Roota91203b2012-02-15 15:00:46 -08001438
Kenny Root07438c82012-11-02 15:41:02 -07001439 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001440 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1441 if (!has_permission(callingUid, P_TEST)) {
1442 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001443 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001444 }
Kenny Roota91203b2012-02-15 15:00:46 -08001445
Kenny Root655b9582013-04-04 08:37:42 -07001446 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001447 }
1448
Kenny Root07438c82012-11-02 15:41:02 -07001449 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001450 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1451 if (!has_permission(callingUid, P_GET)) {
1452 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001453 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001454 }
Kenny Root07438c82012-11-02 15:41:02 -07001455
Kenny Root07438c82012-11-02 15:41:02 -07001456 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001457 Blob keyBlob;
Kenny Root49468902013-03-19 13:41:33 -07001458
Kenny Root655b9582013-04-04 08:37:42 -07001459 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001460 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001461 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001462 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001463 *item = NULL;
1464 *itemLength = 0;
1465 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001466 }
Kenny Roota91203b2012-02-15 15:00:46 -08001467
Kenny Root07438c82012-11-02 15:41:02 -07001468 *item = (uint8_t*) malloc(keyBlob.getLength());
1469 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1470 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001471
Kenny Root07438c82012-11-02 15:41:02 -07001472 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001473 }
1474
Kenny Rootf9119d62013-04-03 09:22:15 -07001475 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1476 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001477 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1478 if (!has_permission(callingUid, P_INSERT)) {
1479 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001480 return ::PERMISSION_DENIED;
1481 }
Kenny Root07438c82012-11-02 15:41:02 -07001482
Kenny Rootf9119d62013-04-03 09:22:15 -07001483 State state = mKeyStore->getState(callingUid);
1484 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1485 ALOGD("calling get in state: %d", state);
1486 return state;
1487 }
1488
Kenny Root49468902013-03-19 13:41:33 -07001489 if (targetUid == -1) {
1490 targetUid = callingUid;
1491 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001492 return ::PERMISSION_DENIED;
1493 }
1494
Kenny Root07438c82012-11-02 15:41:02 -07001495 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001496 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001497
1498 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001499 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1500
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001501 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001502 }
1503
Kenny Root49468902013-03-19 13:41:33 -07001504 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001505 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1506 if (!has_permission(callingUid, P_DELETE)) {
1507 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001508 return ::PERMISSION_DENIED;
1509 }
Kenny Root70e3a862012-02-15 17:20:23 -08001510
Kenny Root49468902013-03-19 13:41:33 -07001511 if (targetUid == -1) {
1512 targetUid = callingUid;
1513 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001514 return ::PERMISSION_DENIED;
1515 }
1516
Kenny Root07438c82012-11-02 15:41:02 -07001517 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001518 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001519
1520 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001521 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001522 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07001523 if (responseCode != ::NO_ERROR) {
1524 return responseCode;
1525 }
1526 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001527 }
1528
Kenny Root49468902013-03-19 13:41:33 -07001529 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001530 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1531 if (!has_permission(callingUid, P_EXIST)) {
1532 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001533 return ::PERMISSION_DENIED;
1534 }
Kenny Root70e3a862012-02-15 17:20:23 -08001535
Kenny Root49468902013-03-19 13:41:33 -07001536 if (targetUid == -1) {
1537 targetUid = callingUid;
1538 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001539 return ::PERMISSION_DENIED;
1540 }
1541
Kenny Root07438c82012-11-02 15:41:02 -07001542 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001543 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001544
Kenny Root655b9582013-04-04 08:37:42 -07001545 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001546 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1547 }
1548 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001549 }
1550
Kenny Root49468902013-03-19 13:41:33 -07001551 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001552 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1553 if (!has_permission(callingUid, P_SAW)) {
1554 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001555 return ::PERMISSION_DENIED;
1556 }
Kenny Root70e3a862012-02-15 17:20:23 -08001557
Kenny Root49468902013-03-19 13:41:33 -07001558 if (targetUid == -1) {
1559 targetUid = callingUid;
1560 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001561 return ::PERMISSION_DENIED;
1562 }
1563
Kenny Root655b9582013-04-04 08:37:42 -07001564 UserState* userState = mKeyStore->getUserState(targetUid);
1565 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001566 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07001567 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001568 return ::SYSTEM_ERROR;
1569 }
Kenny Root70e3a862012-02-15 17:20:23 -08001570
Kenny Root07438c82012-11-02 15:41:02 -07001571 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001572 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1573 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001574
Kenny Root07438c82012-11-02 15:41:02 -07001575 struct dirent* file;
1576 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001577 // We only care about files.
1578 if (file->d_type != DT_REG) {
1579 continue;
1580 }
1581
1582 // Skip anything that starts with a "."
1583 if (file->d_name[0] == '.') {
1584 continue;
1585 }
1586
1587 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001588 const char* p = &file->d_name[n];
1589 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001590
Kenny Root07438c82012-11-02 15:41:02 -07001591 size_t extra = decode_key_length(p, plen);
1592 char *match = (char*) malloc(extra + 1);
1593 if (match != NULL) {
1594 decode_key(match, p, plen);
1595 matches->push(String16(match, extra));
1596 free(match);
1597 } else {
1598 ALOGW("could not allocate match of size %zd", extra);
1599 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001600 }
1601 }
Kenny Root07438c82012-11-02 15:41:02 -07001602 closedir(dir);
1603
1604 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001605 }
1606
Kenny Root07438c82012-11-02 15:41:02 -07001607 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001608 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1609 if (!has_permission(callingUid, P_RESET)) {
1610 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001611 return ::PERMISSION_DENIED;
1612 }
1613
Kenny Root655b9582013-04-04 08:37:42 -07001614 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001615
1616 const keymaster_device_t* device = mKeyStore->getDevice();
1617 if (device == NULL) {
1618 ALOGE("No keymaster device!");
1619 return ::SYSTEM_ERROR;
1620 }
1621
1622 if (device->delete_all == NULL) {
1623 ALOGV("keymaster device doesn't implement delete_all");
1624 return rc;
1625 }
1626
1627 if (device->delete_all(device)) {
1628 ALOGE("Problem calling keymaster's delete_all");
1629 return ::SYSTEM_ERROR;
1630 }
1631
Kenny Root9a53d3e2012-08-14 10:47:54 -07001632 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001633 }
1634
Kenny Root07438c82012-11-02 15:41:02 -07001635 /*
1636 * Here is the history. To improve the security, the parameters to generate the
1637 * master key has been changed. To make a seamless transition, we update the
1638 * file using the same password when the user unlock it for the first time. If
1639 * any thing goes wrong during the transition, the new file will not overwrite
1640 * the old one. This avoids permanent damages of the existing data.
1641 */
1642 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001643 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1644 if (!has_permission(callingUid, P_PASSWORD)) {
1645 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001646 return ::PERMISSION_DENIED;
1647 }
Kenny Root70e3a862012-02-15 17:20:23 -08001648
Kenny Root07438c82012-11-02 15:41:02 -07001649 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001650
Kenny Root655b9582013-04-04 08:37:42 -07001651 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001652 case ::STATE_UNINITIALIZED: {
1653 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001654 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001655 }
1656 case ::STATE_NO_ERROR: {
1657 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001658 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001659 }
1660 case ::STATE_LOCKED: {
1661 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001662 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001663 }
1664 }
1665 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001666 }
1667
Kenny Root07438c82012-11-02 15:41:02 -07001668 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001669 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1670 if (!has_permission(callingUid, P_LOCK)) {
1671 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001672 return ::PERMISSION_DENIED;
1673 }
Kenny Root70e3a862012-02-15 17:20:23 -08001674
Kenny Root655b9582013-04-04 08:37:42 -07001675 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001676 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001677 ALOGD("calling lock in state: %d", state);
1678 return state;
1679 }
1680
Kenny Root655b9582013-04-04 08:37:42 -07001681 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001682 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001683 }
1684
Kenny Root07438c82012-11-02 15:41:02 -07001685 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001686 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1687 if (!has_permission(callingUid, P_UNLOCK)) {
1688 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001689 return ::PERMISSION_DENIED;
1690 }
1691
Kenny Root655b9582013-04-04 08:37:42 -07001692 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001693 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001694 ALOGD("calling unlock when not locked");
1695 return state;
1696 }
1697
1698 const String8 password8(pw);
1699 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001700 }
1701
Kenny Root07438c82012-11-02 15:41:02 -07001702 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001703 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1704 if (!has_permission(callingUid, P_ZERO)) {
1705 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001706 return -1;
1707 }
Kenny Root70e3a862012-02-15 17:20:23 -08001708
Kenny Root655b9582013-04-04 08:37:42 -07001709 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001710 }
1711
Kenny Root96427ba2013-08-16 14:02:41 -07001712 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1713 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001714 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1715 if (!has_permission(callingUid, P_INSERT)) {
1716 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001717 return ::PERMISSION_DENIED;
1718 }
Kenny Root70e3a862012-02-15 17:20:23 -08001719
Kenny Root49468902013-03-19 13:41:33 -07001720 if (targetUid == -1) {
1721 targetUid = callingUid;
1722 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001723 return ::PERMISSION_DENIED;
1724 }
1725
Kenny Root655b9582013-04-04 08:37:42 -07001726 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001727 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1728 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001729 return state;
1730 }
Kenny Root70e3a862012-02-15 17:20:23 -08001731
Kenny Root07438c82012-11-02 15:41:02 -07001732 uint8_t* data;
1733 size_t dataLength;
1734 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001735 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001736
1737 const keymaster_device_t* device = mKeyStore->getDevice();
1738 if (device == NULL) {
1739 return ::SYSTEM_ERROR;
1740 }
1741
1742 if (device->generate_keypair == NULL) {
1743 return ::SYSTEM_ERROR;
1744 }
1745
Kenny Root17208e02013-09-04 13:56:03 -07001746 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001747 keymaster_dsa_keygen_params_t dsa_params;
1748 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001749
Kenny Root96427ba2013-08-16 14:02:41 -07001750 if (keySize == -1) {
1751 keySize = DSA_DEFAULT_KEY_SIZE;
1752 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1753 || keySize > DSA_MAX_KEY_SIZE) {
1754 ALOGI("invalid key size %d", keySize);
1755 return ::SYSTEM_ERROR;
1756 }
1757 dsa_params.key_size = keySize;
1758
1759 if (args->size() == 3) {
1760 sp<KeystoreArg> gArg = args->itemAt(0);
1761 sp<KeystoreArg> pArg = args->itemAt(1);
1762 sp<KeystoreArg> qArg = args->itemAt(2);
1763
1764 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1765 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1766 dsa_params.generator_len = gArg->size();
1767
1768 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1769 dsa_params.prime_p_len = pArg->size();
1770
1771 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1772 dsa_params.prime_q_len = qArg->size();
1773 } else {
1774 ALOGI("not all DSA parameters were read");
1775 return ::SYSTEM_ERROR;
1776 }
1777 } else if (args->size() != 0) {
1778 ALOGI("DSA args must be 3");
1779 return ::SYSTEM_ERROR;
1780 }
1781
Kenny Root17208e02013-09-04 13:56:03 -07001782 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2) {
1783 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1784 } else {
1785 isFallback = true;
1786 rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1787 }
1788 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001789 keymaster_ec_keygen_params_t ec_params;
1790 memset(&ec_params, '\0', sizeof(ec_params));
1791
1792 if (keySize == -1) {
1793 keySize = EC_DEFAULT_KEY_SIZE;
1794 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1795 ALOGI("invalid key size %d", keySize);
1796 return ::SYSTEM_ERROR;
1797 }
1798 ec_params.field_size = keySize;
1799
Kenny Root17208e02013-09-04 13:56:03 -07001800 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2) {
1801 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1802 } else {
1803 isFallback = true;
1804 rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1805 }
Kenny Root96427ba2013-08-16 14:02:41 -07001806 } else if (keyType == EVP_PKEY_RSA) {
1807 keymaster_rsa_keygen_params_t rsa_params;
1808 memset(&rsa_params, '\0', sizeof(rsa_params));
1809 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1810
1811 if (keySize == -1) {
1812 keySize = RSA_DEFAULT_KEY_SIZE;
1813 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1814 ALOGI("invalid key size %d", keySize);
1815 return ::SYSTEM_ERROR;
1816 }
1817 rsa_params.modulus_size = keySize;
1818
1819 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001820 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001821 return ::SYSTEM_ERROR;
1822 } else if (args->size() == 1) {
1823 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1824 if (pubExpBlob != NULL) {
1825 Unique_BIGNUM pubExpBn(
1826 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1827 pubExpBlob->size(), NULL));
1828 if (pubExpBn.get() == NULL) {
1829 ALOGI("Could not convert public exponent to BN");
1830 return ::SYSTEM_ERROR;
1831 }
1832 unsigned long pubExp = BN_get_word(pubExpBn.get());
1833 if (pubExp == 0xFFFFFFFFL) {
1834 ALOGI("cannot represent public exponent as a long value");
1835 return ::SYSTEM_ERROR;
1836 }
1837 rsa_params.public_exponent = pubExp;
1838 }
1839 }
1840
1841 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1842 } else {
1843 ALOGW("Unsupported key type %d", keyType);
1844 rc = -1;
1845 }
1846
Kenny Root07438c82012-11-02 15:41:02 -07001847 if (rc) {
1848 return ::SYSTEM_ERROR;
1849 }
1850
Kenny Root655b9582013-04-04 08:37:42 -07001851 String8 name8(name);
1852 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001853
1854 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1855 free(data);
1856
Kenny Rootee8068b2013-10-07 09:49:15 -07001857 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001858 keyBlob.setFallback(isFallback);
1859
Kenny Root655b9582013-04-04 08:37:42 -07001860 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001861 }
1862
Kenny Rootf9119d62013-04-03 09:22:15 -07001863 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1864 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001865 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1866 if (!has_permission(callingUid, P_INSERT)) {
1867 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001868 return ::PERMISSION_DENIED;
1869 }
Kenny Root07438c82012-11-02 15:41:02 -07001870
Kenny Root49468902013-03-19 13:41:33 -07001871 if (targetUid == -1) {
1872 targetUid = callingUid;
1873 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001874 return ::PERMISSION_DENIED;
1875 }
1876
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001877 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001878 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001879 ALOGD("calling import in state: %d", state);
1880 return state;
1881 }
1882
1883 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001884 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001885
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001886 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001887 }
1888
Kenny Root07438c82012-11-02 15:41:02 -07001889 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1890 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001891 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1892 if (!has_permission(callingUid, P_SIGN)) {
1893 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001894 return ::PERMISSION_DENIED;
1895 }
Kenny Root07438c82012-11-02 15:41:02 -07001896
Kenny Root07438c82012-11-02 15:41:02 -07001897 Blob keyBlob;
1898 String8 name8(name);
1899
Kenny Rootd38a0b02013-02-13 12:59:14 -08001900 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001901 int rc;
1902
Kenny Root655b9582013-04-04 08:37:42 -07001903 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001904 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001905 if (responseCode != ::NO_ERROR) {
1906 return responseCode;
1907 }
1908
1909 const keymaster_device_t* device = mKeyStore->getDevice();
1910 if (device == NULL) {
1911 ALOGE("no keymaster device; cannot sign");
1912 return ::SYSTEM_ERROR;
1913 }
1914
1915 if (device->sign_data == NULL) {
1916 ALOGE("device doesn't implement signing");
1917 return ::SYSTEM_ERROR;
1918 }
1919
1920 keymaster_rsa_sign_params_t params;
1921 params.digest_type = DIGEST_NONE;
1922 params.padding_type = PADDING_NONE;
1923
Kenny Root17208e02013-09-04 13:56:03 -07001924 if (keyBlob.isFallback()) {
1925 rc = openssl_sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1926 length, out, outLength);
1927 } else {
1928 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1929 length, out, outLength);
1930 }
Kenny Root07438c82012-11-02 15:41:02 -07001931 if (rc) {
1932 ALOGW("device couldn't sign data");
1933 return ::SYSTEM_ERROR;
1934 }
1935
1936 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001937 }
1938
Kenny Root07438c82012-11-02 15:41:02 -07001939 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1940 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001941 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1942 if (!has_permission(callingUid, P_VERIFY)) {
1943 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001944 return ::PERMISSION_DENIED;
1945 }
Kenny Root70e3a862012-02-15 17:20:23 -08001946
Kenny Root655b9582013-04-04 08:37:42 -07001947 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001948 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001949 ALOGD("calling verify in state: %d", state);
1950 return state;
1951 }
Kenny Root70e3a862012-02-15 17:20:23 -08001952
Kenny Root07438c82012-11-02 15:41:02 -07001953 Blob keyBlob;
1954 String8 name8(name);
1955 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001956
Kenny Root655b9582013-04-04 08:37:42 -07001957 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001958 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001959 if (responseCode != ::NO_ERROR) {
1960 return responseCode;
1961 }
Kenny Root70e3a862012-02-15 17:20:23 -08001962
Kenny Root07438c82012-11-02 15:41:02 -07001963 const keymaster_device_t* device = mKeyStore->getDevice();
1964 if (device == NULL) {
1965 return ::SYSTEM_ERROR;
1966 }
Kenny Root70e3a862012-02-15 17:20:23 -08001967
Kenny Root07438c82012-11-02 15:41:02 -07001968 if (device->verify_data == NULL) {
1969 return ::SYSTEM_ERROR;
1970 }
Kenny Root70e3a862012-02-15 17:20:23 -08001971
Kenny Root07438c82012-11-02 15:41:02 -07001972 keymaster_rsa_sign_params_t params;
1973 params.digest_type = DIGEST_NONE;
1974 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001975
Kenny Root17208e02013-09-04 13:56:03 -07001976 if (keyBlob.isFallback()) {
1977 rc = openssl_verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1978 dataLength, signature, signatureLength);
1979 } else {
1980 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1981 dataLength, signature, signatureLength);
1982 }
Kenny Root07438c82012-11-02 15:41:02 -07001983 if (rc) {
1984 return ::SYSTEM_ERROR;
1985 } else {
1986 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001987 }
1988 }
Kenny Root07438c82012-11-02 15:41:02 -07001989
1990 /*
1991 * TODO: The abstraction between things stored in hardware and regular blobs
1992 * of data stored on the filesystem should be moved down to keystore itself.
1993 * Unfortunately the Java code that calls this has naming conventions that it
1994 * knows about. Ideally keystore shouldn't be used to store random blobs of
1995 * data.
1996 *
1997 * Until that happens, it's necessary to have a separate "get_pubkey" and
1998 * "del_key" since the Java code doesn't really communicate what it's
1999 * intentions are.
2000 */
2001 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002002 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2003 if (!has_permission(callingUid, P_GET)) {
2004 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002005 return ::PERMISSION_DENIED;
2006 }
Kenny Root07438c82012-11-02 15:41:02 -07002007
Kenny Root07438c82012-11-02 15:41:02 -07002008 Blob keyBlob;
2009 String8 name8(name);
2010
Kenny Rootd38a0b02013-02-13 12:59:14 -08002011 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002012
Kenny Root655b9582013-04-04 08:37:42 -07002013 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002014 TYPE_KEY_PAIR);
2015 if (responseCode != ::NO_ERROR) {
2016 return responseCode;
2017 }
2018
2019 const keymaster_device_t* device = mKeyStore->getDevice();
2020 if (device == NULL) {
2021 return ::SYSTEM_ERROR;
2022 }
2023
2024 if (device->get_keypair_public == NULL) {
2025 ALOGE("device has no get_keypair_public implementation!");
2026 return ::SYSTEM_ERROR;
2027 }
2028
Kenny Root17208e02013-09-04 13:56:03 -07002029 int rc;
2030 if (keyBlob.isFallback()) {
2031 rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2032 pubkeyLength);
2033 } else {
2034 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2035 pubkeyLength);
2036 }
Kenny Root07438c82012-11-02 15:41:02 -07002037 if (rc) {
2038 return ::SYSTEM_ERROR;
2039 }
2040
2041 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002042 }
Kenny Root07438c82012-11-02 15:41:02 -07002043
Kenny Root49468902013-03-19 13:41:33 -07002044 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002045 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2046 if (!has_permission(callingUid, P_DELETE)) {
2047 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002048 return ::PERMISSION_DENIED;
2049 }
Kenny Root07438c82012-11-02 15:41:02 -07002050
Kenny Root49468902013-03-19 13:41:33 -07002051 if (targetUid == -1) {
2052 targetUid = callingUid;
2053 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002054 return ::PERMISSION_DENIED;
2055 }
2056
Kenny Root07438c82012-11-02 15:41:02 -07002057 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002058 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002059
2060 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002061 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002062 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002063 if (responseCode != ::NO_ERROR) {
2064 return responseCode;
2065 }
2066
2067 ResponseCode rc = ::NO_ERROR;
2068
2069 const keymaster_device_t* device = mKeyStore->getDevice();
2070 if (device == NULL) {
2071 rc = ::SYSTEM_ERROR;
2072 } else {
2073 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002074 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Root07438c82012-11-02 15:41:02 -07002075 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2076 rc = ::SYSTEM_ERROR;
2077 }
2078 }
2079 }
2080
2081 if (rc != ::NO_ERROR) {
2082 return rc;
2083 }
2084
2085 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
2086 }
2087
2088 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002089 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2090 if (!has_permission(callingUid, P_GRANT)) {
2091 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002092 return ::PERMISSION_DENIED;
2093 }
Kenny Root07438c82012-11-02 15:41:02 -07002094
Kenny Root655b9582013-04-04 08:37:42 -07002095 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002096 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002097 ALOGD("calling grant in state: %d", state);
2098 return state;
2099 }
2100
2101 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002102 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002103
Kenny Root655b9582013-04-04 08:37:42 -07002104 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002105 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2106 }
2107
Kenny Root655b9582013-04-04 08:37:42 -07002108 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002109 return ::NO_ERROR;
2110 }
2111
2112 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002113 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2114 if (!has_permission(callingUid, P_GRANT)) {
2115 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002116 return ::PERMISSION_DENIED;
2117 }
Kenny Root07438c82012-11-02 15:41:02 -07002118
Kenny Root655b9582013-04-04 08:37:42 -07002119 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002120 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002121 ALOGD("calling ungrant in state: %d", state);
2122 return state;
2123 }
2124
2125 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002126 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002127
Kenny Root655b9582013-04-04 08:37:42 -07002128 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002129 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2130 }
2131
Kenny Root655b9582013-04-04 08:37:42 -07002132 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002133 }
2134
2135 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002136 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2137 if (!has_permission(callingUid, P_GET)) {
2138 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002139 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002140 }
Kenny Root07438c82012-11-02 15:41:02 -07002141
2142 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002143 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002144
Kenny Root655b9582013-04-04 08:37:42 -07002145 if (access(filename.string(), R_OK) == -1) {
2146 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002147 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002148 }
2149
Kenny Root655b9582013-04-04 08:37:42 -07002150 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002151 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002152 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002153 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002154 }
2155
2156 struct stat s;
2157 int ret = fstat(fd, &s);
2158 close(fd);
2159 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002160 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002161 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002162 }
2163
Kenny Root36a9e232013-02-04 14:24:15 -08002164 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002165 }
2166
Kenny Rootd53bc922013-03-21 14:10:15 -07002167 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2168 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002169 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Rootd53bc922013-03-21 14:10:15 -07002170 if (!has_permission(callingUid, P_DUPLICATE)) {
2171 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002172 return -1L;
2173 }
2174
Kenny Root655b9582013-04-04 08:37:42 -07002175 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002176 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002177 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002178 return state;
2179 }
2180
Kenny Rootd53bc922013-03-21 14:10:15 -07002181 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2182 srcUid = callingUid;
2183 } else if (!is_granted_to(callingUid, srcUid)) {
2184 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002185 return ::PERMISSION_DENIED;
2186 }
2187
Kenny Rootd53bc922013-03-21 14:10:15 -07002188 if (destUid == -1) {
2189 destUid = callingUid;
2190 }
2191
2192 if (srcUid != destUid) {
2193 if (static_cast<uid_t>(srcUid) != callingUid) {
2194 ALOGD("can only duplicate from caller to other or to same uid: "
2195 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2196 return ::PERMISSION_DENIED;
2197 }
2198
2199 if (!is_granted_to(callingUid, destUid)) {
2200 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2201 return ::PERMISSION_DENIED;
2202 }
2203 }
2204
2205 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002206 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002207
Kenny Rootd53bc922013-03-21 14:10:15 -07002208 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002209 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002210
Kenny Root655b9582013-04-04 08:37:42 -07002211 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2212 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002213 return ::SYSTEM_ERROR;
2214 }
2215
Kenny Rootd53bc922013-03-21 14:10:15 -07002216 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002217 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002218 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002219 if (responseCode != ::NO_ERROR) {
2220 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002221 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002222
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002223 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002224 }
2225
Kenny Root1b0e3932013-09-05 13:06:32 -07002226 int32_t is_hardware_backed(const String16& keyType) {
2227 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002228 }
2229
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002230 int32_t clear_uid(int64_t targetUid64) {
2231 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002232 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2233 if (!has_permission(callingUid, P_CLEAR_UID)) {
2234 ALOGW("permission denied for %d: clear_uid", callingUid);
2235 return ::PERMISSION_DENIED;
2236 }
2237
Kenny Root655b9582013-04-04 08:37:42 -07002238 State state = mKeyStore->getState(callingUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002239 if (!isKeystoreUnlocked(state)) {
2240 ALOGD("calling clear_uid in state: %d", state);
2241 return state;
2242 }
2243
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002244 if (targetUid64 == -1) {
2245 targetUid = callingUid;
2246 } else if (!is_granted_to(callingUid, targetUid)) {
2247 return ::PERMISSION_DENIED;
2248 }
2249
Kenny Roota9bb5492013-04-01 16:29:11 -07002250 const keymaster_device_t* device = mKeyStore->getDevice();
2251 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002252 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002253 return ::SYSTEM_ERROR;
2254 }
2255
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002256 UserState* userState = mKeyStore->getUserState(targetUid);
Kenny Root655b9582013-04-04 08:37:42 -07002257 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota9bb5492013-04-01 16:29:11 -07002258 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07002259 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Roota9bb5492013-04-01 16:29:11 -07002260 return ::SYSTEM_ERROR;
2261 }
2262
Kenny Root655b9582013-04-04 08:37:42 -07002263 char prefix[NAME_MAX];
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002264 int n = snprintf(prefix, NAME_MAX, "%u_", targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002265
2266 ResponseCode rc = ::NO_ERROR;
2267
2268 struct dirent* file;
2269 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002270 // We only care about files.
2271 if (file->d_type != DT_REG) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002272 continue;
2273 }
2274
Kenny Root655b9582013-04-04 08:37:42 -07002275 // Skip anything that starts with a "."
2276 if (file->d_name[0] == '.') {
2277 continue;
2278 }
Kenny Roota9bb5492013-04-01 16:29:11 -07002279
Kenny Root655b9582013-04-04 08:37:42 -07002280 if (strncmp(prefix, file->d_name, n)) {
2281 continue;
2282 }
2283
2284 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Roota9bb5492013-04-01 16:29:11 -07002285 Blob keyBlob;
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002286 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, targetUid)
Kenny Root655b9582013-04-04 08:37:42 -07002287 != ::NO_ERROR) {
2288 ALOGW("couldn't open %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002289 continue;
2290 }
2291
2292 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2293 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002294 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002295 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2296 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002297 ALOGW("device couldn't remove %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002298 }
2299 }
2300 }
2301
Kenny Root5f531242013-04-12 11:31:50 -07002302 if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002303 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002304 ALOGW("couldn't unlink %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002305 }
2306 }
2307 closedir(dir);
2308
2309 return rc;
2310 }
2311
Kenny Root07438c82012-11-02 15:41:02 -07002312private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002313 inline bool isKeystoreUnlocked(State state) {
2314 switch (state) {
2315 case ::STATE_NO_ERROR:
2316 return true;
2317 case ::STATE_UNINITIALIZED:
2318 case ::STATE_LOCKED:
2319 return false;
2320 }
2321 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002322 }
2323
2324 ::KeyStore* mKeyStore;
2325};
2326
2327}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002328
2329int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002330 if (argc < 2) {
2331 ALOGE("A directory must be specified!");
2332 return 1;
2333 }
2334 if (chdir(argv[1]) == -1) {
2335 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2336 return 1;
2337 }
2338
2339 Entropy entropy;
2340 if (!entropy.open()) {
2341 return 1;
2342 }
Kenny Root70e3a862012-02-15 17:20:23 -08002343
2344 keymaster_device_t* dev;
2345 if (keymaster_device_initialize(&dev)) {
2346 ALOGE("keystore keymaster could not be initialized; exiting");
2347 return 1;
2348 }
2349
Kenny Root70e3a862012-02-15 17:20:23 -08002350 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002351 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002352 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2353 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2354 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2355 if (ret != android::OK) {
2356 ALOGE("Couldn't register binder service!");
2357 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002358 }
Kenny Root07438c82012-11-02 15:41:02 -07002359
2360 /*
2361 * We're the only thread in existence, so we're just going to process
2362 * Binder transaction as a single-threaded program.
2363 */
2364 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002365
2366 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002367 return 1;
2368}