blob: 336a15b97b8b4f06791bdedbe3a4c71a23c1adfa [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
23#include <unistd.h>
24#include <signal.h>
25#include <errno.h>
26#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070027#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080028#include <fcntl.h>
29#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070030#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080031#include <sys/types.h>
32#include <sys/socket.h>
33#include <sys/stat.h>
34#include <sys/time.h>
35#include <arpa/inet.h>
36
37#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070038#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080039#include <openssl/evp.h>
40#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070041#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080042
Kenny Root70e3a862012-02-15 17:20:23 -080043#include <hardware/keymaster.h>
44
Kenny Root17208e02013-09-04 13:56:03 -070045#include <keymaster/softkeymaster.h>
46
Kenny Root655b9582013-04-04 08:37:42 -070047#include <utils/String8.h>
Kenny Root822c3a92012-03-23 16:34:39 -070048#include <utils/UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070049#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080050
Kenny Root07438c82012-11-02 15:41:02 -070051#include <keystore/IKeystoreService.h>
52#include <binder/IPCThreadState.h>
53#include <binder/IServiceManager.h>
54
Kenny Roota91203b2012-02-15 15:00:46 -080055#include <cutils/log.h>
56#include <cutils/sockets.h>
57#include <private/android_filesystem_config.h>
58
Kenny Root07438c82012-11-02 15:41:02 -070059#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080060
Kenny Root96427ba2013-08-16 14:02:41 -070061#include "defaults.h"
62
Kenny Roota91203b2012-02-15 15:00:46 -080063/* KeyStore is a secured storage for key-value pairs. In this implementation,
64 * each file stores one key-value pair. Keys are encoded in file names, and
65 * values are encrypted with checksums. The encryption key is protected by a
66 * user-defined password. To keep things simple, buffers are always larger than
67 * the maximum space we needed, so boundary checks on buffers are omitted. */
68
69#define KEY_SIZE ((NAME_MAX - 15) / 2)
70#define VALUE_SIZE 32768
71#define PASSWORD_SIZE VALUE_SIZE
72
Kenny Root822c3a92012-03-23 16:34:39 -070073
Kenny Root96427ba2013-08-16 14:02:41 -070074struct BIGNUM_Delete {
75 void operator()(BIGNUM* p) const {
76 BN_free(p);
77 }
78};
79typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
80
Kenny Root822c3a92012-03-23 16:34:39 -070081struct BIO_Delete {
82 void operator()(BIO* p) const {
83 BIO_free(p);
84 }
85};
86typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
87
88struct EVP_PKEY_Delete {
89 void operator()(EVP_PKEY* p) const {
90 EVP_PKEY_free(p);
91 }
92};
93typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
94
95struct PKCS8_PRIV_KEY_INFO_Delete {
96 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
97 PKCS8_PRIV_KEY_INFO_free(p);
98 }
99};
100typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
101
102
Kenny Root70e3a862012-02-15 17:20:23 -0800103static int keymaster_device_initialize(keymaster_device_t** dev) {
104 int rc;
105
106 const hw_module_t* mod;
107 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
108 if (rc) {
109 ALOGE("could not find any keystore module");
110 goto out;
111 }
112
113 rc = keymaster_open(mod, dev);
114 if (rc) {
115 ALOGE("could not open keymaster device in %s (%s)",
116 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
117 goto out;
118 }
119
120 return 0;
121
122out:
123 *dev = NULL;
124 return rc;
125}
126
127static void keymaster_device_release(keymaster_device_t* dev) {
128 keymaster_close(dev);
129}
130
Kenny Root07438c82012-11-02 15:41:02 -0700131/***************
132 * PERMISSIONS *
133 ***************/
134
135/* Here are the permissions, actions, users, and the main function. */
136typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700137 P_TEST = 1 << 0,
138 P_GET = 1 << 1,
139 P_INSERT = 1 << 2,
140 P_DELETE = 1 << 3,
141 P_EXIST = 1 << 4,
142 P_SAW = 1 << 5,
143 P_RESET = 1 << 6,
144 P_PASSWORD = 1 << 7,
145 P_LOCK = 1 << 8,
146 P_UNLOCK = 1 << 9,
147 P_ZERO = 1 << 10,
148 P_SIGN = 1 << 11,
149 P_VERIFY = 1 << 12,
150 P_GRANT = 1 << 13,
151 P_DUPLICATE = 1 << 14,
Kenny Roota9bb5492013-04-01 16:29:11 -0700152 P_CLEAR_UID = 1 << 15,
Kenny Root07438c82012-11-02 15:41:02 -0700153} perm_t;
154
155static struct user_euid {
156 uid_t uid;
157 uid_t euid;
158} user_euids[] = {
159 {AID_VPN, AID_SYSTEM},
160 {AID_WIFI, AID_SYSTEM},
161 {AID_ROOT, AID_SYSTEM},
162};
163
164static struct user_perm {
165 uid_t uid;
166 perm_t perms;
167} user_perms[] = {
168 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
169 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
170 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
171 {AID_ROOT, static_cast<perm_t>(P_GET) },
172};
173
174static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
175 | P_VERIFY);
176
Kenny Root655b9582013-04-04 08:37:42 -0700177/**
178 * Returns the app ID (in the Android multi-user sense) for the current
179 * UNIX UID.
180 */
181static uid_t get_app_id(uid_t uid) {
182 return uid % AID_USER;
183}
184
185/**
186 * Returns the user ID (in the Android multi-user sense) for the current
187 * UNIX UID.
188 */
189static uid_t get_user_id(uid_t uid) {
190 return uid / AID_USER;
191}
192
193
Kenny Root07438c82012-11-02 15:41:02 -0700194static bool has_permission(uid_t uid, perm_t perm) {
Kenny Root655b9582013-04-04 08:37:42 -0700195 // All system users are equivalent for multi-user support.
196 if (get_app_id(uid) == AID_SYSTEM) {
197 uid = AID_SYSTEM;
198 }
199
Kenny Root07438c82012-11-02 15:41:02 -0700200 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
201 struct user_perm user = user_perms[i];
202 if (user.uid == uid) {
203 return user.perms & perm;
204 }
205 }
206
207 return DEFAULT_PERMS & perm;
208}
209
Kenny Root49468902013-03-19 13:41:33 -0700210/**
211 * Returns the UID that the callingUid should act as. This is here for
212 * legacy support of the WiFi and VPN systems and should be removed
213 * when WiFi can operate in its own namespace.
214 */
Kenny Root07438c82012-11-02 15:41:02 -0700215static uid_t get_keystore_euid(uid_t uid) {
216 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
217 struct user_euid user = user_euids[i];
218 if (user.uid == uid) {
219 return user.euid;
220 }
221 }
222
223 return uid;
224}
225
Kenny Root49468902013-03-19 13:41:33 -0700226/**
227 * Returns true if the callingUid is allowed to interact in the targetUid's
228 * namespace.
229 */
230static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
231 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
232 struct user_euid user = user_euids[i];
233 if (user.euid == callingUid && user.uid == targetUid) {
234 return true;
235 }
236 }
237
238 return false;
239}
240
Kenny Roota91203b2012-02-15 15:00:46 -0800241/* Here is the encoding of keys. This is necessary in order to allow arbitrary
242 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
243 * into two bytes. The first byte is one of [+-.] which represents the first
244 * two bits of the character. The second byte encodes the rest of the bits into
245 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
246 * that Base64 cannot be used here due to the need of prefix match on keys. */
247
Kenny Root655b9582013-04-04 08:37:42 -0700248static size_t encode_key_length(const android::String8& keyName) {
249 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
250 size_t length = keyName.length();
251 for (int i = length; i > 0; --i, ++in) {
252 if (*in < '0' || *in > '~') {
253 ++length;
254 }
255 }
256 return length;
257}
258
Kenny Root07438c82012-11-02 15:41:02 -0700259static int encode_key(char* out, const android::String8& keyName) {
260 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
261 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800262 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700263 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800264 *out = '+' + (*in >> 6);
265 *++out = '0' + (*in & 0x3F);
266 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700267 } else {
268 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800269 }
270 }
271 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800272 return length;
273}
274
Kenny Root07438c82012-11-02 15:41:02 -0700275/*
276 * Converts from the "escaped" format on disk to actual name.
277 * This will be smaller than the input string.
278 *
279 * Characters that should combine with the next at the end will be truncated.
280 */
281static size_t decode_key_length(const char* in, size_t length) {
282 size_t outLength = 0;
283
284 for (const char* end = in + length; in < end; in++) {
285 /* This combines with the next character. */
286 if (*in < '0' || *in > '~') {
287 continue;
288 }
289
290 outLength++;
291 }
292 return outLength;
293}
294
295static void decode_key(char* out, const char* in, size_t length) {
296 for (const char* end = in + length; in < end; in++) {
297 if (*in < '0' || *in > '~') {
298 /* Truncate combining characters at the end. */
299 if (in + 1 >= end) {
300 break;
301 }
302
303 *out = (*in++ - '+') << 6;
304 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800305 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700306 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800307 }
308 }
309 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800310}
311
312static size_t readFully(int fd, uint8_t* data, size_t size) {
313 size_t remaining = size;
314 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800315 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800316 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800317 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800318 }
319 data += n;
320 remaining -= n;
321 }
322 return size;
323}
324
325static size_t writeFully(int fd, uint8_t* data, size_t size) {
326 size_t remaining = size;
327 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800328 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
329 if (n < 0) {
330 ALOGW("write failed: %s", strerror(errno));
331 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800332 }
333 data += n;
334 remaining -= n;
335 }
336 return size;
337}
338
339class Entropy {
340public:
341 Entropy() : mRandom(-1) {}
342 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800343 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800344 close(mRandom);
345 }
346 }
347
348 bool open() {
349 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800350 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
351 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800352 ALOGE("open: %s: %s", randomDevice, strerror(errno));
353 return false;
354 }
355 return true;
356 }
357
Kenny Root51878182012-03-13 12:53:19 -0700358 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800359 return (readFully(mRandom, data, size) == size);
360 }
361
362private:
363 int mRandom;
364};
365
366/* Here is the file format. There are two parts in blob.value, the secret and
367 * the description. The secret is stored in ciphertext, and its original size
368 * can be found in blob.length. The description is stored after the secret in
369 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700370 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700371 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800372 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
373 * and decryptBlob(). Thus they should not be accessed from outside. */
374
Kenny Root822c3a92012-03-23 16:34:39 -0700375/* ** Note to future implementors of encryption: **
376 * Currently this is the construction:
377 * metadata || Enc(MD5(data) || data)
378 *
379 * This should be the construction used for encrypting if re-implementing:
380 *
381 * Derive independent keys for encryption and MAC:
382 * Kenc = AES_encrypt(masterKey, "Encrypt")
383 * Kmac = AES_encrypt(masterKey, "MAC")
384 *
385 * Store this:
386 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
387 * HMAC(Kmac, metadata || Enc(data))
388 */
Kenny Roota91203b2012-02-15 15:00:46 -0800389struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700390 uint8_t version;
391 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700392 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800393 uint8_t info;
394 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700395 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800396 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700397 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800398 int32_t length; // in network byte order when encrypted
399 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
400};
401
Kenny Root822c3a92012-03-23 16:34:39 -0700402typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700403 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700404 TYPE_GENERIC = 1,
405 TYPE_MASTER_KEY = 2,
406 TYPE_KEY_PAIR = 3,
407} BlobType;
408
Kenny Rootf9119d62013-04-03 09:22:15 -0700409static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700410
Kenny Roota91203b2012-02-15 15:00:46 -0800411class Blob {
412public:
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
424 mBlob.flags = KEYSTORE_FLAG_NONE;
Kenny Roota91203b2012-02-15 15:00:46 -0800425 }
426
427 Blob(blob b) {
428 mBlob = b;
429 }
430
431 Blob() {}
432
Kenny Root51878182012-03-13 12:53:19 -0700433 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800434 return mBlob.value;
435 }
436
Kenny Root51878182012-03-13 12:53:19 -0700437 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800438 return mBlob.length;
439 }
440
Kenny Root51878182012-03-13 12:53:19 -0700441 const uint8_t* getInfo() const {
442 return mBlob.value + mBlob.length;
443 }
444
445 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800446 return mBlob.info;
447 }
448
Kenny Root822c3a92012-03-23 16:34:39 -0700449 uint8_t getVersion() const {
450 return mBlob.version;
451 }
452
Kenny Rootf9119d62013-04-03 09:22:15 -0700453 bool isEncrypted() const {
454 if (mBlob.version < 2) {
455 return true;
456 }
457
458 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
459 }
460
461 void setEncrypted(bool encrypted) {
462 if (encrypted) {
463 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
464 } else {
465 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
466 }
467 }
468
Kenny Root17208e02013-09-04 13:56:03 -0700469 bool isFallback() const {
470 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
471 }
472
473 void setFallback(bool fallback) {
474 if (fallback) {
475 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
476 } else {
477 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
478 }
479 }
480
Kenny Root822c3a92012-03-23 16:34:39 -0700481 void setVersion(uint8_t version) {
482 mBlob.version = version;
483 }
484
485 BlobType getType() const {
486 return BlobType(mBlob.type);
487 }
488
489 void setType(BlobType type) {
490 mBlob.type = uint8_t(type);
491 }
492
Kenny Rootf9119d62013-04-03 09:22:15 -0700493 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
494 ALOGV("writing blob %s", filename);
495 if (isEncrypted()) {
496 if (state != STATE_NO_ERROR) {
497 ALOGD("couldn't insert encrypted blob while not unlocked");
498 return LOCKED;
499 }
500
501 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
502 ALOGW("Could not read random data for: %s", filename);
503 return SYSTEM_ERROR;
504 }
Kenny Roota91203b2012-02-15 15:00:46 -0800505 }
506
507 // data includes the value and the value's length
508 size_t dataLength = mBlob.length + sizeof(mBlob.length);
509 // pad data to the AES_BLOCK_SIZE
510 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
511 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
512 // encrypted data includes the digest value
513 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
514 // move info after space for padding
515 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
516 // zero padding area
517 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
518
519 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800520
Kenny Rootf9119d62013-04-03 09:22:15 -0700521 if (isEncrypted()) {
522 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800523
Kenny Rootf9119d62013-04-03 09:22:15 -0700524 uint8_t vector[AES_BLOCK_SIZE];
525 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
526 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
527 aes_key, vector, AES_ENCRYPT);
528 }
529
Kenny Roota91203b2012-02-15 15:00:46 -0800530 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
531 size_t fileLength = encryptedLength + headerLength + mBlob.info;
532
533 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800534 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
535 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
536 if (out < 0) {
537 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800538 return SYSTEM_ERROR;
539 }
540 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
541 if (close(out) != 0) {
542 return SYSTEM_ERROR;
543 }
544 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800545 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800546 unlink(tmpFileName);
547 return SYSTEM_ERROR;
548 }
Kenny Root150ca932012-11-14 14:29:02 -0800549 if (rename(tmpFileName, filename) == -1) {
550 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
551 return SYSTEM_ERROR;
552 }
553 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800554 }
555
Kenny Rootf9119d62013-04-03 09:22:15 -0700556 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
557 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800558 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
559 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800560 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
561 }
562 // fileLength may be less than sizeof(mBlob) since the in
563 // memory version has extra padding to tolerate rounding up to
564 // the AES_BLOCK_SIZE
565 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
566 if (close(in) != 0) {
567 return SYSTEM_ERROR;
568 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700569
570 if (isEncrypted() && (state != STATE_NO_ERROR)) {
571 return LOCKED;
572 }
573
Kenny Roota91203b2012-02-15 15:00:46 -0800574 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
575 if (fileLength < headerLength) {
576 return VALUE_CORRUPTED;
577 }
578
579 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700580 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800581 return VALUE_CORRUPTED;
582 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700583
584 ssize_t digestedLength;
585 if (isEncrypted()) {
586 if (encryptedLength % AES_BLOCK_SIZE != 0) {
587 return VALUE_CORRUPTED;
588 }
589
590 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
591 mBlob.vector, AES_DECRYPT);
592 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
593 uint8_t computedDigest[MD5_DIGEST_LENGTH];
594 MD5(mBlob.digested, digestedLength, computedDigest);
595 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
596 return VALUE_CORRUPTED;
597 }
598 } else {
599 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800600 }
601
602 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
603 mBlob.length = ntohl(mBlob.length);
604 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
605 return VALUE_CORRUPTED;
606 }
607 if (mBlob.info != 0) {
608 // move info from after padding to after data
609 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
610 }
Kenny Root07438c82012-11-02 15:41:02 -0700611 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800612 }
613
614private:
615 struct blob mBlob;
616};
617
Kenny Root655b9582013-04-04 08:37:42 -0700618class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800619public:
Kenny Root655b9582013-04-04 08:37:42 -0700620 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
621 asprintf(&mUserDir, "user_%u", mUserId);
622 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
623 }
624
625 ~UserState() {
626 free(mUserDir);
627 free(mMasterKeyFile);
628 }
629
630 bool initialize() {
631 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
632 ALOGE("Could not create directory '%s'", mUserDir);
633 return false;
634 }
635
636 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800637 setState(STATE_LOCKED);
638 } else {
639 setState(STATE_UNINITIALIZED);
640 }
Kenny Root70e3a862012-02-15 17:20:23 -0800641
Kenny Root655b9582013-04-04 08:37:42 -0700642 return true;
643 }
644
645 uid_t getUserId() const {
646 return mUserId;
647 }
648
649 const char* getUserDirName() const {
650 return mUserDir;
651 }
652
653 const char* getMasterKeyFileName() const {
654 return mMasterKeyFile;
655 }
656
657 void setState(State state) {
658 mState = state;
659 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
660 mRetry = MAX_RETRY;
661 }
Kenny Roota91203b2012-02-15 15:00:46 -0800662 }
663
Kenny Root51878182012-03-13 12:53:19 -0700664 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800665 return mState;
666 }
667
Kenny Root51878182012-03-13 12:53:19 -0700668 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800669 return mRetry;
670 }
671
Kenny Root655b9582013-04-04 08:37:42 -0700672 void zeroizeMasterKeysInMemory() {
673 memset(mMasterKey, 0, sizeof(mMasterKey));
674 memset(mSalt, 0, sizeof(mSalt));
675 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
676 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800677 }
678
Kenny Root655b9582013-04-04 08:37:42 -0700679 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
680 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800681 return SYSTEM_ERROR;
682 }
Kenny Root655b9582013-04-04 08:37:42 -0700683 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800684 if (response != NO_ERROR) {
685 return response;
686 }
687 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700688 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800689 }
690
Kenny Root655b9582013-04-04 08:37:42 -0700691 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800692 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
693 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
694 AES_KEY passwordAesKey;
695 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700696 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700697 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800698 }
699
Kenny Root655b9582013-04-04 08:37:42 -0700700 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
701 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800702 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800703 return SYSTEM_ERROR;
704 }
705
706 // we read the raw blob to just to get the salt to generate
707 // the AES key, then we create the Blob to use with decryptBlob
708 blob rawBlob;
709 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
710 if (close(in) != 0) {
711 return SYSTEM_ERROR;
712 }
713 // find salt at EOF if present, otherwise we have an old file
714 uint8_t* salt;
715 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
716 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
717 } else {
718 salt = NULL;
719 }
720 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
721 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
722 AES_KEY passwordAesKey;
723 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
724 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700725 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
726 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800727 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700728 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800729 }
730 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
731 // if salt was missing, generate one and write a new master key file with the salt.
732 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700733 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800734 return SYSTEM_ERROR;
735 }
Kenny Root655b9582013-04-04 08:37:42 -0700736 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800737 }
738 if (response == NO_ERROR) {
739 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
740 setupMasterKeys();
741 }
742 return response;
743 }
744 if (mRetry <= 0) {
745 reset();
746 return UNINITIALIZED;
747 }
748 --mRetry;
749 switch (mRetry) {
750 case 0: return WRONG_PASSWORD_0;
751 case 1: return WRONG_PASSWORD_1;
752 case 2: return WRONG_PASSWORD_2;
753 case 3: return WRONG_PASSWORD_3;
754 default: return WRONG_PASSWORD_3;
755 }
756 }
757
Kenny Root655b9582013-04-04 08:37:42 -0700758 AES_KEY* getEncryptionKey() {
759 return &mMasterKeyEncryption;
760 }
761
762 AES_KEY* getDecryptionKey() {
763 return &mMasterKeyDecryption;
764 }
765
Kenny Roota91203b2012-02-15 15:00:46 -0800766 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700767 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800768 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700769 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800770 return false;
771 }
Kenny Root655b9582013-04-04 08:37:42 -0700772
773 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800774 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700775 // We only care about files.
776 if (file->d_type != DT_REG) {
777 continue;
778 }
779
780 // Skip anything that starts with a "."
781 if (file->d_name[0] == '.') {
782 continue;
783 }
784
785 // Find the current file's UID.
786 char* end;
787 unsigned long thisUid = strtoul(file->d_name, &end, 10);
788 if (end[0] != '_' || end[1] == 0) {
789 continue;
790 }
791
792 // Skip if this is not our user.
793 if (get_user_id(thisUid) != mUserId) {
794 continue;
795 }
796
797 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800798 }
799 closedir(dir);
800 return true;
801 }
802
Kenny Root655b9582013-04-04 08:37:42 -0700803private:
804 static const int MASTER_KEY_SIZE_BYTES = 16;
805 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
806
807 static const int MAX_RETRY = 4;
808 static const size_t SALT_SIZE = 16;
809
810 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
811 uint8_t* salt) {
812 size_t saltSize;
813 if (salt != NULL) {
814 saltSize = SALT_SIZE;
815 } else {
816 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
817 salt = (uint8_t*) "keystore";
818 // sizeof = 9, not strlen = 8
819 saltSize = sizeof("keystore");
820 }
821
822 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
823 saltSize, 8192, keySize, key);
824 }
825
826 bool generateSalt(Entropy* entropy) {
827 return entropy->generate_random_data(mSalt, sizeof(mSalt));
828 }
829
830 bool generateMasterKey(Entropy* entropy) {
831 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
832 return false;
833 }
834 if (!generateSalt(entropy)) {
835 return false;
836 }
837 return true;
838 }
839
840 void setupMasterKeys() {
841 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
842 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
843 setState(STATE_NO_ERROR);
844 }
845
846 uid_t mUserId;
847
848 char* mUserDir;
849 char* mMasterKeyFile;
850
851 State mState;
852 int8_t mRetry;
853
854 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
855 uint8_t mSalt[SALT_SIZE];
856
857 AES_KEY mMasterKeyEncryption;
858 AES_KEY mMasterKeyDecryption;
859};
860
861typedef struct {
862 uint32_t uid;
863 const uint8_t* filename;
864} grant_t;
865
866class KeyStore {
867public:
868 KeyStore(Entropy* entropy, keymaster_device_t* device)
869 : mEntropy(entropy)
870 , mDevice(device)
871 {
872 memset(&mMetaData, '\0', sizeof(mMetaData));
873 }
874
875 ~KeyStore() {
876 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
877 it != mGrants.end(); it++) {
878 delete *it;
879 mGrants.erase(it);
880 }
881
882 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
883 it != mMasterKeys.end(); it++) {
884 delete *it;
885 mMasterKeys.erase(it);
886 }
887 }
888
889 keymaster_device_t* getDevice() const {
890 return mDevice;
891 }
892
893 ResponseCode initialize() {
894 readMetaData();
895 if (upgradeKeystore()) {
896 writeMetaData();
897 }
898
899 return ::NO_ERROR;
900 }
901
902 State getState(uid_t uid) {
903 return getUserState(uid)->getState();
904 }
905
906 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
907 UserState* userState = getUserState(uid);
908 return userState->initialize(pw, mEntropy);
909 }
910
911 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
912 uid_t user_id = get_user_id(uid);
913 UserState* userState = getUserState(user_id);
914 return userState->writeMasterKey(pw, mEntropy);
915 }
916
917 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
918 uid_t user_id = get_user_id(uid);
919 UserState* userState = getUserState(user_id);
920 return userState->readMasterKey(pw, mEntropy);
921 }
922
923 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700924 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700925 encode_key(encoded, keyName);
926 return android::String8(encoded);
927 }
928
929 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700930 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700931 encode_key(encoded, keyName);
932 return android::String8::format("%u_%s", uid, encoded);
933 }
934
935 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700936 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700937 encode_key(encoded, keyName);
938 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
939 encoded);
940 }
941
942 bool reset(uid_t uid) {
943 UserState* userState = getUserState(uid);
944 userState->zeroizeMasterKeysInMemory();
945 userState->setState(STATE_UNINITIALIZED);
946 return userState->reset();
947 }
948
949 bool isEmpty(uid_t uid) const {
950 const UserState* userState = getUserState(uid);
951 if (userState == NULL) {
952 return true;
953 }
954
955 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800956 struct dirent* file;
957 if (!dir) {
958 return true;
959 }
960 bool result = true;
Kenny Root655b9582013-04-04 08:37:42 -0700961
962 char filename[NAME_MAX];
963 int n = snprintf(filename, sizeof(filename), "%u_", uid);
964
Kenny Roota91203b2012-02-15 15:00:46 -0800965 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700966 // We only care about files.
967 if (file->d_type != DT_REG) {
968 continue;
969 }
970
971 // Skip anything that starts with a "."
972 if (file->d_name[0] == '.') {
973 continue;
974 }
975
976 if (!strncmp(file->d_name, filename, n)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800977 result = false;
978 break;
979 }
980 }
981 closedir(dir);
982 return result;
983 }
984
Kenny Root655b9582013-04-04 08:37:42 -0700985 void lock(uid_t uid) {
986 UserState* userState = getUserState(uid);
987 userState->zeroizeMasterKeysInMemory();
988 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -0800989 }
990
Kenny Root655b9582013-04-04 08:37:42 -0700991 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
992 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -0700993 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
994 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -0700995 if (rc != NO_ERROR) {
996 return rc;
997 }
998
999 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001000 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001001 /* If we upgrade the key, we need to write it to disk again. Then
1002 * it must be read it again since the blob is encrypted each time
1003 * it's written.
1004 */
Kenny Root655b9582013-04-04 08:37:42 -07001005 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1006 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001007 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1008 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001009 return rc;
1010 }
1011 }
Kenny Root822c3a92012-03-23 16:34:39 -07001012 }
1013
Kenny Root17208e02013-09-04 13:56:03 -07001014 /*
1015 * This will upgrade software-backed keys to hardware-backed keys when
1016 * the HAL for the device supports the newer key types.
1017 */
1018 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1019 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1020 && keyBlob->isFallback()) {
1021 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1022 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1023
1024 // The HAL allowed the import, reget the key to have the "fresh"
1025 // version.
1026 if (imported == NO_ERROR) {
1027 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1028 }
1029 }
1030
Kenny Rootd53bc922013-03-21 14:10:15 -07001031 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001032 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1033 return KEY_NOT_FOUND;
1034 }
1035
1036 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001037 }
1038
Kenny Root655b9582013-04-04 08:37:42 -07001039 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1040 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001041 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1042 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001043 }
1044
Kenny Root07438c82012-11-02 15:41:02 -07001045 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001046 const grant_t* existing = getGrant(filename, granteeUid);
1047 if (existing == NULL) {
1048 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001049 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001050 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001051 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001052 }
1053 }
1054
Kenny Root07438c82012-11-02 15:41:02 -07001055 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001056 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1057 it != mGrants.end(); it++) {
1058 grant_t* grant = *it;
1059 if (grant->uid == granteeUid
1060 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1061 mGrants.erase(it);
1062 return true;
1063 }
Kenny Root70e3a862012-02-15 17:20:23 -08001064 }
Kenny Root70e3a862012-02-15 17:20:23 -08001065 return false;
1066 }
1067
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001068 bool hasGrant(const char* filename, const uid_t uid) const {
1069 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001070 }
1071
Kenny Rootf9119d62013-04-03 09:22:15 -07001072 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1073 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001074 uint8_t* data;
1075 size_t dataLength;
1076 int rc;
1077
1078 if (mDevice->import_keypair == NULL) {
1079 ALOGE("Keymaster doesn't support import!");
1080 return SYSTEM_ERROR;
1081 }
1082
Kenny Root17208e02013-09-04 13:56:03 -07001083 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001084 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001085 if (rc) {
Kenny Root17208e02013-09-04 13:56:03 -07001086 // If this is an old device HAL, try to fall back to an old version
1087 if (mDevice->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_2) {
1088 rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength);
1089 isFallback = true;
1090 }
1091
1092 if (rc) {
1093 ALOGE("Error while importing keypair: %d", rc);
1094 return SYSTEM_ERROR;
1095 }
Kenny Root822c3a92012-03-23 16:34:39 -07001096 }
1097
1098 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1099 free(data);
1100
Kenny Rootf9119d62013-04-03 09:22:15 -07001101 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001102 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001103
Kenny Root655b9582013-04-04 08:37:42 -07001104 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001105 }
1106
Kenny Root1b0e3932013-09-05 13:06:32 -07001107 bool isHardwareBacked(const android::String16& keyType) const {
1108 if (mDevice == NULL) {
1109 ALOGW("can't get keymaster device");
1110 return false;
1111 }
1112
1113 if (sRSAKeyType == keyType) {
1114 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1115 } else {
1116 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1117 && (mDevice->common.module->module_api_version
1118 >= KEYMASTER_MODULE_API_VERSION_0_2);
1119 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001120 }
1121
Kenny Root655b9582013-04-04 08:37:42 -07001122 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1123 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001124 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001125
1126 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1127 if (responseCode == NO_ERROR) {
1128 return responseCode;
1129 }
1130
1131 // If this is one of the legacy UID->UID mappings, use it.
1132 uid_t euid = get_keystore_euid(uid);
1133 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001134 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001135 responseCode = get(filepath8.string(), keyBlob, type, uid);
1136 if (responseCode == NO_ERROR) {
1137 return responseCode;
1138 }
1139 }
1140
1141 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001142 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001143 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001144 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001145 if (end[0] != '_' || end[1] == 0) {
1146 return KEY_NOT_FOUND;
1147 }
Kenny Root86b16e82013-09-09 11:15:54 -07001148 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1149 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001150 if (!hasGrant(filepath8.string(), uid)) {
1151 return responseCode;
1152 }
1153
1154 // It is a granted key. Try to load it.
1155 return get(filepath8.string(), keyBlob, type, uid);
1156 }
1157
1158 /**
1159 * Returns any existing UserState or creates it if it doesn't exist.
1160 */
1161 UserState* getUserState(uid_t uid) {
1162 uid_t userId = get_user_id(uid);
1163
1164 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1165 it != mMasterKeys.end(); it++) {
1166 UserState* state = *it;
1167 if (state->getUserId() == userId) {
1168 return state;
1169 }
1170 }
1171
1172 UserState* userState = new UserState(userId);
1173 if (!userState->initialize()) {
1174 /* There's not much we can do if initialization fails. Trying to
1175 * unlock the keystore for that user will fail as well, so any
1176 * subsequent request for this user will just return SYSTEM_ERROR.
1177 */
1178 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1179 }
1180 mMasterKeys.add(userState);
1181 return userState;
1182 }
1183
1184 /**
1185 * Returns NULL if the UserState doesn't already exist.
1186 */
1187 const UserState* getUserState(uid_t uid) const {
1188 uid_t userId = get_user_id(uid);
1189
1190 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1191 it != mMasterKeys.end(); it++) {
1192 UserState* state = *it;
1193 if (state->getUserId() == userId) {
1194 return state;
1195 }
1196 }
1197
1198 return NULL;
1199 }
1200
Kenny Roota91203b2012-02-15 15:00:46 -08001201private:
Kenny Root655b9582013-04-04 08:37:42 -07001202 static const char* sOldMasterKey;
1203 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001204 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001205 Entropy* mEntropy;
1206
Kenny Root70e3a862012-02-15 17:20:23 -08001207 keymaster_device_t* mDevice;
1208
Kenny Root655b9582013-04-04 08:37:42 -07001209 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001210
Kenny Root655b9582013-04-04 08:37:42 -07001211 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001212
Kenny Root655b9582013-04-04 08:37:42 -07001213 typedef struct {
1214 uint32_t version;
1215 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001216
Kenny Root655b9582013-04-04 08:37:42 -07001217 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001218
Kenny Root655b9582013-04-04 08:37:42 -07001219 const grant_t* getGrant(const char* filename, uid_t uid) const {
1220 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1221 it != mGrants.end(); it++) {
1222 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001223 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001224 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001225 return grant;
1226 }
1227 }
Kenny Root70e3a862012-02-15 17:20:23 -08001228 return NULL;
1229 }
1230
Kenny Root822c3a92012-03-23 16:34:39 -07001231 /**
1232 * Upgrade code. This will upgrade the key from the current version
1233 * to whatever is newest.
1234 */
Kenny Root655b9582013-04-04 08:37:42 -07001235 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1236 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001237 bool updated = false;
1238 uint8_t version = oldVersion;
1239
1240 /* From V0 -> V1: All old types were unknown */
1241 if (version == 0) {
1242 ALOGV("upgrading to version 1 and setting type %d", type);
1243
1244 blob->setType(type);
1245 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001246 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001247 }
1248 version = 1;
1249 updated = true;
1250 }
1251
Kenny Rootf9119d62013-04-03 09:22:15 -07001252 /* From V1 -> V2: All old keys were encrypted */
1253 if (version == 1) {
1254 ALOGV("upgrading to version 2");
1255
1256 blob->setEncrypted(true);
1257 version = 2;
1258 updated = true;
1259 }
1260
Kenny Root822c3a92012-03-23 16:34:39 -07001261 /*
1262 * If we've updated, set the key blob to the right version
1263 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001264 */
Kenny Root822c3a92012-03-23 16:34:39 -07001265 if (updated) {
1266 ALOGV("updated and writing file %s", filename);
1267 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001268 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001269
1270 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001271 }
1272
1273 /**
1274 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1275 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1276 * Then it overwrites the original blob with the new blob
1277 * format that is returned from the keymaster.
1278 */
Kenny Root655b9582013-04-04 08:37:42 -07001279 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001280 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1281 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1282 if (b.get() == NULL) {
1283 ALOGE("Problem instantiating BIO");
1284 return SYSTEM_ERROR;
1285 }
1286
1287 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1288 if (pkey.get() == NULL) {
1289 ALOGE("Couldn't read old PEM file");
1290 return SYSTEM_ERROR;
1291 }
1292
1293 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1294 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1295 if (len < 0) {
1296 ALOGE("Couldn't measure PKCS#8 length");
1297 return SYSTEM_ERROR;
1298 }
1299
Kenny Root70c98892013-02-07 09:10:36 -08001300 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1301 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001302 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1303 ALOGE("Couldn't convert to PKCS#8");
1304 return SYSTEM_ERROR;
1305 }
1306
Kenny Rootf9119d62013-04-03 09:22:15 -07001307 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1308 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001309 if (rc != NO_ERROR) {
1310 return rc;
1311 }
1312
Kenny Root655b9582013-04-04 08:37:42 -07001313 return get(filename, blob, TYPE_KEY_PAIR, uid);
1314 }
1315
1316 void readMetaData() {
1317 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1318 if (in < 0) {
1319 return;
1320 }
1321 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1322 if (fileLength != sizeof(mMetaData)) {
1323 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1324 sizeof(mMetaData));
1325 }
1326 close(in);
1327 }
1328
1329 void writeMetaData() {
1330 const char* tmpFileName = ".metadata.tmp";
1331 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1332 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1333 if (out < 0) {
1334 ALOGE("couldn't write metadata file: %s", strerror(errno));
1335 return;
1336 }
1337 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1338 if (fileLength != sizeof(mMetaData)) {
1339 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1340 sizeof(mMetaData));
1341 }
1342 close(out);
1343 rename(tmpFileName, sMetaDataFile);
1344 }
1345
1346 bool upgradeKeystore() {
1347 bool upgraded = false;
1348
1349 if (mMetaData.version == 0) {
1350 UserState* userState = getUserState(0);
1351
1352 // Initialize first so the directory is made.
1353 userState->initialize();
1354
1355 // Migrate the old .masterkey file to user 0.
1356 if (access(sOldMasterKey, R_OK) == 0) {
1357 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1358 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1359 return false;
1360 }
1361 }
1362
1363 // Initialize again in case we had a key.
1364 userState->initialize();
1365
1366 // Try to migrate existing keys.
1367 DIR* dir = opendir(".");
1368 if (!dir) {
1369 // Give up now; maybe we can upgrade later.
1370 ALOGE("couldn't open keystore's directory; something is wrong");
1371 return false;
1372 }
1373
1374 struct dirent* file;
1375 while ((file = readdir(dir)) != NULL) {
1376 // We only care about files.
1377 if (file->d_type != DT_REG) {
1378 continue;
1379 }
1380
1381 // Skip anything that starts with a "."
1382 if (file->d_name[0] == '.') {
1383 continue;
1384 }
1385
1386 // Find the current file's user.
1387 char* end;
1388 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1389 if (end[0] != '_' || end[1] == 0) {
1390 continue;
1391 }
1392 UserState* otherUser = getUserState(thisUid);
1393 if (otherUser->getUserId() != 0) {
1394 unlinkat(dirfd(dir), file->d_name, 0);
1395 }
1396
1397 // Rename the file into user directory.
1398 DIR* otherdir = opendir(otherUser->getUserDirName());
1399 if (otherdir == NULL) {
1400 ALOGW("couldn't open user directory for rename");
1401 continue;
1402 }
1403 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1404 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1405 }
1406 closedir(otherdir);
1407 }
1408 closedir(dir);
1409
1410 mMetaData.version = 1;
1411 upgraded = true;
1412 }
1413
1414 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001415 }
Kenny Roota91203b2012-02-15 15:00:46 -08001416};
1417
Kenny Root655b9582013-04-04 08:37:42 -07001418const char* KeyStore::sOldMasterKey = ".masterkey";
1419const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001420
Kenny Root1b0e3932013-09-05 13:06:32 -07001421const android::String16 KeyStore::sRSAKeyType("RSA");
1422
Kenny Root07438c82012-11-02 15:41:02 -07001423namespace android {
1424class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1425public:
1426 KeyStoreProxy(KeyStore* keyStore)
1427 : mKeyStore(keyStore)
1428 {
Kenny Roota91203b2012-02-15 15:00:46 -08001429 }
Kenny Roota91203b2012-02-15 15:00:46 -08001430
Kenny Root07438c82012-11-02 15:41:02 -07001431 void binderDied(const wp<IBinder>&) {
1432 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001433 }
Kenny Roota91203b2012-02-15 15:00:46 -08001434
Kenny Root07438c82012-11-02 15:41:02 -07001435 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001436 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1437 if (!has_permission(callingUid, P_TEST)) {
1438 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001439 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001440 }
Kenny Roota91203b2012-02-15 15:00:46 -08001441
Kenny Root655b9582013-04-04 08:37:42 -07001442 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001443 }
1444
Kenny Root07438c82012-11-02 15:41:02 -07001445 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001446 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1447 if (!has_permission(callingUid, P_GET)) {
1448 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001449 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001450 }
Kenny Root07438c82012-11-02 15:41:02 -07001451
Kenny Root07438c82012-11-02 15:41:02 -07001452 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001453 Blob keyBlob;
Kenny Root49468902013-03-19 13:41:33 -07001454
Kenny Root655b9582013-04-04 08:37:42 -07001455 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001456 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001457 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001458 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001459 *item = NULL;
1460 *itemLength = 0;
1461 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001462 }
Kenny Roota91203b2012-02-15 15:00:46 -08001463
Kenny Root07438c82012-11-02 15:41:02 -07001464 *item = (uint8_t*) malloc(keyBlob.getLength());
1465 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1466 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001467
Kenny Root07438c82012-11-02 15:41:02 -07001468 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001469 }
1470
Kenny Rootf9119d62013-04-03 09:22:15 -07001471 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1472 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001473 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1474 if (!has_permission(callingUid, P_INSERT)) {
1475 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001476 return ::PERMISSION_DENIED;
1477 }
Kenny Root07438c82012-11-02 15:41:02 -07001478
Kenny Rootf9119d62013-04-03 09:22:15 -07001479 State state = mKeyStore->getState(callingUid);
1480 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1481 ALOGD("calling get in state: %d", state);
1482 return state;
1483 }
1484
Kenny Root49468902013-03-19 13:41:33 -07001485 if (targetUid == -1) {
1486 targetUid = callingUid;
1487 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001488 return ::PERMISSION_DENIED;
1489 }
1490
Kenny Root07438c82012-11-02 15:41:02 -07001491 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001492 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001493
1494 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Root655b9582013-04-04 08:37:42 -07001495 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001496 }
1497
Kenny Root49468902013-03-19 13:41:33 -07001498 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001499 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1500 if (!has_permission(callingUid, P_DELETE)) {
1501 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001502 return ::PERMISSION_DENIED;
1503 }
Kenny Root70e3a862012-02-15 17:20:23 -08001504
Kenny Root49468902013-03-19 13:41:33 -07001505 if (targetUid == -1) {
1506 targetUid = callingUid;
1507 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001508 return ::PERMISSION_DENIED;
1509 }
1510
Kenny Root07438c82012-11-02 15:41:02 -07001511 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001512 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001513
1514 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001515 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
1516 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001517 if (responseCode != ::NO_ERROR) {
1518 return responseCode;
1519 }
1520 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001521 }
1522
Kenny Root49468902013-03-19 13:41:33 -07001523 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001524 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1525 if (!has_permission(callingUid, P_EXIST)) {
1526 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001527 return ::PERMISSION_DENIED;
1528 }
Kenny Root70e3a862012-02-15 17:20:23 -08001529
Kenny Root49468902013-03-19 13:41:33 -07001530 if (targetUid == -1) {
1531 targetUid = callingUid;
1532 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001533 return ::PERMISSION_DENIED;
1534 }
1535
Kenny Root07438c82012-11-02 15:41:02 -07001536 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001537 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001538
Kenny Root655b9582013-04-04 08:37:42 -07001539 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001540 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1541 }
1542 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001543 }
1544
Kenny Root49468902013-03-19 13:41:33 -07001545 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001546 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1547 if (!has_permission(callingUid, P_SAW)) {
1548 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001549 return ::PERMISSION_DENIED;
1550 }
Kenny Root70e3a862012-02-15 17:20:23 -08001551
Kenny Root49468902013-03-19 13:41:33 -07001552 if (targetUid == -1) {
1553 targetUid = callingUid;
1554 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001555 return ::PERMISSION_DENIED;
1556 }
1557
Kenny Root655b9582013-04-04 08:37:42 -07001558 UserState* userState = mKeyStore->getUserState(targetUid);
1559 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001560 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07001561 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001562 return ::SYSTEM_ERROR;
1563 }
Kenny Root70e3a862012-02-15 17:20:23 -08001564
Kenny Root07438c82012-11-02 15:41:02 -07001565 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001566 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1567 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001568
Kenny Root07438c82012-11-02 15:41:02 -07001569 struct dirent* file;
1570 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001571 // We only care about files.
1572 if (file->d_type != DT_REG) {
1573 continue;
1574 }
1575
1576 // Skip anything that starts with a "."
1577 if (file->d_name[0] == '.') {
1578 continue;
1579 }
1580
1581 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001582 const char* p = &file->d_name[n];
1583 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001584
Kenny Root07438c82012-11-02 15:41:02 -07001585 size_t extra = decode_key_length(p, plen);
1586 char *match = (char*) malloc(extra + 1);
1587 if (match != NULL) {
1588 decode_key(match, p, plen);
1589 matches->push(String16(match, extra));
1590 free(match);
1591 } else {
1592 ALOGW("could not allocate match of size %zd", extra);
1593 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001594 }
1595 }
Kenny Root07438c82012-11-02 15:41:02 -07001596 closedir(dir);
1597
1598 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001599 }
1600
Kenny Root07438c82012-11-02 15:41:02 -07001601 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001602 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1603 if (!has_permission(callingUid, P_RESET)) {
1604 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001605 return ::PERMISSION_DENIED;
1606 }
1607
Kenny Root655b9582013-04-04 08:37:42 -07001608 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001609
1610 const keymaster_device_t* device = mKeyStore->getDevice();
1611 if (device == NULL) {
1612 ALOGE("No keymaster device!");
1613 return ::SYSTEM_ERROR;
1614 }
1615
1616 if (device->delete_all == NULL) {
1617 ALOGV("keymaster device doesn't implement delete_all");
1618 return rc;
1619 }
1620
1621 if (device->delete_all(device)) {
1622 ALOGE("Problem calling keymaster's delete_all");
1623 return ::SYSTEM_ERROR;
1624 }
1625
Kenny Root9a53d3e2012-08-14 10:47:54 -07001626 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001627 }
1628
Kenny Root07438c82012-11-02 15:41:02 -07001629 /*
1630 * Here is the history. To improve the security, the parameters to generate the
1631 * master key has been changed. To make a seamless transition, we update the
1632 * file using the same password when the user unlock it for the first time. If
1633 * any thing goes wrong during the transition, the new file will not overwrite
1634 * the old one. This avoids permanent damages of the existing data.
1635 */
1636 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001637 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1638 if (!has_permission(callingUid, P_PASSWORD)) {
1639 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001640 return ::PERMISSION_DENIED;
1641 }
Kenny Root70e3a862012-02-15 17:20:23 -08001642
Kenny Root07438c82012-11-02 15:41:02 -07001643 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001644
Kenny Root655b9582013-04-04 08:37:42 -07001645 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001646 case ::STATE_UNINITIALIZED: {
1647 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001648 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001649 }
1650 case ::STATE_NO_ERROR: {
1651 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001652 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001653 }
1654 case ::STATE_LOCKED: {
1655 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001656 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001657 }
1658 }
1659 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001660 }
1661
Kenny Root07438c82012-11-02 15:41:02 -07001662 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001663 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1664 if (!has_permission(callingUid, P_LOCK)) {
1665 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001666 return ::PERMISSION_DENIED;
1667 }
Kenny Root70e3a862012-02-15 17:20:23 -08001668
Kenny Root655b9582013-04-04 08:37:42 -07001669 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001670 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001671 ALOGD("calling lock in state: %d", state);
1672 return state;
1673 }
1674
Kenny Root655b9582013-04-04 08:37:42 -07001675 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001676 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001677 }
1678
Kenny Root07438c82012-11-02 15:41:02 -07001679 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001680 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1681 if (!has_permission(callingUid, P_UNLOCK)) {
1682 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001683 return ::PERMISSION_DENIED;
1684 }
1685
Kenny Root655b9582013-04-04 08:37:42 -07001686 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001687 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001688 ALOGD("calling unlock when not locked");
1689 return state;
1690 }
1691
1692 const String8 password8(pw);
1693 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001694 }
1695
Kenny Root07438c82012-11-02 15:41:02 -07001696 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001697 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1698 if (!has_permission(callingUid, P_ZERO)) {
1699 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001700 return -1;
1701 }
Kenny Root70e3a862012-02-15 17:20:23 -08001702
Kenny Root655b9582013-04-04 08:37:42 -07001703 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001704 }
1705
Kenny Root96427ba2013-08-16 14:02:41 -07001706 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1707 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001708 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1709 if (!has_permission(callingUid, P_INSERT)) {
1710 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001711 return ::PERMISSION_DENIED;
1712 }
Kenny Root70e3a862012-02-15 17:20:23 -08001713
Kenny Root49468902013-03-19 13:41:33 -07001714 if (targetUid == -1) {
1715 targetUid = callingUid;
1716 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001717 return ::PERMISSION_DENIED;
1718 }
1719
Kenny Root655b9582013-04-04 08:37:42 -07001720 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001721 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1722 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001723 return state;
1724 }
Kenny Root70e3a862012-02-15 17:20:23 -08001725
Kenny Root07438c82012-11-02 15:41:02 -07001726 uint8_t* data;
1727 size_t dataLength;
1728 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001729 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001730
1731 const keymaster_device_t* device = mKeyStore->getDevice();
1732 if (device == NULL) {
1733 return ::SYSTEM_ERROR;
1734 }
1735
1736 if (device->generate_keypair == NULL) {
1737 return ::SYSTEM_ERROR;
1738 }
1739
Kenny Root17208e02013-09-04 13:56:03 -07001740 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001741 keymaster_dsa_keygen_params_t dsa_params;
1742 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001743
Kenny Root96427ba2013-08-16 14:02:41 -07001744 if (keySize == -1) {
1745 keySize = DSA_DEFAULT_KEY_SIZE;
1746 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1747 || keySize > DSA_MAX_KEY_SIZE) {
1748 ALOGI("invalid key size %d", keySize);
1749 return ::SYSTEM_ERROR;
1750 }
1751 dsa_params.key_size = keySize;
1752
1753 if (args->size() == 3) {
1754 sp<KeystoreArg> gArg = args->itemAt(0);
1755 sp<KeystoreArg> pArg = args->itemAt(1);
1756 sp<KeystoreArg> qArg = args->itemAt(2);
1757
1758 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1759 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1760 dsa_params.generator_len = gArg->size();
1761
1762 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1763 dsa_params.prime_p_len = pArg->size();
1764
1765 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1766 dsa_params.prime_q_len = qArg->size();
1767 } else {
1768 ALOGI("not all DSA parameters were read");
1769 return ::SYSTEM_ERROR;
1770 }
1771 } else if (args->size() != 0) {
1772 ALOGI("DSA args must be 3");
1773 return ::SYSTEM_ERROR;
1774 }
1775
Kenny Root17208e02013-09-04 13:56:03 -07001776 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2) {
1777 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1778 } else {
1779 isFallback = true;
1780 rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1781 }
1782 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001783 keymaster_ec_keygen_params_t ec_params;
1784 memset(&ec_params, '\0', sizeof(ec_params));
1785
1786 if (keySize == -1) {
1787 keySize = EC_DEFAULT_KEY_SIZE;
1788 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1789 ALOGI("invalid key size %d", keySize);
1790 return ::SYSTEM_ERROR;
1791 }
1792 ec_params.field_size = keySize;
1793
Kenny Root17208e02013-09-04 13:56:03 -07001794 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2) {
1795 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1796 } else {
1797 isFallback = true;
1798 rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1799 }
Kenny Root96427ba2013-08-16 14:02:41 -07001800 } else if (keyType == EVP_PKEY_RSA) {
1801 keymaster_rsa_keygen_params_t rsa_params;
1802 memset(&rsa_params, '\0', sizeof(rsa_params));
1803 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1804
1805 if (keySize == -1) {
1806 keySize = RSA_DEFAULT_KEY_SIZE;
1807 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1808 ALOGI("invalid key size %d", keySize);
1809 return ::SYSTEM_ERROR;
1810 }
1811 rsa_params.modulus_size = keySize;
1812
1813 if (args->size() > 1) {
1814 ALOGI("invalid number of arguments: %d", args->size());
1815 return ::SYSTEM_ERROR;
1816 } else if (args->size() == 1) {
1817 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1818 if (pubExpBlob != NULL) {
1819 Unique_BIGNUM pubExpBn(
1820 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1821 pubExpBlob->size(), NULL));
1822 if (pubExpBn.get() == NULL) {
1823 ALOGI("Could not convert public exponent to BN");
1824 return ::SYSTEM_ERROR;
1825 }
1826 unsigned long pubExp = BN_get_word(pubExpBn.get());
1827 if (pubExp == 0xFFFFFFFFL) {
1828 ALOGI("cannot represent public exponent as a long value");
1829 return ::SYSTEM_ERROR;
1830 }
1831 rsa_params.public_exponent = pubExp;
1832 }
1833 }
1834
1835 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1836 } else {
1837 ALOGW("Unsupported key type %d", keyType);
1838 rc = -1;
1839 }
1840
Kenny Root07438c82012-11-02 15:41:02 -07001841 if (rc) {
1842 return ::SYSTEM_ERROR;
1843 }
1844
Kenny Root655b9582013-04-04 08:37:42 -07001845 String8 name8(name);
1846 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001847
1848 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1849 free(data);
1850
Kenny Root17208e02013-09-04 13:56:03 -07001851 keyBlob.setFallback(isFallback);
1852
Kenny Root655b9582013-04-04 08:37:42 -07001853 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001854 }
1855
Kenny Rootf9119d62013-04-03 09:22:15 -07001856 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1857 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001858 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1859 if (!has_permission(callingUid, P_INSERT)) {
1860 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001861 return ::PERMISSION_DENIED;
1862 }
Kenny Root07438c82012-11-02 15:41:02 -07001863
Kenny Root49468902013-03-19 13:41:33 -07001864 if (targetUid == -1) {
1865 targetUid = callingUid;
1866 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001867 return ::PERMISSION_DENIED;
1868 }
1869
Kenny Root655b9582013-04-04 08:37:42 -07001870 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001871 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001872 ALOGD("calling import in state: %d", state);
1873 return state;
1874 }
1875
1876 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001877 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001878
Kenny Rootf9119d62013-04-03 09:22:15 -07001879 return mKeyStore->importKey(data, length, filename.string(), callingUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001880 }
1881
Kenny Root07438c82012-11-02 15:41:02 -07001882 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1883 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001884 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1885 if (!has_permission(callingUid, P_SIGN)) {
1886 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001887 return ::PERMISSION_DENIED;
1888 }
Kenny Root07438c82012-11-02 15:41:02 -07001889
Kenny Root07438c82012-11-02 15:41:02 -07001890 Blob keyBlob;
1891 String8 name8(name);
1892
Kenny Rootd38a0b02013-02-13 12:59:14 -08001893 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001894 int rc;
1895
Kenny Root655b9582013-04-04 08:37:42 -07001896 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001897 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001898 if (responseCode != ::NO_ERROR) {
1899 return responseCode;
1900 }
1901
1902 const keymaster_device_t* device = mKeyStore->getDevice();
1903 if (device == NULL) {
1904 ALOGE("no keymaster device; cannot sign");
1905 return ::SYSTEM_ERROR;
1906 }
1907
1908 if (device->sign_data == NULL) {
1909 ALOGE("device doesn't implement signing");
1910 return ::SYSTEM_ERROR;
1911 }
1912
1913 keymaster_rsa_sign_params_t params;
1914 params.digest_type = DIGEST_NONE;
1915 params.padding_type = PADDING_NONE;
1916
Kenny Root17208e02013-09-04 13:56:03 -07001917 if (keyBlob.isFallback()) {
1918 rc = openssl_sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1919 length, out, outLength);
1920 } else {
1921 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1922 length, out, outLength);
1923 }
Kenny Root07438c82012-11-02 15:41:02 -07001924 if (rc) {
1925 ALOGW("device couldn't sign data");
1926 return ::SYSTEM_ERROR;
1927 }
1928
1929 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001930 }
1931
Kenny Root07438c82012-11-02 15:41:02 -07001932 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1933 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001934 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1935 if (!has_permission(callingUid, P_VERIFY)) {
1936 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001937 return ::PERMISSION_DENIED;
1938 }
Kenny Root70e3a862012-02-15 17:20:23 -08001939
Kenny Root655b9582013-04-04 08:37:42 -07001940 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001941 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001942 ALOGD("calling verify in state: %d", state);
1943 return state;
1944 }
Kenny Root70e3a862012-02-15 17:20:23 -08001945
Kenny Root07438c82012-11-02 15:41:02 -07001946 Blob keyBlob;
1947 String8 name8(name);
1948 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001949
Kenny Root655b9582013-04-04 08:37:42 -07001950 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001951 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001952 if (responseCode != ::NO_ERROR) {
1953 return responseCode;
1954 }
Kenny Root70e3a862012-02-15 17:20:23 -08001955
Kenny Root07438c82012-11-02 15:41:02 -07001956 const keymaster_device_t* device = mKeyStore->getDevice();
1957 if (device == NULL) {
1958 return ::SYSTEM_ERROR;
1959 }
Kenny Root70e3a862012-02-15 17:20:23 -08001960
Kenny Root07438c82012-11-02 15:41:02 -07001961 if (device->verify_data == NULL) {
1962 return ::SYSTEM_ERROR;
1963 }
Kenny Root70e3a862012-02-15 17:20:23 -08001964
Kenny Root07438c82012-11-02 15:41:02 -07001965 keymaster_rsa_sign_params_t params;
1966 params.digest_type = DIGEST_NONE;
1967 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001968
Kenny Root17208e02013-09-04 13:56:03 -07001969 if (keyBlob.isFallback()) {
1970 rc = openssl_verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1971 dataLength, signature, signatureLength);
1972 } else {
1973 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1974 dataLength, signature, signatureLength);
1975 }
Kenny Root07438c82012-11-02 15:41:02 -07001976 if (rc) {
1977 return ::SYSTEM_ERROR;
1978 } else {
1979 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001980 }
1981 }
Kenny Root07438c82012-11-02 15:41:02 -07001982
1983 /*
1984 * TODO: The abstraction between things stored in hardware and regular blobs
1985 * of data stored on the filesystem should be moved down to keystore itself.
1986 * Unfortunately the Java code that calls this has naming conventions that it
1987 * knows about. Ideally keystore shouldn't be used to store random blobs of
1988 * data.
1989 *
1990 * Until that happens, it's necessary to have a separate "get_pubkey" and
1991 * "del_key" since the Java code doesn't really communicate what it's
1992 * intentions are.
1993 */
1994 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001995 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1996 if (!has_permission(callingUid, P_GET)) {
1997 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001998 return ::PERMISSION_DENIED;
1999 }
Kenny Root07438c82012-11-02 15:41:02 -07002000
Kenny Root07438c82012-11-02 15:41:02 -07002001 Blob keyBlob;
2002 String8 name8(name);
2003
Kenny Rootd38a0b02013-02-13 12:59:14 -08002004 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002005
Kenny Root655b9582013-04-04 08:37:42 -07002006 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002007 TYPE_KEY_PAIR);
2008 if (responseCode != ::NO_ERROR) {
2009 return responseCode;
2010 }
2011
2012 const keymaster_device_t* device = mKeyStore->getDevice();
2013 if (device == NULL) {
2014 return ::SYSTEM_ERROR;
2015 }
2016
2017 if (device->get_keypair_public == NULL) {
2018 ALOGE("device has no get_keypair_public implementation!");
2019 return ::SYSTEM_ERROR;
2020 }
2021
Kenny Root17208e02013-09-04 13:56:03 -07002022 int rc;
2023 if (keyBlob.isFallback()) {
2024 rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2025 pubkeyLength);
2026 } else {
2027 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2028 pubkeyLength);
2029 }
Kenny Root07438c82012-11-02 15:41:02 -07002030 if (rc) {
2031 return ::SYSTEM_ERROR;
2032 }
2033
2034 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002035 }
Kenny Root07438c82012-11-02 15:41:02 -07002036
Kenny Root49468902013-03-19 13:41:33 -07002037 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002038 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2039 if (!has_permission(callingUid, P_DELETE)) {
2040 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002041 return ::PERMISSION_DENIED;
2042 }
Kenny Root07438c82012-11-02 15:41:02 -07002043
Kenny Root49468902013-03-19 13:41:33 -07002044 if (targetUid == -1) {
2045 targetUid = callingUid;
2046 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002047 return ::PERMISSION_DENIED;
2048 }
2049
Kenny Root07438c82012-11-02 15:41:02 -07002050 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002051 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002052
2053 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002054 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
2055 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002056 if (responseCode != ::NO_ERROR) {
2057 return responseCode;
2058 }
2059
2060 ResponseCode rc = ::NO_ERROR;
2061
2062 const keymaster_device_t* device = mKeyStore->getDevice();
2063 if (device == NULL) {
2064 rc = ::SYSTEM_ERROR;
2065 } else {
2066 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002067 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Root07438c82012-11-02 15:41:02 -07002068 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2069 rc = ::SYSTEM_ERROR;
2070 }
2071 }
2072 }
2073
2074 if (rc != ::NO_ERROR) {
2075 return rc;
2076 }
2077
2078 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
2079 }
2080
2081 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002082 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2083 if (!has_permission(callingUid, P_GRANT)) {
2084 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002085 return ::PERMISSION_DENIED;
2086 }
Kenny Root07438c82012-11-02 15:41:02 -07002087
Kenny Root655b9582013-04-04 08:37:42 -07002088 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002089 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002090 ALOGD("calling grant in state: %d", state);
2091 return state;
2092 }
2093
2094 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002095 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002096
Kenny Root655b9582013-04-04 08:37:42 -07002097 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002098 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2099 }
2100
Kenny Root655b9582013-04-04 08:37:42 -07002101 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002102 return ::NO_ERROR;
2103 }
2104
2105 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002106 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2107 if (!has_permission(callingUid, P_GRANT)) {
2108 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002109 return ::PERMISSION_DENIED;
2110 }
Kenny Root07438c82012-11-02 15:41:02 -07002111
Kenny Root655b9582013-04-04 08:37:42 -07002112 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002113 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002114 ALOGD("calling ungrant in state: %d", state);
2115 return state;
2116 }
2117
2118 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002119 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002120
Kenny Root655b9582013-04-04 08:37:42 -07002121 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002122 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2123 }
2124
Kenny Root655b9582013-04-04 08:37:42 -07002125 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002126 }
2127
2128 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002129 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2130 if (!has_permission(callingUid, P_GET)) {
2131 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002132 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002133 }
Kenny Root07438c82012-11-02 15:41:02 -07002134
2135 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002136 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002137
Kenny Root655b9582013-04-04 08:37:42 -07002138 if (access(filename.string(), R_OK) == -1) {
2139 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002140 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002141 }
2142
Kenny Root655b9582013-04-04 08:37:42 -07002143 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002144 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002145 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002146 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002147 }
2148
2149 struct stat s;
2150 int ret = fstat(fd, &s);
2151 close(fd);
2152 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002153 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002154 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002155 }
2156
Kenny Root36a9e232013-02-04 14:24:15 -08002157 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002158 }
2159
Kenny Rootd53bc922013-03-21 14:10:15 -07002160 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2161 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002162 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Rootd53bc922013-03-21 14:10:15 -07002163 if (!has_permission(callingUid, P_DUPLICATE)) {
2164 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002165 return -1L;
2166 }
2167
Kenny Root655b9582013-04-04 08:37:42 -07002168 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002169 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002170 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002171 return state;
2172 }
2173
Kenny Rootd53bc922013-03-21 14:10:15 -07002174 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2175 srcUid = callingUid;
2176 } else if (!is_granted_to(callingUid, srcUid)) {
2177 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002178 return ::PERMISSION_DENIED;
2179 }
2180
Kenny Rootd53bc922013-03-21 14:10:15 -07002181 if (destUid == -1) {
2182 destUid = callingUid;
2183 }
2184
2185 if (srcUid != destUid) {
2186 if (static_cast<uid_t>(srcUid) != callingUid) {
2187 ALOGD("can only duplicate from caller to other or to same uid: "
2188 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2189 return ::PERMISSION_DENIED;
2190 }
2191
2192 if (!is_granted_to(callingUid, destUid)) {
2193 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2194 return ::PERMISSION_DENIED;
2195 }
2196 }
2197
2198 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002199 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002200
Kenny Rootd53bc922013-03-21 14:10:15 -07002201 String8 target8(destKey);
Kenny Root655b9582013-04-04 08:37:42 -07002202 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002203
Kenny Root655b9582013-04-04 08:37:42 -07002204 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2205 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002206 return ::SYSTEM_ERROR;
2207 }
2208
Kenny Rootd53bc922013-03-21 14:10:15 -07002209 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002210 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
2211 callingUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002212 if (responseCode != ::NO_ERROR) {
2213 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002214 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002215
Kenny Root655b9582013-04-04 08:37:42 -07002216 return mKeyStore->put(targetFile.string(), &keyBlob, callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002217 }
2218
Kenny Root1b0e3932013-09-05 13:06:32 -07002219 int32_t is_hardware_backed(const String16& keyType) {
2220 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002221 }
2222
Kenny Roota9bb5492013-04-01 16:29:11 -07002223 int32_t clear_uid(int64_t targetUid) {
2224 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2225 if (!has_permission(callingUid, P_CLEAR_UID)) {
2226 ALOGW("permission denied for %d: clear_uid", callingUid);
2227 return ::PERMISSION_DENIED;
2228 }
2229
Kenny Root655b9582013-04-04 08:37:42 -07002230 State state = mKeyStore->getState(callingUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002231 if (!isKeystoreUnlocked(state)) {
2232 ALOGD("calling clear_uid in state: %d", state);
2233 return state;
2234 }
2235
2236 const keymaster_device_t* device = mKeyStore->getDevice();
2237 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002238 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002239 return ::SYSTEM_ERROR;
2240 }
2241
Kenny Root655b9582013-04-04 08:37:42 -07002242 UserState* userState = mKeyStore->getUserState(callingUid);
2243 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota9bb5492013-04-01 16:29:11 -07002244 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07002245 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Roota9bb5492013-04-01 16:29:11 -07002246 return ::SYSTEM_ERROR;
2247 }
2248
Kenny Root655b9582013-04-04 08:37:42 -07002249 char prefix[NAME_MAX];
2250 int n = snprintf(prefix, NAME_MAX, "%u_", static_cast<uid_t>(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002251
2252 ResponseCode rc = ::NO_ERROR;
2253
2254 struct dirent* file;
2255 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002256 // We only care about files.
2257 if (file->d_type != DT_REG) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002258 continue;
2259 }
2260
Kenny Root655b9582013-04-04 08:37:42 -07002261 // Skip anything that starts with a "."
2262 if (file->d_name[0] == '.') {
2263 continue;
2264 }
Kenny Roota9bb5492013-04-01 16:29:11 -07002265
Kenny Root655b9582013-04-04 08:37:42 -07002266 if (strncmp(prefix, file->d_name, n)) {
2267 continue;
2268 }
2269
2270 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Roota9bb5492013-04-01 16:29:11 -07002271 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002272 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, callingUid)
2273 != ::NO_ERROR) {
2274 ALOGW("couldn't open %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002275 continue;
2276 }
2277
2278 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2279 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002280 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002281 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2282 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002283 ALOGW("device couldn't remove %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002284 }
2285 }
2286 }
2287
Kenny Root5f531242013-04-12 11:31:50 -07002288 if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002289 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002290 ALOGW("couldn't unlink %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002291 }
2292 }
2293 closedir(dir);
2294
2295 return rc;
2296 }
2297
Kenny Root07438c82012-11-02 15:41:02 -07002298private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002299 inline bool isKeystoreUnlocked(State state) {
2300 switch (state) {
2301 case ::STATE_NO_ERROR:
2302 return true;
2303 case ::STATE_UNINITIALIZED:
2304 case ::STATE_LOCKED:
2305 return false;
2306 }
2307 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002308 }
2309
2310 ::KeyStore* mKeyStore;
2311};
2312
2313}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002314
2315int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002316 if (argc < 2) {
2317 ALOGE("A directory must be specified!");
2318 return 1;
2319 }
2320 if (chdir(argv[1]) == -1) {
2321 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2322 return 1;
2323 }
2324
2325 Entropy entropy;
2326 if (!entropy.open()) {
2327 return 1;
2328 }
Kenny Root70e3a862012-02-15 17:20:23 -08002329
2330 keymaster_device_t* dev;
2331 if (keymaster_device_initialize(&dev)) {
2332 ALOGE("keystore keymaster could not be initialized; exiting");
2333 return 1;
2334 }
2335
Kenny Root70e3a862012-02-15 17:20:23 -08002336 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002337 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002338 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2339 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2340 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2341 if (ret != android::OK) {
2342 ALOGE("Couldn't register binder service!");
2343 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002344 }
Kenny Root07438c82012-11-02 15:41:02 -07002345
2346 /*
2347 * We're the only thread in existence, so we're just going to process
2348 * Binder transaction as a single-threaded program.
2349 */
2350 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002351
2352 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002353 return 1;
2354}