blob: b4cb64da0d39575184f54f345f4f6c3a1bfb87e5 [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
23#include <unistd.h>
24#include <signal.h>
25#include <errno.h>
26#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070027#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080028#include <fcntl.h>
29#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070030#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080031#include <sys/types.h>
32#include <sys/socket.h>
33#include <sys/stat.h>
34#include <sys/time.h>
35#include <arpa/inet.h>
36
37#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070038#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080039#include <openssl/evp.h>
40#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070041#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080042
Kenny Root70e3a862012-02-15 17:20:23 -080043#include <hardware/keymaster.h>
44
Kenny Rootb4d2e022013-09-04 13:56:03 -070045#include <keymaster/softkeymaster.h>
46
Kenny 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 Root60711792013-08-16 14:02:41 -070061#include "defaults.h"
62
Kenny Roota91203b2012-02-15 15:00:46 -080063/* KeyStore is a secured storage for key-value pairs. In this implementation,
64 * each file stores one key-value pair. Keys are encoded in file names, and
65 * values are encrypted with checksums. The encryption key is protected by a
66 * user-defined password. To keep things simple, buffers are always larger than
67 * the maximum space we needed, so boundary checks on buffers are omitted. */
68
69#define KEY_SIZE ((NAME_MAX - 15) / 2)
70#define VALUE_SIZE 32768
71#define PASSWORD_SIZE VALUE_SIZE
72
Kenny Root822c3a92012-03-23 16:34:39 -070073
Kenny Root60711792013-08-16 14:02:41 -070074struct BIGNUM_Delete {
75 void operator()(BIGNUM* p) const {
76 BN_free(p);
77 }
78};
79typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
80
Kenny Root822c3a92012-03-23 16:34:39 -070081struct BIO_Delete {
82 void operator()(BIO* p) const {
83 BIO_free(p);
84 }
85};
86typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
87
88struct EVP_PKEY_Delete {
89 void operator()(EVP_PKEY* p) const {
90 EVP_PKEY_free(p);
91 }
92};
93typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
94
95struct PKCS8_PRIV_KEY_INFO_Delete {
96 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
97 PKCS8_PRIV_KEY_INFO_free(p);
98 }
99};
100typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
101
102
Kenny Root70e3a862012-02-15 17:20:23 -0800103static int keymaster_device_initialize(keymaster_device_t** dev) {
104 int rc;
105
106 const hw_module_t* mod;
107 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
108 if (rc) {
109 ALOGE("could not find any keystore module");
110 goto out;
111 }
112
113 rc = keymaster_open(mod, dev);
114 if (rc) {
115 ALOGE("could not open keymaster device in %s (%s)",
116 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
117 goto out;
118 }
119
120 return 0;
121
122out:
123 *dev = NULL;
124 return rc;
125}
126
127static void keymaster_device_release(keymaster_device_t* dev) {
128 keymaster_close(dev);
129}
130
Kenny Root07438c82012-11-02 15:41:02 -0700131/***************
132 * PERMISSIONS *
133 ***************/
134
135/* Here are the permissions, actions, users, and the main function. */
136typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700137 P_TEST = 1 << 0,
138 P_GET = 1 << 1,
139 P_INSERT = 1 << 2,
140 P_DELETE = 1 << 3,
141 P_EXIST = 1 << 4,
142 P_SAW = 1 << 5,
143 P_RESET = 1 << 6,
144 P_PASSWORD = 1 << 7,
145 P_LOCK = 1 << 8,
146 P_UNLOCK = 1 << 9,
147 P_ZERO = 1 << 10,
148 P_SIGN = 1 << 11,
149 P_VERIFY = 1 << 12,
150 P_GRANT = 1 << 13,
151 P_DUPLICATE = 1 << 14,
Kenny Roota9bb5492013-04-01 16:29:11 -0700152 P_CLEAR_UID = 1 << 15,
Kenny Root07438c82012-11-02 15:41:02 -0700153} perm_t;
154
155static struct user_euid {
156 uid_t uid;
157 uid_t euid;
158} user_euids[] = {
159 {AID_VPN, AID_SYSTEM},
160 {AID_WIFI, AID_SYSTEM},
161 {AID_ROOT, AID_SYSTEM},
162};
163
164static struct user_perm {
165 uid_t uid;
166 perm_t perms;
167} user_perms[] = {
168 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
169 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
170 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
171 {AID_ROOT, static_cast<perm_t>(P_GET) },
172};
173
174static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
175 | P_VERIFY);
176
Kenny Root655b9582013-04-04 08:37:42 -0700177/**
178 * Returns the app ID (in the Android multi-user sense) for the current
179 * UNIX UID.
180 */
181static uid_t get_app_id(uid_t uid) {
182 return uid % AID_USER;
183}
184
185/**
186 * Returns the user ID (in the Android multi-user sense) for the current
187 * UNIX UID.
188 */
189static uid_t get_user_id(uid_t uid) {
190 return uid / AID_USER;
191}
192
193
Kenny Root07438c82012-11-02 15:41:02 -0700194static bool has_permission(uid_t uid, perm_t perm) {
Kenny Root655b9582013-04-04 08:37:42 -0700195 // All system users are equivalent for multi-user support.
196 if (get_app_id(uid) == AID_SYSTEM) {
197 uid = AID_SYSTEM;
198 }
199
Kenny Root07438c82012-11-02 15:41:02 -0700200 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
201 struct user_perm user = user_perms[i];
202 if (user.uid == uid) {
203 return user.perms & perm;
204 }
205 }
206
207 return DEFAULT_PERMS & perm;
208}
209
Kenny Root49468902013-03-19 13:41:33 -0700210/**
211 * Returns the UID that the callingUid should act as. This is here for
212 * legacy support of the WiFi and VPN systems and should be removed
213 * when WiFi can operate in its own namespace.
214 */
Kenny Root07438c82012-11-02 15:41:02 -0700215static uid_t get_keystore_euid(uid_t uid) {
216 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
217 struct user_euid user = user_euids[i];
218 if (user.uid == uid) {
219 return user.euid;
220 }
221 }
222
223 return uid;
224}
225
Kenny Root49468902013-03-19 13:41:33 -0700226/**
227 * Returns true if the callingUid is allowed to interact in the targetUid's
228 * namespace.
229 */
230static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
231 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
232 struct user_euid user = user_euids[i];
233 if (user.euid == callingUid && user.uid == targetUid) {
234 return true;
235 }
236 }
237
238 return false;
239}
240
Kenny Roota91203b2012-02-15 15:00:46 -0800241/* Here is the encoding of keys. This is necessary in order to allow arbitrary
242 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
243 * into two bytes. The first byte is one of [+-.] which represents the first
244 * two bits of the character. The second byte encodes the rest of the bits into
245 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
246 * that Base64 cannot be used here due to the need of prefix match on keys. */
247
Kenny Root655b9582013-04-04 08:37:42 -0700248static size_t encode_key_length(const android::String8& keyName) {
249 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
250 size_t length = keyName.length();
251 for (int i = length; i > 0; --i, ++in) {
252 if (*in < '0' || *in > '~') {
253 ++length;
254 }
255 }
256 return length;
257}
258
Kenny Root07438c82012-11-02 15:41:02 -0700259static int encode_key(char* out, const android::String8& keyName) {
260 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
261 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800262 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700263 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800264 *out = '+' + (*in >> 6);
265 *++out = '0' + (*in & 0x3F);
266 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700267 } else {
268 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800269 }
270 }
271 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800272 return length;
273}
274
Kenny Root07438c82012-11-02 15:41:02 -0700275static int encode_key_for_uid(char* out, uid_t uid, const android::String8& keyName) {
Kenny Root70e3a862012-02-15 17:20:23 -0800276 int n = snprintf(out, NAME_MAX, "%u_", uid);
277 out += n;
278
Kenny Root07438c82012-11-02 15:41:02 -0700279 return n + encode_key(out, keyName);
Kenny Roota91203b2012-02-15 15:00:46 -0800280}
281
Kenny Root07438c82012-11-02 15:41:02 -0700282/*
283 * Converts from the "escaped" format on disk to actual name.
284 * This will be smaller than the input string.
285 *
286 * Characters that should combine with the next at the end will be truncated.
287 */
288static size_t decode_key_length(const char* in, size_t length) {
289 size_t outLength = 0;
290
291 for (const char* end = in + length; in < end; in++) {
292 /* This combines with the next character. */
293 if (*in < '0' || *in > '~') {
294 continue;
295 }
296
297 outLength++;
298 }
299 return outLength;
300}
301
302static void decode_key(char* out, const char* in, size_t length) {
303 for (const char* end = in + length; in < end; in++) {
304 if (*in < '0' || *in > '~') {
305 /* Truncate combining characters at the end. */
306 if (in + 1 >= end) {
307 break;
308 }
309
310 *out = (*in++ - '+') << 6;
311 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800312 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700313 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800314 }
315 }
316 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800317}
318
319static size_t readFully(int fd, uint8_t* data, size_t size) {
320 size_t remaining = size;
321 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800322 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800323 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800324 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800325 }
326 data += n;
327 remaining -= n;
328 }
329 return size;
330}
331
332static size_t writeFully(int fd, uint8_t* data, size_t size) {
333 size_t remaining = size;
334 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800335 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
336 if (n < 0) {
337 ALOGW("write failed: %s", strerror(errno));
338 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800339 }
340 data += n;
341 remaining -= n;
342 }
343 return size;
344}
345
346class Entropy {
347public:
348 Entropy() : mRandom(-1) {}
349 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800350 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800351 close(mRandom);
352 }
353 }
354
355 bool open() {
356 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800357 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
358 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800359 ALOGE("open: %s: %s", randomDevice, strerror(errno));
360 return false;
361 }
362 return true;
363 }
364
Kenny Root51878182012-03-13 12:53:19 -0700365 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800366 return (readFully(mRandom, data, size) == size);
367 }
368
369private:
370 int mRandom;
371};
372
373/* Here is the file format. There are two parts in blob.value, the secret and
374 * the description. The secret is stored in ciphertext, and its original size
375 * can be found in blob.length. The description is stored after the secret in
376 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700377 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700378 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800379 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
380 * and decryptBlob(). Thus they should not be accessed from outside. */
381
Kenny Root822c3a92012-03-23 16:34:39 -0700382/* ** Note to future implementors of encryption: **
383 * Currently this is the construction:
384 * metadata || Enc(MD5(data) || data)
385 *
386 * This should be the construction used for encrypting if re-implementing:
387 *
388 * Derive independent keys for encryption and MAC:
389 * Kenc = AES_encrypt(masterKey, "Encrypt")
390 * Kmac = AES_encrypt(masterKey, "MAC")
391 *
392 * Store this:
393 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
394 * HMAC(Kmac, metadata || Enc(data))
395 */
Kenny Roota91203b2012-02-15 15:00:46 -0800396struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700397 uint8_t version;
398 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700399 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800400 uint8_t info;
401 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700402 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800403 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700404 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800405 int32_t length; // in network byte order when encrypted
406 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
407};
408
Kenny Root822c3a92012-03-23 16:34:39 -0700409typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700410 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700411 TYPE_GENERIC = 1,
412 TYPE_MASTER_KEY = 2,
413 TYPE_KEY_PAIR = 3,
414} BlobType;
415
Kenny Rootf9119d62013-04-03 09:22:15 -0700416static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700417
Kenny Roota91203b2012-02-15 15:00:46 -0800418class Blob {
419public:
Kenny Root07438c82012-11-02 15:41:02 -0700420 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
421 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800422 mBlob.length = valueLength;
423 memcpy(mBlob.value, value, valueLength);
424
425 mBlob.info = infoLength;
426 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700427
Kenny Root07438c82012-11-02 15:41:02 -0700428 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700429 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700430
431 mBlob.flags = KEYSTORE_FLAG_NONE;
Kenny Roota91203b2012-02-15 15:00:46 -0800432 }
433
434 Blob(blob b) {
435 mBlob = b;
436 }
437
438 Blob() {}
439
Kenny Root51878182012-03-13 12:53:19 -0700440 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800441 return mBlob.value;
442 }
443
Kenny Root51878182012-03-13 12:53:19 -0700444 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800445 return mBlob.length;
446 }
447
Kenny Root51878182012-03-13 12:53:19 -0700448 const uint8_t* getInfo() const {
449 return mBlob.value + mBlob.length;
450 }
451
452 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800453 return mBlob.info;
454 }
455
Kenny Root822c3a92012-03-23 16:34:39 -0700456 uint8_t getVersion() const {
457 return mBlob.version;
458 }
459
Kenny Rootf9119d62013-04-03 09:22:15 -0700460 bool isEncrypted() const {
461 if (mBlob.version < 2) {
462 return true;
463 }
464
465 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
466 }
467
468 void setEncrypted(bool encrypted) {
469 if (encrypted) {
470 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
471 } else {
472 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
473 }
474 }
475
Kenny Rootb4d2e022013-09-04 13:56:03 -0700476 bool isFallback() const {
477 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
478 }
479
480 void setFallback(bool fallback) {
481 if (fallback) {
482 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
483 } else {
484 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
485 }
486 }
487
Kenny Root822c3a92012-03-23 16:34:39 -0700488 void setVersion(uint8_t version) {
489 mBlob.version = version;
490 }
491
492 BlobType getType() const {
493 return BlobType(mBlob.type);
494 }
495
496 void setType(BlobType type) {
497 mBlob.type = uint8_t(type);
498 }
499
Kenny Rootf9119d62013-04-03 09:22:15 -0700500 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
501 ALOGV("writing blob %s", filename);
502 if (isEncrypted()) {
503 if (state != STATE_NO_ERROR) {
504 ALOGD("couldn't insert encrypted blob while not unlocked");
505 return LOCKED;
506 }
507
508 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
509 ALOGW("Could not read random data for: %s", filename);
510 return SYSTEM_ERROR;
511 }
Kenny Roota91203b2012-02-15 15:00:46 -0800512 }
513
514 // data includes the value and the value's length
515 size_t dataLength = mBlob.length + sizeof(mBlob.length);
516 // pad data to the AES_BLOCK_SIZE
517 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
518 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
519 // encrypted data includes the digest value
520 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
521 // move info after space for padding
522 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
523 // zero padding area
524 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
525
526 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800527
Kenny Rootf9119d62013-04-03 09:22:15 -0700528 if (isEncrypted()) {
529 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800530
Kenny Rootf9119d62013-04-03 09:22:15 -0700531 uint8_t vector[AES_BLOCK_SIZE];
532 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
533 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
534 aes_key, vector, AES_ENCRYPT);
535 }
536
Kenny Roota91203b2012-02-15 15:00:46 -0800537 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
538 size_t fileLength = encryptedLength + headerLength + mBlob.info;
539
540 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800541 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
542 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
543 if (out < 0) {
544 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800545 return SYSTEM_ERROR;
546 }
547 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
548 if (close(out) != 0) {
549 return SYSTEM_ERROR;
550 }
551 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800552 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800553 unlink(tmpFileName);
554 return SYSTEM_ERROR;
555 }
Kenny Root150ca932012-11-14 14:29:02 -0800556 if (rename(tmpFileName, filename) == -1) {
557 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
558 return SYSTEM_ERROR;
559 }
560 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800561 }
562
Kenny Rootf9119d62013-04-03 09:22:15 -0700563 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
564 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800565 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
566 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800567 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
568 }
569 // fileLength may be less than sizeof(mBlob) since the in
570 // memory version has extra padding to tolerate rounding up to
571 // the AES_BLOCK_SIZE
572 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
573 if (close(in) != 0) {
574 return SYSTEM_ERROR;
575 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700576
577 if (isEncrypted() && (state != STATE_NO_ERROR)) {
578 return LOCKED;
579 }
580
Kenny Roota91203b2012-02-15 15:00:46 -0800581 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
582 if (fileLength < headerLength) {
583 return VALUE_CORRUPTED;
584 }
585
586 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700587 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800588 return VALUE_CORRUPTED;
589 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700590
591 ssize_t digestedLength;
592 if (isEncrypted()) {
593 if (encryptedLength % AES_BLOCK_SIZE != 0) {
594 return VALUE_CORRUPTED;
595 }
596
597 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
598 mBlob.vector, AES_DECRYPT);
599 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
600 uint8_t computedDigest[MD5_DIGEST_LENGTH];
601 MD5(mBlob.digested, digestedLength, computedDigest);
602 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
603 return VALUE_CORRUPTED;
604 }
605 } else {
606 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800607 }
608
609 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
610 mBlob.length = ntohl(mBlob.length);
611 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
612 return VALUE_CORRUPTED;
613 }
614 if (mBlob.info != 0) {
615 // move info from after padding to after data
616 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
617 }
Kenny Root07438c82012-11-02 15:41:02 -0700618 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800619 }
620
621private:
622 struct blob mBlob;
623};
624
Kenny Root655b9582013-04-04 08:37:42 -0700625class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800626public:
Kenny Root655b9582013-04-04 08:37:42 -0700627 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
628 asprintf(&mUserDir, "user_%u", mUserId);
629 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
630 }
631
632 ~UserState() {
633 free(mUserDir);
634 free(mMasterKeyFile);
635 }
636
637 bool initialize() {
638 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
639 ALOGE("Could not create directory '%s'", mUserDir);
640 return false;
641 }
642
643 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800644 setState(STATE_LOCKED);
645 } else {
646 setState(STATE_UNINITIALIZED);
647 }
Kenny Root70e3a862012-02-15 17:20:23 -0800648
Kenny Root655b9582013-04-04 08:37:42 -0700649 return true;
650 }
651
652 uid_t getUserId() const {
653 return mUserId;
654 }
655
656 const char* getUserDirName() const {
657 return mUserDir;
658 }
659
660 const char* getMasterKeyFileName() const {
661 return mMasterKeyFile;
662 }
663
664 void setState(State state) {
665 mState = state;
666 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
667 mRetry = MAX_RETRY;
668 }
Kenny Roota91203b2012-02-15 15:00:46 -0800669 }
670
Kenny Root51878182012-03-13 12:53:19 -0700671 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800672 return mState;
673 }
674
Kenny Root51878182012-03-13 12:53:19 -0700675 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800676 return mRetry;
677 }
678
Kenny Root655b9582013-04-04 08:37:42 -0700679 void zeroizeMasterKeysInMemory() {
680 memset(mMasterKey, 0, sizeof(mMasterKey));
681 memset(mSalt, 0, sizeof(mSalt));
682 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
683 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800684 }
685
Kenny Root655b9582013-04-04 08:37:42 -0700686 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
687 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800688 return SYSTEM_ERROR;
689 }
Kenny Root655b9582013-04-04 08:37:42 -0700690 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800691 if (response != NO_ERROR) {
692 return response;
693 }
694 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700695 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800696 }
697
Kenny Root655b9582013-04-04 08:37:42 -0700698 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800699 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
700 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
701 AES_KEY passwordAesKey;
702 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700703 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700704 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800705 }
706
Kenny Root655b9582013-04-04 08:37:42 -0700707 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
708 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800709 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800710 return SYSTEM_ERROR;
711 }
712
713 // we read the raw blob to just to get the salt to generate
714 // the AES key, then we create the Blob to use with decryptBlob
715 blob rawBlob;
716 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
717 if (close(in) != 0) {
718 return SYSTEM_ERROR;
719 }
720 // find salt at EOF if present, otherwise we have an old file
721 uint8_t* salt;
722 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
723 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
724 } else {
725 salt = NULL;
726 }
727 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
728 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
729 AES_KEY passwordAesKey;
730 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
731 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700732 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
733 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800734 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700735 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800736 }
737 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
738 // if salt was missing, generate one and write a new master key file with the salt.
739 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700740 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800741 return SYSTEM_ERROR;
742 }
Kenny Root655b9582013-04-04 08:37:42 -0700743 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800744 }
745 if (response == NO_ERROR) {
746 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
747 setupMasterKeys();
748 }
749 return response;
750 }
751 if (mRetry <= 0) {
752 reset();
753 return UNINITIALIZED;
754 }
755 --mRetry;
756 switch (mRetry) {
757 case 0: return WRONG_PASSWORD_0;
758 case 1: return WRONG_PASSWORD_1;
759 case 2: return WRONG_PASSWORD_2;
760 case 3: return WRONG_PASSWORD_3;
761 default: return WRONG_PASSWORD_3;
762 }
763 }
764
Kenny Root655b9582013-04-04 08:37:42 -0700765 AES_KEY* getEncryptionKey() {
766 return &mMasterKeyEncryption;
767 }
768
769 AES_KEY* getDecryptionKey() {
770 return &mMasterKeyDecryption;
771 }
772
Kenny Roota91203b2012-02-15 15:00:46 -0800773 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700774 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800775 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700776 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800777 return false;
778 }
Kenny Root655b9582013-04-04 08:37:42 -0700779
780 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800781 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700782 // We only care about files.
783 if (file->d_type != DT_REG) {
784 continue;
785 }
786
787 // Skip anything that starts with a "."
788 if (file->d_name[0] == '.') {
789 continue;
790 }
791
792 // Find the current file's UID.
793 char* end;
794 unsigned long thisUid = strtoul(file->d_name, &end, 10);
795 if (end[0] != '_' || end[1] == 0) {
796 continue;
797 }
798
799 // Skip if this is not our user.
800 if (get_user_id(thisUid) != mUserId) {
801 continue;
802 }
803
804 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800805 }
806 closedir(dir);
807 return true;
808 }
809
Kenny Root655b9582013-04-04 08:37:42 -0700810private:
811 static const int MASTER_KEY_SIZE_BYTES = 16;
812 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
813
814 static const int MAX_RETRY = 4;
815 static const size_t SALT_SIZE = 16;
816
817 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
818 uint8_t* salt) {
819 size_t saltSize;
820 if (salt != NULL) {
821 saltSize = SALT_SIZE;
822 } else {
823 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
824 salt = (uint8_t*) "keystore";
825 // sizeof = 9, not strlen = 8
826 saltSize = sizeof("keystore");
827 }
828
829 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
830 saltSize, 8192, keySize, key);
831 }
832
833 bool generateSalt(Entropy* entropy) {
834 return entropy->generate_random_data(mSalt, sizeof(mSalt));
835 }
836
837 bool generateMasterKey(Entropy* entropy) {
838 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
839 return false;
840 }
841 if (!generateSalt(entropy)) {
842 return false;
843 }
844 return true;
845 }
846
847 void setupMasterKeys() {
848 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
849 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
850 setState(STATE_NO_ERROR);
851 }
852
853 uid_t mUserId;
854
855 char* mUserDir;
856 char* mMasterKeyFile;
857
858 State mState;
859 int8_t mRetry;
860
861 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
862 uint8_t mSalt[SALT_SIZE];
863
864 AES_KEY mMasterKeyEncryption;
865 AES_KEY mMasterKeyDecryption;
866};
867
868typedef struct {
869 uint32_t uid;
870 const uint8_t* filename;
871} grant_t;
872
873class KeyStore {
874public:
875 KeyStore(Entropy* entropy, keymaster_device_t* device)
876 : mEntropy(entropy)
877 , mDevice(device)
878 {
879 memset(&mMetaData, '\0', sizeof(mMetaData));
880 }
881
882 ~KeyStore() {
883 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
884 it != mGrants.end(); it++) {
885 delete *it;
886 mGrants.erase(it);
887 }
888
889 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
890 it != mMasterKeys.end(); it++) {
891 delete *it;
892 mMasterKeys.erase(it);
893 }
894 }
895
896 keymaster_device_t* getDevice() const {
897 return mDevice;
898 }
899
900 ResponseCode initialize() {
901 readMetaData();
902 if (upgradeKeystore()) {
903 writeMetaData();
904 }
905
906 return ::NO_ERROR;
907 }
908
909 State getState(uid_t uid) {
910 return getUserState(uid)->getState();
911 }
912
913 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
914 UserState* userState = getUserState(uid);
915 return userState->initialize(pw, mEntropy);
916 }
917
918 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
919 uid_t user_id = get_user_id(uid);
920 UserState* userState = getUserState(user_id);
921 return userState->writeMasterKey(pw, mEntropy);
922 }
923
924 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
925 uid_t user_id = get_user_id(uid);
926 UserState* userState = getUserState(user_id);
927 return userState->readMasterKey(pw, mEntropy);
928 }
929
930 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700931 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700932 encode_key(encoded, keyName);
933 return android::String8(encoded);
934 }
935
936 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700937 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700938 encode_key(encoded, keyName);
939 return android::String8::format("%u_%s", uid, encoded);
940 }
941
942 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700943 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700944 encode_key(encoded, keyName);
945 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
946 encoded);
947 }
948
949 bool reset(uid_t uid) {
950 UserState* userState = getUserState(uid);
951 userState->zeroizeMasterKeysInMemory();
952 userState->setState(STATE_UNINITIALIZED);
953 return userState->reset();
954 }
955
956 bool isEmpty(uid_t uid) const {
957 const UserState* userState = getUserState(uid);
958 if (userState == NULL) {
959 return true;
960 }
961
962 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800963 struct dirent* file;
964 if (!dir) {
965 return true;
966 }
967 bool result = true;
Kenny Root655b9582013-04-04 08:37:42 -0700968
969 char filename[NAME_MAX];
970 int n = snprintf(filename, sizeof(filename), "%u_", uid);
971
Kenny Roota91203b2012-02-15 15:00:46 -0800972 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700973 // We only care about files.
974 if (file->d_type != DT_REG) {
975 continue;
976 }
977
978 // Skip anything that starts with a "."
979 if (file->d_name[0] == '.') {
980 continue;
981 }
982
983 if (!strncmp(file->d_name, filename, n)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800984 result = false;
985 break;
986 }
987 }
988 closedir(dir);
989 return result;
990 }
991
Kenny Root655b9582013-04-04 08:37:42 -0700992 void lock(uid_t uid) {
993 UserState* userState = getUserState(uid);
994 userState->zeroizeMasterKeysInMemory();
995 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -0800996 }
997
Kenny Root655b9582013-04-04 08:37:42 -0700998 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
999 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001000 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1001 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001002 if (rc != NO_ERROR) {
1003 return rc;
1004 }
1005
1006 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001007 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001008 /* If we upgrade the key, we need to write it to disk again. Then
1009 * it must be read it again since the blob is encrypted each time
1010 * it's written.
1011 */
Kenny Root655b9582013-04-04 08:37:42 -07001012 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1013 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001014 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1015 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001016 return rc;
1017 }
1018 }
Kenny Root822c3a92012-03-23 16:34:39 -07001019 }
1020
Kenny Rootb4d2e022013-09-04 13:56:03 -07001021 /*
1022 * This will upgrade software-backed keys to hardware-backed keys when
1023 * the HAL for the device supports the newer key types.
1024 */
1025 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1026 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1027 && keyBlob->isFallback()) {
1028 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1029 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1030
1031 // The HAL allowed the import, reget the key to have the "fresh"
1032 // version.
1033 if (imported == NO_ERROR) {
1034 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1035 }
1036 }
1037
Kenny Rootd53bc922013-03-21 14:10:15 -07001038 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001039 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1040 return KEY_NOT_FOUND;
1041 }
1042
1043 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001044 }
1045
Kenny Root655b9582013-04-04 08:37:42 -07001046 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1047 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001048 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1049 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001050 }
1051
Kenny Root07438c82012-11-02 15:41:02 -07001052 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001053 const grant_t* existing = getGrant(filename, granteeUid);
1054 if (existing == NULL) {
1055 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001056 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001057 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001058 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001059 }
1060 }
1061
Kenny Root07438c82012-11-02 15:41:02 -07001062 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001063 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1064 it != mGrants.end(); it++) {
1065 grant_t* grant = *it;
1066 if (grant->uid == granteeUid
1067 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1068 mGrants.erase(it);
1069 return true;
1070 }
Kenny Root70e3a862012-02-15 17:20:23 -08001071 }
Kenny Root70e3a862012-02-15 17:20:23 -08001072 return false;
1073 }
1074
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001075 bool hasGrant(const char* filename, const uid_t uid) const {
1076 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001077 }
1078
Kenny Rootf9119d62013-04-03 09:22:15 -07001079 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1080 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001081 uint8_t* data;
1082 size_t dataLength;
1083 int rc;
1084
1085 if (mDevice->import_keypair == NULL) {
1086 ALOGE("Keymaster doesn't support import!");
1087 return SYSTEM_ERROR;
1088 }
1089
Kenny Rootb4d2e022013-09-04 13:56:03 -07001090 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001091 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001092 if (rc) {
Kenny Rootb4d2e022013-09-04 13:56:03 -07001093 // If this is an old device HAL, try to fall back to an old version
1094 if (mDevice->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_2) {
1095 rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength);
1096 isFallback = true;
1097 }
1098
1099 if (rc) {
1100 ALOGE("Error while importing keypair: %d", rc);
1101 return SYSTEM_ERROR;
1102 }
Kenny Root822c3a92012-03-23 16:34:39 -07001103 }
1104
1105 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1106 free(data);
1107
Kenny Rootf9119d62013-04-03 09:22:15 -07001108 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Rootb4d2e022013-09-04 13:56:03 -07001109 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001110
Kenny Root655b9582013-04-04 08:37:42 -07001111 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001112 }
1113
Kenny Root8ddf35a2013-03-29 11:15:50 -07001114 bool isHardwareBacked() const {
Kenny Root483407e2013-04-04 17:12:25 -07001115 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07001116 }
1117
Kenny Root655b9582013-04-04 08:37:42 -07001118 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1119 const BlobType type) {
1120 char filename[NAME_MAX];
1121 encode_key_for_uid(filename, uid, keyName);
1122
1123 UserState* userState = getUserState(uid);
1124 android::String8 filepath8;
1125
1126 filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1127 if (filepath8.string() == NULL) {
1128 ALOGW("can't create filepath for key %s", filename);
1129 return SYSTEM_ERROR;
1130 }
1131
1132 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1133 if (responseCode == NO_ERROR) {
1134 return responseCode;
1135 }
1136
1137 // If this is one of the legacy UID->UID mappings, use it.
1138 uid_t euid = get_keystore_euid(uid);
1139 if (euid != uid) {
1140 encode_key_for_uid(filename, euid, keyName);
1141 filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1142 responseCode = get(filepath8.string(), keyBlob, type, uid);
1143 if (responseCode == NO_ERROR) {
1144 return responseCode;
1145 }
1146 }
1147
1148 // They might be using a granted key.
1149 encode_key(filename, keyName);
1150 char* end;
1151 strtoul(filename, &end, 10);
1152 if (end[0] != '_' || end[1] == 0) {
1153 return KEY_NOT_FOUND;
1154 }
1155 filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1156 if (!hasGrant(filepath8.string(), uid)) {
1157 return responseCode;
1158 }
1159
1160 // It is a granted key. Try to load it.
1161 return get(filepath8.string(), keyBlob, type, uid);
1162 }
1163
1164 /**
1165 * Returns any existing UserState or creates it if it doesn't exist.
1166 */
1167 UserState* getUserState(uid_t uid) {
1168 uid_t userId = get_user_id(uid);
1169
1170 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1171 it != mMasterKeys.end(); it++) {
1172 UserState* state = *it;
1173 if (state->getUserId() == userId) {
1174 return state;
1175 }
1176 }
1177
1178 UserState* userState = new UserState(userId);
1179 if (!userState->initialize()) {
1180 /* There's not much we can do if initialization fails. Trying to
1181 * unlock the keystore for that user will fail as well, so any
1182 * subsequent request for this user will just return SYSTEM_ERROR.
1183 */
1184 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1185 }
1186 mMasterKeys.add(userState);
1187 return userState;
1188 }
1189
1190 /**
1191 * Returns NULL if the UserState doesn't already exist.
1192 */
1193 const UserState* getUserState(uid_t uid) const {
1194 uid_t userId = get_user_id(uid);
1195
1196 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1197 it != mMasterKeys.end(); it++) {
1198 UserState* state = *it;
1199 if (state->getUserId() == userId) {
1200 return state;
1201 }
1202 }
1203
1204 return NULL;
1205 }
1206
Kenny Roota91203b2012-02-15 15:00:46 -08001207private:
Kenny Root655b9582013-04-04 08:37:42 -07001208 static const char* sOldMasterKey;
1209 static const char* sMetaDataFile;
Kenny Roota91203b2012-02-15 15:00:46 -08001210 Entropy* mEntropy;
1211
Kenny Root70e3a862012-02-15 17:20:23 -08001212 keymaster_device_t* mDevice;
1213
Kenny Root655b9582013-04-04 08:37:42 -07001214 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001215
Kenny Root655b9582013-04-04 08:37:42 -07001216 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001217
Kenny Root655b9582013-04-04 08:37:42 -07001218 typedef struct {
1219 uint32_t version;
1220 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001221
Kenny Root655b9582013-04-04 08:37:42 -07001222 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001223
Kenny Root655b9582013-04-04 08:37:42 -07001224 const grant_t* getGrant(const char* filename, uid_t uid) const {
1225 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1226 it != mGrants.end(); it++) {
1227 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001228 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001229 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001230 return grant;
1231 }
1232 }
Kenny Root70e3a862012-02-15 17:20:23 -08001233 return NULL;
1234 }
1235
Kenny Root822c3a92012-03-23 16:34:39 -07001236 /**
1237 * Upgrade code. This will upgrade the key from the current version
1238 * to whatever is newest.
1239 */
Kenny Root655b9582013-04-04 08:37:42 -07001240 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1241 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001242 bool updated = false;
1243 uint8_t version = oldVersion;
1244
1245 /* From V0 -> V1: All old types were unknown */
1246 if (version == 0) {
1247 ALOGV("upgrading to version 1 and setting type %d", type);
1248
1249 blob->setType(type);
1250 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001251 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001252 }
1253 version = 1;
1254 updated = true;
1255 }
1256
Kenny Rootf9119d62013-04-03 09:22:15 -07001257 /* From V1 -> V2: All old keys were encrypted */
1258 if (version == 1) {
1259 ALOGV("upgrading to version 2");
1260
1261 blob->setEncrypted(true);
1262 version = 2;
1263 updated = true;
1264 }
1265
Kenny Root822c3a92012-03-23 16:34:39 -07001266 /*
1267 * If we've updated, set the key blob to the right version
1268 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001269 */
Kenny Root822c3a92012-03-23 16:34:39 -07001270 if (updated) {
1271 ALOGV("updated and writing file %s", filename);
1272 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001273 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001274
1275 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001276 }
1277
1278 /**
1279 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1280 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1281 * Then it overwrites the original blob with the new blob
1282 * format that is returned from the keymaster.
1283 */
Kenny Root655b9582013-04-04 08:37:42 -07001284 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001285 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1286 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1287 if (b.get() == NULL) {
1288 ALOGE("Problem instantiating BIO");
1289 return SYSTEM_ERROR;
1290 }
1291
1292 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1293 if (pkey.get() == NULL) {
1294 ALOGE("Couldn't read old PEM file");
1295 return SYSTEM_ERROR;
1296 }
1297
1298 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1299 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1300 if (len < 0) {
1301 ALOGE("Couldn't measure PKCS#8 length");
1302 return SYSTEM_ERROR;
1303 }
1304
Kenny Root70c98892013-02-07 09:10:36 -08001305 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1306 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001307 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1308 ALOGE("Couldn't convert to PKCS#8");
1309 return SYSTEM_ERROR;
1310 }
1311
Kenny Rootf9119d62013-04-03 09:22:15 -07001312 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1313 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001314 if (rc != NO_ERROR) {
1315 return rc;
1316 }
1317
Kenny Root655b9582013-04-04 08:37:42 -07001318 return get(filename, blob, TYPE_KEY_PAIR, uid);
1319 }
1320
1321 void readMetaData() {
1322 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1323 if (in < 0) {
1324 return;
1325 }
1326 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1327 if (fileLength != sizeof(mMetaData)) {
1328 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1329 sizeof(mMetaData));
1330 }
1331 close(in);
1332 }
1333
1334 void writeMetaData() {
1335 const char* tmpFileName = ".metadata.tmp";
1336 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1337 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1338 if (out < 0) {
1339 ALOGE("couldn't write metadata file: %s", strerror(errno));
1340 return;
1341 }
1342 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1343 if (fileLength != sizeof(mMetaData)) {
1344 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1345 sizeof(mMetaData));
1346 }
1347 close(out);
1348 rename(tmpFileName, sMetaDataFile);
1349 }
1350
1351 bool upgradeKeystore() {
1352 bool upgraded = false;
1353
1354 if (mMetaData.version == 0) {
1355 UserState* userState = getUserState(0);
1356
1357 // Initialize first so the directory is made.
1358 userState->initialize();
1359
1360 // Migrate the old .masterkey file to user 0.
1361 if (access(sOldMasterKey, R_OK) == 0) {
1362 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1363 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1364 return false;
1365 }
1366 }
1367
1368 // Initialize again in case we had a key.
1369 userState->initialize();
1370
1371 // Try to migrate existing keys.
1372 DIR* dir = opendir(".");
1373 if (!dir) {
1374 // Give up now; maybe we can upgrade later.
1375 ALOGE("couldn't open keystore's directory; something is wrong");
1376 return false;
1377 }
1378
1379 struct dirent* file;
1380 while ((file = readdir(dir)) != NULL) {
1381 // We only care about files.
1382 if (file->d_type != DT_REG) {
1383 continue;
1384 }
1385
1386 // Skip anything that starts with a "."
1387 if (file->d_name[0] == '.') {
1388 continue;
1389 }
1390
1391 // Find the current file's user.
1392 char* end;
1393 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1394 if (end[0] != '_' || end[1] == 0) {
1395 continue;
1396 }
1397 UserState* otherUser = getUserState(thisUid);
1398 if (otherUser->getUserId() != 0) {
1399 unlinkat(dirfd(dir), file->d_name, 0);
1400 }
1401
1402 // Rename the file into user directory.
1403 DIR* otherdir = opendir(otherUser->getUserDirName());
1404 if (otherdir == NULL) {
1405 ALOGW("couldn't open user directory for rename");
1406 continue;
1407 }
1408 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1409 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1410 }
1411 closedir(otherdir);
1412 }
1413 closedir(dir);
1414
1415 mMetaData.version = 1;
1416 upgraded = true;
1417 }
1418
1419 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001420 }
Kenny Roota91203b2012-02-15 15:00:46 -08001421};
1422
Kenny Root655b9582013-04-04 08:37:42 -07001423const char* KeyStore::sOldMasterKey = ".masterkey";
1424const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001425
Kenny Root07438c82012-11-02 15:41:02 -07001426namespace android {
1427class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1428public:
1429 KeyStoreProxy(KeyStore* keyStore)
1430 : mKeyStore(keyStore)
1431 {
Kenny Roota91203b2012-02-15 15:00:46 -08001432 }
Kenny Roota91203b2012-02-15 15:00:46 -08001433
Kenny Root07438c82012-11-02 15:41:02 -07001434 void binderDied(const wp<IBinder>&) {
1435 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001436 }
Kenny Roota91203b2012-02-15 15:00:46 -08001437
Kenny Root07438c82012-11-02 15:41:02 -07001438 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001439 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1440 if (!has_permission(callingUid, P_TEST)) {
1441 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001442 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001443 }
Kenny Roota91203b2012-02-15 15:00:46 -08001444
Kenny Root655b9582013-04-04 08:37:42 -07001445 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001446 }
1447
Kenny Root07438c82012-11-02 15:41:02 -07001448 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001449 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1450 if (!has_permission(callingUid, P_GET)) {
1451 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001452 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001453 }
Kenny Root07438c82012-11-02 15:41:02 -07001454
Kenny Root07438c82012-11-02 15:41:02 -07001455 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001456 Blob keyBlob;
Kenny Root49468902013-03-19 13:41:33 -07001457
Kenny Root655b9582013-04-04 08:37:42 -07001458 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001459 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001460 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001461 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001462 *item = NULL;
1463 *itemLength = 0;
1464 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001465 }
Kenny Roota91203b2012-02-15 15:00:46 -08001466
Kenny Root07438c82012-11-02 15:41:02 -07001467 *item = (uint8_t*) malloc(keyBlob.getLength());
1468 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1469 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001470
Kenny Root07438c82012-11-02 15:41:02 -07001471 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001472 }
1473
Kenny Rootf9119d62013-04-03 09:22:15 -07001474 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1475 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001476 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1477 if (!has_permission(callingUid, P_INSERT)) {
1478 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001479 return ::PERMISSION_DENIED;
1480 }
Kenny Root07438c82012-11-02 15:41:02 -07001481
Kenny Rootf9119d62013-04-03 09:22:15 -07001482 State state = mKeyStore->getState(callingUid);
1483 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1484 ALOGD("calling get in state: %d", state);
1485 return state;
1486 }
1487
Kenny Root49468902013-03-19 13:41:33 -07001488 if (targetUid == -1) {
1489 targetUid = callingUid;
1490 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001491 return ::PERMISSION_DENIED;
1492 }
1493
Kenny Root07438c82012-11-02 15:41:02 -07001494 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001495 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001496
1497 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Root655b9582013-04-04 08:37:42 -07001498 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001499 }
1500
Kenny Root49468902013-03-19 13:41:33 -07001501 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001502 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1503 if (!has_permission(callingUid, P_DELETE)) {
1504 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001505 return ::PERMISSION_DENIED;
1506 }
Kenny Root70e3a862012-02-15 17:20:23 -08001507
Kenny Root49468902013-03-19 13:41:33 -07001508 if (targetUid == -1) {
1509 targetUid = callingUid;
1510 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001511 return ::PERMISSION_DENIED;
1512 }
1513
Kenny Root07438c82012-11-02 15:41:02 -07001514 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001515 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001516
1517 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001518 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
1519 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001520 if (responseCode != ::NO_ERROR) {
1521 return responseCode;
1522 }
1523 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001524 }
1525
Kenny Root49468902013-03-19 13:41:33 -07001526 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001527 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1528 if (!has_permission(callingUid, P_EXIST)) {
1529 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001530 return ::PERMISSION_DENIED;
1531 }
Kenny Root70e3a862012-02-15 17:20:23 -08001532
Kenny Root49468902013-03-19 13:41:33 -07001533 if (targetUid == -1) {
1534 targetUid = callingUid;
1535 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001536 return ::PERMISSION_DENIED;
1537 }
1538
Kenny Root07438c82012-11-02 15:41:02 -07001539 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001540 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001541
Kenny Root655b9582013-04-04 08:37:42 -07001542 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001543 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1544 }
1545 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001546 }
1547
Kenny Root49468902013-03-19 13:41:33 -07001548 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001549 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1550 if (!has_permission(callingUid, P_SAW)) {
1551 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001552 return ::PERMISSION_DENIED;
1553 }
Kenny Root70e3a862012-02-15 17:20:23 -08001554
Kenny Root49468902013-03-19 13:41:33 -07001555 if (targetUid == -1) {
1556 targetUid = callingUid;
1557 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001558 return ::PERMISSION_DENIED;
1559 }
1560
Kenny Root655b9582013-04-04 08:37:42 -07001561 UserState* userState = mKeyStore->getUserState(targetUid);
1562 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001563 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07001564 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001565 return ::SYSTEM_ERROR;
1566 }
Kenny Root70e3a862012-02-15 17:20:23 -08001567
Kenny Root07438c82012-11-02 15:41:02 -07001568 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001569 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1570 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001571
Kenny Root07438c82012-11-02 15:41:02 -07001572 struct dirent* file;
1573 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001574 // We only care about files.
1575 if (file->d_type != DT_REG) {
1576 continue;
1577 }
1578
1579 // Skip anything that starts with a "."
1580 if (file->d_name[0] == '.') {
1581 continue;
1582 }
1583
1584 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001585 const char* p = &file->d_name[n];
1586 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001587
Kenny Root07438c82012-11-02 15:41:02 -07001588 size_t extra = decode_key_length(p, plen);
1589 char *match = (char*) malloc(extra + 1);
1590 if (match != NULL) {
1591 decode_key(match, p, plen);
1592 matches->push(String16(match, extra));
1593 free(match);
1594 } else {
1595 ALOGW("could not allocate match of size %zd", extra);
1596 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001597 }
1598 }
Kenny Root07438c82012-11-02 15:41:02 -07001599 closedir(dir);
1600
1601 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001602 }
1603
Kenny Root07438c82012-11-02 15:41:02 -07001604 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001605 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1606 if (!has_permission(callingUid, P_RESET)) {
1607 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001608 return ::PERMISSION_DENIED;
1609 }
1610
Kenny Root655b9582013-04-04 08:37:42 -07001611 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001612
1613 const keymaster_device_t* device = mKeyStore->getDevice();
1614 if (device == NULL) {
1615 ALOGE("No keymaster device!");
1616 return ::SYSTEM_ERROR;
1617 }
1618
1619 if (device->delete_all == NULL) {
1620 ALOGV("keymaster device doesn't implement delete_all");
1621 return rc;
1622 }
1623
1624 if (device->delete_all(device)) {
1625 ALOGE("Problem calling keymaster's delete_all");
1626 return ::SYSTEM_ERROR;
1627 }
1628
Kenny Root9a53d3e2012-08-14 10:47:54 -07001629 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001630 }
1631
Kenny Root07438c82012-11-02 15:41:02 -07001632 /*
1633 * Here is the history. To improve the security, the parameters to generate the
1634 * master key has been changed. To make a seamless transition, we update the
1635 * file using the same password when the user unlock it for the first time. If
1636 * any thing goes wrong during the transition, the new file will not overwrite
1637 * the old one. This avoids permanent damages of the existing data.
1638 */
1639 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001640 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1641 if (!has_permission(callingUid, P_PASSWORD)) {
1642 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001643 return ::PERMISSION_DENIED;
1644 }
Kenny Root70e3a862012-02-15 17:20:23 -08001645
Kenny Root07438c82012-11-02 15:41:02 -07001646 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001647
Kenny Root655b9582013-04-04 08:37:42 -07001648 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001649 case ::STATE_UNINITIALIZED: {
1650 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001651 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001652 }
1653 case ::STATE_NO_ERROR: {
1654 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001655 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001656 }
1657 case ::STATE_LOCKED: {
1658 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001659 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001660 }
1661 }
1662 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001663 }
1664
Kenny Root07438c82012-11-02 15:41:02 -07001665 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001666 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1667 if (!has_permission(callingUid, P_LOCK)) {
1668 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001669 return ::PERMISSION_DENIED;
1670 }
Kenny Root70e3a862012-02-15 17:20:23 -08001671
Kenny Root655b9582013-04-04 08:37:42 -07001672 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001673 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001674 ALOGD("calling lock in state: %d", state);
1675 return state;
1676 }
1677
Kenny Root655b9582013-04-04 08:37:42 -07001678 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001679 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001680 }
1681
Kenny Root07438c82012-11-02 15:41:02 -07001682 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001683 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1684 if (!has_permission(callingUid, P_UNLOCK)) {
1685 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001686 return ::PERMISSION_DENIED;
1687 }
1688
Kenny Root655b9582013-04-04 08:37:42 -07001689 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001690 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001691 ALOGD("calling unlock when not locked");
1692 return state;
1693 }
1694
1695 const String8 password8(pw);
1696 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001697 }
1698
Kenny Root07438c82012-11-02 15:41:02 -07001699 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001700 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1701 if (!has_permission(callingUid, P_ZERO)) {
1702 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001703 return -1;
1704 }
Kenny Root70e3a862012-02-15 17:20:23 -08001705
Kenny Root655b9582013-04-04 08:37:42 -07001706 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001707 }
1708
Kenny Root60711792013-08-16 14:02:41 -07001709 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1710 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001711 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1712 if (!has_permission(callingUid, P_INSERT)) {
1713 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001714 return ::PERMISSION_DENIED;
1715 }
Kenny Root70e3a862012-02-15 17:20:23 -08001716
Kenny Root49468902013-03-19 13:41:33 -07001717 if (targetUid == -1) {
1718 targetUid = callingUid;
1719 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001720 return ::PERMISSION_DENIED;
1721 }
1722
Kenny Root655b9582013-04-04 08:37:42 -07001723 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001724 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1725 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001726 return state;
1727 }
Kenny Root70e3a862012-02-15 17:20:23 -08001728
Kenny Root07438c82012-11-02 15:41:02 -07001729 uint8_t* data;
1730 size_t dataLength;
1731 int rc;
Kenny Rootb4d2e022013-09-04 13:56:03 -07001732 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001733
1734 const keymaster_device_t* device = mKeyStore->getDevice();
1735 if (device == NULL) {
1736 return ::SYSTEM_ERROR;
1737 }
1738
1739 if (device->generate_keypair == NULL) {
1740 return ::SYSTEM_ERROR;
1741 }
1742
Kenny Rootb4d2e022013-09-04 13:56:03 -07001743 if (keyType == EVP_PKEY_DSA) {
Kenny Root60711792013-08-16 14:02:41 -07001744 keymaster_dsa_keygen_params_t dsa_params;
1745 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001746
Kenny Root60711792013-08-16 14:02:41 -07001747 if (keySize == -1) {
1748 keySize = DSA_DEFAULT_KEY_SIZE;
1749 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1750 || keySize > DSA_MAX_KEY_SIZE) {
1751 ALOGI("invalid key size %d", keySize);
1752 return ::SYSTEM_ERROR;
1753 }
1754 dsa_params.key_size = keySize;
1755
1756 if (args->size() == 3) {
1757 sp<KeystoreArg> gArg = args->itemAt(0);
1758 sp<KeystoreArg> pArg = args->itemAt(1);
1759 sp<KeystoreArg> qArg = args->itemAt(2);
1760
1761 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1762 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1763 dsa_params.generator_len = gArg->size();
1764
1765 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1766 dsa_params.prime_p_len = pArg->size();
1767
1768 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1769 dsa_params.prime_q_len = qArg->size();
1770 } else {
1771 ALOGI("not all DSA parameters were read");
1772 return ::SYSTEM_ERROR;
1773 }
1774 } else if (args->size() != 0) {
1775 ALOGI("DSA args must be 3");
1776 return ::SYSTEM_ERROR;
1777 }
1778
Kenny Rootb4d2e022013-09-04 13:56:03 -07001779 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2) {
1780 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1781 } else {
1782 isFallback = true;
1783 rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1784 }
1785 } else if (keyType == EVP_PKEY_EC) {
Kenny Root60711792013-08-16 14:02:41 -07001786 keymaster_ec_keygen_params_t ec_params;
1787 memset(&ec_params, '\0', sizeof(ec_params));
1788
1789 if (keySize == -1) {
1790 keySize = EC_DEFAULT_KEY_SIZE;
1791 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1792 ALOGI("invalid key size %d", keySize);
1793 return ::SYSTEM_ERROR;
1794 }
1795 ec_params.field_size = keySize;
1796
Kenny Rootb4d2e022013-09-04 13:56:03 -07001797 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2) {
1798 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1799 } else {
1800 isFallback = true;
1801 rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1802 }
Kenny Root60711792013-08-16 14:02:41 -07001803 } else if (keyType == EVP_PKEY_RSA) {
1804 keymaster_rsa_keygen_params_t rsa_params;
1805 memset(&rsa_params, '\0', sizeof(rsa_params));
1806 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1807
1808 if (keySize == -1) {
1809 keySize = RSA_DEFAULT_KEY_SIZE;
1810 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1811 ALOGI("invalid key size %d", keySize);
1812 return ::SYSTEM_ERROR;
1813 }
1814 rsa_params.modulus_size = keySize;
1815
1816 if (args->size() > 1) {
1817 ALOGI("invalid number of arguments: %d", args->size());
1818 return ::SYSTEM_ERROR;
1819 } else if (args->size() == 1) {
1820 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1821 if (pubExpBlob != NULL) {
1822 Unique_BIGNUM pubExpBn(
1823 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1824 pubExpBlob->size(), NULL));
1825 if (pubExpBn.get() == NULL) {
1826 ALOGI("Could not convert public exponent to BN");
1827 return ::SYSTEM_ERROR;
1828 }
1829 unsigned long pubExp = BN_get_word(pubExpBn.get());
1830 if (pubExp == 0xFFFFFFFFL) {
1831 ALOGI("cannot represent public exponent as a long value");
1832 return ::SYSTEM_ERROR;
1833 }
1834 rsa_params.public_exponent = pubExp;
1835 }
1836 }
1837
1838 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1839 } else {
1840 ALOGW("Unsupported key type %d", keyType);
1841 rc = -1;
1842 }
1843
Kenny Root07438c82012-11-02 15:41:02 -07001844 if (rc) {
1845 return ::SYSTEM_ERROR;
1846 }
1847
Kenny Root655b9582013-04-04 08:37:42 -07001848 String8 name8(name);
1849 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001850
1851 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1852 free(data);
1853
Kenny Rootb4d2e022013-09-04 13:56:03 -07001854 keyBlob.setFallback(isFallback);
1855
Kenny Root655b9582013-04-04 08:37:42 -07001856 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001857 }
1858
Kenny Rootf9119d62013-04-03 09:22:15 -07001859 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1860 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001861 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1862 if (!has_permission(callingUid, P_INSERT)) {
1863 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001864 return ::PERMISSION_DENIED;
1865 }
Kenny Root07438c82012-11-02 15:41:02 -07001866
Kenny Root49468902013-03-19 13:41:33 -07001867 if (targetUid == -1) {
1868 targetUid = callingUid;
1869 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001870 return ::PERMISSION_DENIED;
1871 }
1872
Kenny Root655b9582013-04-04 08:37:42 -07001873 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001874 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001875 ALOGD("calling import in state: %d", state);
1876 return state;
1877 }
1878
1879 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001880 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001881
Kenny Rootf9119d62013-04-03 09:22:15 -07001882 return mKeyStore->importKey(data, length, filename.string(), callingUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001883 }
1884
Kenny Root07438c82012-11-02 15:41:02 -07001885 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1886 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001887 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1888 if (!has_permission(callingUid, P_SIGN)) {
1889 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001890 return ::PERMISSION_DENIED;
1891 }
Kenny Root07438c82012-11-02 15:41:02 -07001892
Kenny Root07438c82012-11-02 15:41:02 -07001893 Blob keyBlob;
1894 String8 name8(name);
1895
Kenny Rootd38a0b02013-02-13 12:59:14 -08001896 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001897 int rc;
1898
Kenny Root655b9582013-04-04 08:37:42 -07001899 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001900 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001901 if (responseCode != ::NO_ERROR) {
1902 return responseCode;
1903 }
1904
1905 const keymaster_device_t* device = mKeyStore->getDevice();
1906 if (device == NULL) {
1907 ALOGE("no keymaster device; cannot sign");
1908 return ::SYSTEM_ERROR;
1909 }
1910
1911 if (device->sign_data == NULL) {
1912 ALOGE("device doesn't implement signing");
1913 return ::SYSTEM_ERROR;
1914 }
1915
1916 keymaster_rsa_sign_params_t params;
1917 params.digest_type = DIGEST_NONE;
1918 params.padding_type = PADDING_NONE;
1919
Kenny Rootb4d2e022013-09-04 13:56:03 -07001920 if (keyBlob.isFallback()) {
1921 rc = openssl_sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1922 length, out, outLength);
1923 } else {
1924 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1925 length, out, outLength);
1926 }
Kenny Root07438c82012-11-02 15:41:02 -07001927 if (rc) {
1928 ALOGW("device couldn't sign data");
1929 return ::SYSTEM_ERROR;
1930 }
1931
1932 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001933 }
1934
Kenny Root07438c82012-11-02 15:41:02 -07001935 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1936 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001937 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1938 if (!has_permission(callingUid, P_VERIFY)) {
1939 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001940 return ::PERMISSION_DENIED;
1941 }
Kenny Root70e3a862012-02-15 17:20:23 -08001942
Kenny Root655b9582013-04-04 08:37:42 -07001943 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001944 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001945 ALOGD("calling verify in state: %d", state);
1946 return state;
1947 }
Kenny Root70e3a862012-02-15 17:20:23 -08001948
Kenny Root07438c82012-11-02 15:41:02 -07001949 Blob keyBlob;
1950 String8 name8(name);
1951 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001952
Kenny Root655b9582013-04-04 08:37:42 -07001953 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001954 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001955 if (responseCode != ::NO_ERROR) {
1956 return responseCode;
1957 }
Kenny Root70e3a862012-02-15 17:20:23 -08001958
Kenny Root07438c82012-11-02 15:41:02 -07001959 const keymaster_device_t* device = mKeyStore->getDevice();
1960 if (device == NULL) {
1961 return ::SYSTEM_ERROR;
1962 }
Kenny Root70e3a862012-02-15 17:20:23 -08001963
Kenny Root07438c82012-11-02 15:41:02 -07001964 if (device->verify_data == NULL) {
1965 return ::SYSTEM_ERROR;
1966 }
Kenny Root70e3a862012-02-15 17:20:23 -08001967
Kenny Root07438c82012-11-02 15:41:02 -07001968 keymaster_rsa_sign_params_t params;
1969 params.digest_type = DIGEST_NONE;
1970 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001971
Kenny Rootb4d2e022013-09-04 13:56:03 -07001972 if (keyBlob.isFallback()) {
1973 rc = openssl_verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1974 dataLength, signature, signatureLength);
1975 } else {
1976 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1977 dataLength, signature, signatureLength);
1978 }
Kenny Root07438c82012-11-02 15:41:02 -07001979 if (rc) {
1980 return ::SYSTEM_ERROR;
1981 } else {
1982 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001983 }
1984 }
Kenny Root07438c82012-11-02 15:41:02 -07001985
1986 /*
1987 * TODO: The abstraction between things stored in hardware and regular blobs
1988 * of data stored on the filesystem should be moved down to keystore itself.
1989 * Unfortunately the Java code that calls this has naming conventions that it
1990 * knows about. Ideally keystore shouldn't be used to store random blobs of
1991 * data.
1992 *
1993 * Until that happens, it's necessary to have a separate "get_pubkey" and
1994 * "del_key" since the Java code doesn't really communicate what it's
1995 * intentions are.
1996 */
1997 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001998 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1999 if (!has_permission(callingUid, P_GET)) {
2000 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002001 return ::PERMISSION_DENIED;
2002 }
Kenny Root07438c82012-11-02 15:41:02 -07002003
Kenny Root07438c82012-11-02 15:41:02 -07002004 Blob keyBlob;
2005 String8 name8(name);
2006
Kenny Rootd38a0b02013-02-13 12:59:14 -08002007 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002008
Kenny Root655b9582013-04-04 08:37:42 -07002009 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002010 TYPE_KEY_PAIR);
2011 if (responseCode != ::NO_ERROR) {
2012 return responseCode;
2013 }
2014
2015 const keymaster_device_t* device = mKeyStore->getDevice();
2016 if (device == NULL) {
2017 return ::SYSTEM_ERROR;
2018 }
2019
2020 if (device->get_keypair_public == NULL) {
2021 ALOGE("device has no get_keypair_public implementation!");
2022 return ::SYSTEM_ERROR;
2023 }
2024
Kenny Rootb4d2e022013-09-04 13:56:03 -07002025 int rc;
2026 if (keyBlob.isFallback()) {
2027 rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2028 pubkeyLength);
2029 } else {
2030 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2031 pubkeyLength);
2032 }
Kenny Root07438c82012-11-02 15:41:02 -07002033 if (rc) {
2034 return ::SYSTEM_ERROR;
2035 }
2036
2037 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002038 }
Kenny Root07438c82012-11-02 15:41:02 -07002039
Kenny Root49468902013-03-19 13:41:33 -07002040 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002041 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2042 if (!has_permission(callingUid, P_DELETE)) {
2043 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002044 return ::PERMISSION_DENIED;
2045 }
Kenny Root07438c82012-11-02 15:41:02 -07002046
Kenny Root49468902013-03-19 13:41:33 -07002047 if (targetUid == -1) {
2048 targetUid = callingUid;
2049 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002050 return ::PERMISSION_DENIED;
2051 }
2052
Kenny Root07438c82012-11-02 15:41:02 -07002053 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002054 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002055
2056 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002057 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
2058 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002059 if (responseCode != ::NO_ERROR) {
2060 return responseCode;
2061 }
2062
2063 ResponseCode rc = ::NO_ERROR;
2064
2065 const keymaster_device_t* device = mKeyStore->getDevice();
2066 if (device == NULL) {
2067 rc = ::SYSTEM_ERROR;
2068 } else {
2069 // A device doesn't have to implement delete_keypair.
Kenny Rootb4d2e022013-09-04 13:56:03 -07002070 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Root07438c82012-11-02 15:41:02 -07002071 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2072 rc = ::SYSTEM_ERROR;
2073 }
2074 }
2075 }
2076
2077 if (rc != ::NO_ERROR) {
2078 return rc;
2079 }
2080
2081 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
2082 }
2083
2084 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002085 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2086 if (!has_permission(callingUid, P_GRANT)) {
2087 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002088 return ::PERMISSION_DENIED;
2089 }
Kenny Root07438c82012-11-02 15:41:02 -07002090
Kenny Root655b9582013-04-04 08:37:42 -07002091 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002092 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002093 ALOGD("calling grant in state: %d", state);
2094 return state;
2095 }
2096
2097 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002098 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002099
Kenny Root655b9582013-04-04 08:37:42 -07002100 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002101 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2102 }
2103
Kenny Root655b9582013-04-04 08:37:42 -07002104 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002105 return ::NO_ERROR;
2106 }
2107
2108 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002109 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2110 if (!has_permission(callingUid, P_GRANT)) {
2111 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002112 return ::PERMISSION_DENIED;
2113 }
Kenny Root07438c82012-11-02 15:41:02 -07002114
Kenny Root655b9582013-04-04 08:37:42 -07002115 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002116 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002117 ALOGD("calling ungrant in state: %d", state);
2118 return state;
2119 }
2120
2121 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002122 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002123
Kenny Root655b9582013-04-04 08:37:42 -07002124 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002125 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2126 }
2127
Kenny Root655b9582013-04-04 08:37:42 -07002128 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002129 }
2130
2131 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002132 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2133 if (!has_permission(callingUid, P_GET)) {
2134 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002135 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002136 }
Kenny Root07438c82012-11-02 15:41:02 -07002137
2138 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002139 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002140
Kenny Root655b9582013-04-04 08:37:42 -07002141 if (access(filename.string(), R_OK) == -1) {
2142 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002143 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002144 }
2145
Kenny Root655b9582013-04-04 08:37:42 -07002146 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002147 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002148 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002149 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002150 }
2151
2152 struct stat s;
2153 int ret = fstat(fd, &s);
2154 close(fd);
2155 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002156 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002157 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002158 }
2159
Kenny Root36a9e232013-02-04 14:24:15 -08002160 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002161 }
2162
Kenny Rootd53bc922013-03-21 14:10:15 -07002163 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2164 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002165 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Rootd53bc922013-03-21 14:10:15 -07002166 if (!has_permission(callingUid, P_DUPLICATE)) {
2167 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002168 return -1L;
2169 }
2170
Kenny Root655b9582013-04-04 08:37:42 -07002171 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002172 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002173 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002174 return state;
2175 }
2176
Kenny Rootd53bc922013-03-21 14:10:15 -07002177 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2178 srcUid = callingUid;
2179 } else if (!is_granted_to(callingUid, srcUid)) {
2180 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002181 return ::PERMISSION_DENIED;
2182 }
2183
Kenny Rootd53bc922013-03-21 14:10:15 -07002184 if (destUid == -1) {
2185 destUid = callingUid;
2186 }
2187
2188 if (srcUid != destUid) {
2189 if (static_cast<uid_t>(srcUid) != callingUid) {
2190 ALOGD("can only duplicate from caller to other or to same uid: "
2191 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2192 return ::PERMISSION_DENIED;
2193 }
2194
2195 if (!is_granted_to(callingUid, destUid)) {
2196 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2197 return ::PERMISSION_DENIED;
2198 }
2199 }
2200
2201 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002202 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002203
Kenny Rootd53bc922013-03-21 14:10:15 -07002204 String8 target8(destKey);
Kenny Root655b9582013-04-04 08:37:42 -07002205 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002206
Kenny Root655b9582013-04-04 08:37:42 -07002207 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2208 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002209 return ::SYSTEM_ERROR;
2210 }
2211
Kenny Rootd53bc922013-03-21 14:10:15 -07002212 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002213 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
2214 callingUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002215 if (responseCode != ::NO_ERROR) {
2216 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002217 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002218
Kenny Root655b9582013-04-04 08:37:42 -07002219 return mKeyStore->put(targetFile.string(), &keyBlob, callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002220 }
2221
Kenny Root8ddf35a2013-03-29 11:15:50 -07002222 int32_t is_hardware_backed() {
2223 return mKeyStore->isHardwareBacked() ? 1 : 0;
2224 }
2225
Kenny Roota9bb5492013-04-01 16:29:11 -07002226 int32_t clear_uid(int64_t targetUid) {
2227 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2228 if (!has_permission(callingUid, P_CLEAR_UID)) {
2229 ALOGW("permission denied for %d: clear_uid", callingUid);
2230 return ::PERMISSION_DENIED;
2231 }
2232
Kenny Root655b9582013-04-04 08:37:42 -07002233 State state = mKeyStore->getState(callingUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002234 if (!isKeystoreUnlocked(state)) {
2235 ALOGD("calling clear_uid in state: %d", state);
2236 return state;
2237 }
2238
2239 const keymaster_device_t* device = mKeyStore->getDevice();
2240 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002241 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002242 return ::SYSTEM_ERROR;
2243 }
2244
Kenny Root655b9582013-04-04 08:37:42 -07002245 UserState* userState = mKeyStore->getUserState(callingUid);
2246 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota9bb5492013-04-01 16:29:11 -07002247 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07002248 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Roota9bb5492013-04-01 16:29:11 -07002249 return ::SYSTEM_ERROR;
2250 }
2251
Kenny Root655b9582013-04-04 08:37:42 -07002252 char prefix[NAME_MAX];
2253 int n = snprintf(prefix, NAME_MAX, "%u_", static_cast<uid_t>(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002254
2255 ResponseCode rc = ::NO_ERROR;
2256
2257 struct dirent* file;
2258 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002259 // We only care about files.
2260 if (file->d_type != DT_REG) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002261 continue;
2262 }
2263
Kenny Root655b9582013-04-04 08:37:42 -07002264 // Skip anything that starts with a "."
2265 if (file->d_name[0] == '.') {
2266 continue;
2267 }
Kenny Roota9bb5492013-04-01 16:29:11 -07002268
Kenny Root655b9582013-04-04 08:37:42 -07002269 if (strncmp(prefix, file->d_name, n)) {
2270 continue;
2271 }
2272
2273 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Roota9bb5492013-04-01 16:29:11 -07002274 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002275 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, callingUid)
2276 != ::NO_ERROR) {
2277 ALOGW("couldn't open %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002278 continue;
2279 }
2280
2281 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2282 // A device doesn't have to implement delete_keypair.
Kenny Rootb4d2e022013-09-04 13:56:03 -07002283 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002284 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2285 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002286 ALOGW("device couldn't remove %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002287 }
2288 }
2289 }
2290
Kenny Root5f531242013-04-12 11:31:50 -07002291 if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002292 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002293 ALOGW("couldn't unlink %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002294 }
2295 }
2296 closedir(dir);
2297
2298 return rc;
2299 }
2300
Kenny Root07438c82012-11-02 15:41:02 -07002301private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002302 inline bool isKeystoreUnlocked(State state) {
2303 switch (state) {
2304 case ::STATE_NO_ERROR:
2305 return true;
2306 case ::STATE_UNINITIALIZED:
2307 case ::STATE_LOCKED:
2308 return false;
2309 }
2310 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002311 }
2312
2313 ::KeyStore* mKeyStore;
2314};
2315
2316}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002317
2318int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002319 if (argc < 2) {
2320 ALOGE("A directory must be specified!");
2321 return 1;
2322 }
2323 if (chdir(argv[1]) == -1) {
2324 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2325 return 1;
2326 }
2327
2328 Entropy entropy;
2329 if (!entropy.open()) {
2330 return 1;
2331 }
Kenny Root70e3a862012-02-15 17:20:23 -08002332
2333 keymaster_device_t* dev;
2334 if (keymaster_device_initialize(&dev)) {
2335 ALOGE("keystore keymaster could not be initialized; exiting");
2336 return 1;
2337 }
2338
Kenny Root70e3a862012-02-15 17:20:23 -08002339 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002340 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002341 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2342 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2343 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2344 if (ret != android::OK) {
2345 ALOGE("Couldn't register binder service!");
2346 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002347 }
Kenny Root07438c82012-11-02 15:41:02 -07002348
2349 /*
2350 * We're the only thread in existence, so we're just going to process
2351 * Binder transaction as a single-threaded program.
2352 */
2353 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002354
2355 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002356 return 1;
2357}