blob: 8bfb970fa278c19ddacdd17430e8d9574d93e176 [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 Root68b46312013-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 Root68b46312013-04-04 08:37:42 -070045#include <utils/String8.h>
Kenny Root822c3a92012-03-23 16:34:39 -070046#include <utils/UniquePtr.h>
Kenny Root68b46312013-04-04 08:37:42 -070047#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080048
Kenny Root07438c82012-11-02 15:41:02 -070049#include <keystore/IKeystoreService.h>
50#include <binder/IPCThreadState.h>
51#include <binder/IServiceManager.h>
52
Kenny Roota91203b2012-02-15 15:00:46 -080053#include <cutils/log.h>
54#include <cutils/sockets.h>
55#include <private/android_filesystem_config.h>
56
Kenny Root07438c82012-11-02 15:41:02 -070057#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080058
59/* KeyStore is a secured storage for key-value pairs. In this implementation,
60 * each file stores one key-value pair. Keys are encoded in file names, and
61 * values are encrypted with checksums. The encryption key is protected by a
62 * user-defined password. To keep things simple, buffers are always larger than
63 * the maximum space we needed, so boundary checks on buffers are omitted. */
64
65#define KEY_SIZE ((NAME_MAX - 15) / 2)
66#define VALUE_SIZE 32768
67#define PASSWORD_SIZE VALUE_SIZE
68
Kenny Root822c3a92012-03-23 16:34:39 -070069
70struct BIO_Delete {
71 void operator()(BIO* p) const {
72 BIO_free(p);
73 }
74};
75typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
76
77struct EVP_PKEY_Delete {
78 void operator()(EVP_PKEY* p) const {
79 EVP_PKEY_free(p);
80 }
81};
82typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
83
84struct PKCS8_PRIV_KEY_INFO_Delete {
85 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
86 PKCS8_PRIV_KEY_INFO_free(p);
87 }
88};
89typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
90
91
Kenny Root70e3a862012-02-15 17:20:23 -080092static int keymaster_device_initialize(keymaster_device_t** dev) {
93 int rc;
94
95 const hw_module_t* mod;
96 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
97 if (rc) {
98 ALOGE("could not find any keystore module");
99 goto out;
100 }
101
102 rc = keymaster_open(mod, dev);
103 if (rc) {
104 ALOGE("could not open keymaster device in %s (%s)",
105 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
106 goto out;
107 }
108
109 return 0;
110
111out:
112 *dev = NULL;
113 return rc;
114}
115
116static void keymaster_device_release(keymaster_device_t* dev) {
117 keymaster_close(dev);
118}
119
Kenny Root07438c82012-11-02 15:41:02 -0700120/***************
121 * PERMISSIONS *
122 ***************/
123
124/* Here are the permissions, actions, users, and the main function. */
125typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700126 P_TEST = 1 << 0,
127 P_GET = 1 << 1,
128 P_INSERT = 1 << 2,
129 P_DELETE = 1 << 3,
130 P_EXIST = 1 << 4,
131 P_SAW = 1 << 5,
132 P_RESET = 1 << 6,
133 P_PASSWORD = 1 << 7,
134 P_LOCK = 1 << 8,
135 P_UNLOCK = 1 << 9,
136 P_ZERO = 1 << 10,
137 P_SIGN = 1 << 11,
138 P_VERIFY = 1 << 12,
139 P_GRANT = 1 << 13,
140 P_DUPLICATE = 1 << 14,
Kenny Root2ecc7a12013-04-01 16:29:11 -0700141 P_CLEAR_UID = 1 << 15,
Kenny Root07438c82012-11-02 15:41:02 -0700142} perm_t;
143
144static struct user_euid {
145 uid_t uid;
146 uid_t euid;
147} user_euids[] = {
148 {AID_VPN, AID_SYSTEM},
149 {AID_WIFI, AID_SYSTEM},
150 {AID_ROOT, AID_SYSTEM},
151};
152
153static struct user_perm {
154 uid_t uid;
155 perm_t perms;
156} user_perms[] = {
157 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
158 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
159 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
160 {AID_ROOT, static_cast<perm_t>(P_GET) },
161};
162
163static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
164 | P_VERIFY);
165
Kenny Root68b46312013-04-04 08:37:42 -0700166/**
167 * Returns the app ID (in the Android multi-user sense) for the current
168 * UNIX UID.
169 */
170static uid_t get_app_id(uid_t uid) {
171 return uid % AID_USER;
172}
173
174/**
175 * Returns the user ID (in the Android multi-user sense) for the current
176 * UNIX UID.
177 */
178static uid_t get_user_id(uid_t uid) {
179 return uid / AID_USER;
180}
181
182
Kenny Root07438c82012-11-02 15:41:02 -0700183static bool has_permission(uid_t uid, perm_t perm) {
Kenny Root68b46312013-04-04 08:37:42 -0700184 // All system users are equivalent for multi-user support.
185 if (get_app_id(uid) == AID_SYSTEM) {
186 uid = AID_SYSTEM;
187 }
188
Kenny Root07438c82012-11-02 15:41:02 -0700189 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
190 struct user_perm user = user_perms[i];
191 if (user.uid == uid) {
192 return user.perms & perm;
193 }
194 }
195
196 return DEFAULT_PERMS & perm;
197}
198
Kenny Root49468902013-03-19 13:41:33 -0700199/**
200 * Returns the UID that the callingUid should act as. This is here for
201 * legacy support of the WiFi and VPN systems and should be removed
202 * when WiFi can operate in its own namespace.
203 */
Kenny Root07438c82012-11-02 15:41:02 -0700204static uid_t get_keystore_euid(uid_t uid) {
205 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
206 struct user_euid user = user_euids[i];
207 if (user.uid == uid) {
208 return user.euid;
209 }
210 }
211
212 return uid;
213}
214
Kenny Root49468902013-03-19 13:41:33 -0700215/**
216 * Returns true if the callingUid is allowed to interact in the targetUid's
217 * namespace.
218 */
219static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
220 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
221 struct user_euid user = user_euids[i];
222 if (user.euid == callingUid && user.uid == targetUid) {
223 return true;
224 }
225 }
226
227 return false;
228}
229
Kenny Roota91203b2012-02-15 15:00:46 -0800230/* Here is the encoding of keys. This is necessary in order to allow arbitrary
231 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
232 * into two bytes. The first byte is one of [+-.] which represents the first
233 * two bits of the character. The second byte encodes the rest of the bits into
234 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
235 * that Base64 cannot be used here due to the need of prefix match on keys. */
236
Kenny Root68b46312013-04-04 08:37:42 -0700237static size_t encode_key_length(const android::String8& keyName) {
238 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
239 size_t length = keyName.length();
240 for (int i = length; i > 0; --i, ++in) {
241 if (*in < '0' || *in > '~') {
242 ++length;
243 }
244 }
245 return length;
246}
247
Kenny Root07438c82012-11-02 15:41:02 -0700248static int encode_key(char* out, const android::String8& keyName) {
249 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
250 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800251 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root68b46312013-04-04 08:37:42 -0700252 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800253 *out = '+' + (*in >> 6);
254 *++out = '0' + (*in & 0x3F);
255 ++length;
Kenny Root68b46312013-04-04 08:37:42 -0700256 } else {
257 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800258 }
259 }
260 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800261 return length;
262}
263
Kenny Root07438c82012-11-02 15:41:02 -0700264/*
265 * Converts from the "escaped" format on disk to actual name.
266 * This will be smaller than the input string.
267 *
268 * Characters that should combine with the next at the end will be truncated.
269 */
270static size_t decode_key_length(const char* in, size_t length) {
271 size_t outLength = 0;
272
273 for (const char* end = in + length; in < end; in++) {
274 /* This combines with the next character. */
275 if (*in < '0' || *in > '~') {
276 continue;
277 }
278
279 outLength++;
280 }
281 return outLength;
282}
283
284static void decode_key(char* out, const char* in, size_t length) {
285 for (const char* end = in + length; in < end; in++) {
286 if (*in < '0' || *in > '~') {
287 /* Truncate combining characters at the end. */
288 if (in + 1 >= end) {
289 break;
290 }
291
292 *out = (*in++ - '+') << 6;
293 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800294 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700295 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800296 }
297 }
298 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800299}
300
301static size_t readFully(int fd, uint8_t* data, size_t size) {
302 size_t remaining = size;
303 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800304 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800305 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800306 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800307 }
308 data += n;
309 remaining -= n;
310 }
311 return size;
312}
313
314static size_t writeFully(int fd, uint8_t* data, size_t size) {
315 size_t remaining = size;
316 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800317 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
318 if (n < 0) {
319 ALOGW("write failed: %s", strerror(errno));
320 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800321 }
322 data += n;
323 remaining -= n;
324 }
325 return size;
326}
327
328class Entropy {
329public:
330 Entropy() : mRandom(-1) {}
331 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800332 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800333 close(mRandom);
334 }
335 }
336
337 bool open() {
338 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800339 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
340 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800341 ALOGE("open: %s: %s", randomDevice, strerror(errno));
342 return false;
343 }
344 return true;
345 }
346
Kenny Root51878182012-03-13 12:53:19 -0700347 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800348 return (readFully(mRandom, data, size) == size);
349 }
350
351private:
352 int mRandom;
353};
354
355/* Here is the file format. There are two parts in blob.value, the secret and
356 * the description. The secret is stored in ciphertext, and its original size
357 * can be found in blob.length. The description is stored after the secret in
358 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700359 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Root0c540aa2013-04-03 09:22:15 -0700360 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800361 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
362 * and decryptBlob(). Thus they should not be accessed from outside. */
363
Kenny Root822c3a92012-03-23 16:34:39 -0700364/* ** Note to future implementors of encryption: **
365 * Currently this is the construction:
366 * metadata || Enc(MD5(data) || data)
367 *
368 * This should be the construction used for encrypting if re-implementing:
369 *
370 * Derive independent keys for encryption and MAC:
371 * Kenc = AES_encrypt(masterKey, "Encrypt")
372 * Kmac = AES_encrypt(masterKey, "MAC")
373 *
374 * Store this:
375 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
376 * HMAC(Kmac, metadata || Enc(data))
377 */
Kenny Roota91203b2012-02-15 15:00:46 -0800378struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700379 uint8_t version;
380 uint8_t type;
Kenny Root0c540aa2013-04-03 09:22:15 -0700381 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800382 uint8_t info;
383 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700384 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800385 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700386 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800387 int32_t length; // in network byte order when encrypted
388 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
389};
390
Kenny Root822c3a92012-03-23 16:34:39 -0700391typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700392 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700393 TYPE_GENERIC = 1,
394 TYPE_MASTER_KEY = 2,
395 TYPE_KEY_PAIR = 3,
396} BlobType;
397
Kenny Root0c540aa2013-04-03 09:22:15 -0700398static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700399
Kenny Roota91203b2012-02-15 15:00:46 -0800400class Blob {
401public:
Kenny Root07438c82012-11-02 15:41:02 -0700402 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
403 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800404 mBlob.length = valueLength;
405 memcpy(mBlob.value, value, valueLength);
406
407 mBlob.info = infoLength;
408 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700409
Kenny Root07438c82012-11-02 15:41:02 -0700410 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700411 mBlob.type = uint8_t(type);
Kenny Root0c540aa2013-04-03 09:22:15 -0700412
413 mBlob.flags = KEYSTORE_FLAG_NONE;
Kenny Roota91203b2012-02-15 15:00:46 -0800414 }
415
416 Blob(blob b) {
417 mBlob = b;
418 }
419
420 Blob() {}
421
Kenny Root51878182012-03-13 12:53:19 -0700422 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800423 return mBlob.value;
424 }
425
Kenny Root51878182012-03-13 12:53:19 -0700426 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800427 return mBlob.length;
428 }
429
Kenny Root51878182012-03-13 12:53:19 -0700430 const uint8_t* getInfo() const {
431 return mBlob.value + mBlob.length;
432 }
433
434 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800435 return mBlob.info;
436 }
437
Kenny Root822c3a92012-03-23 16:34:39 -0700438 uint8_t getVersion() const {
439 return mBlob.version;
440 }
441
Kenny Root0c540aa2013-04-03 09:22:15 -0700442 bool isEncrypted() const {
443 if (mBlob.version < 2) {
444 return true;
445 }
446
447 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
448 }
449
450 void setEncrypted(bool encrypted) {
451 if (encrypted) {
452 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
453 } else {
454 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
455 }
456 }
457
Kenny Root822c3a92012-03-23 16:34:39 -0700458 void setVersion(uint8_t version) {
459 mBlob.version = version;
460 }
461
462 BlobType getType() const {
463 return BlobType(mBlob.type);
464 }
465
466 void setType(BlobType type) {
467 mBlob.type = uint8_t(type);
468 }
469
Kenny Root0c540aa2013-04-03 09:22:15 -0700470 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
471 ALOGV("writing blob %s", filename);
472 if (isEncrypted()) {
473 if (state != STATE_NO_ERROR) {
474 ALOGD("couldn't insert encrypted blob while not unlocked");
475 return LOCKED;
476 }
477
478 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
479 ALOGW("Could not read random data for: %s", filename);
480 return SYSTEM_ERROR;
481 }
Kenny Roota91203b2012-02-15 15:00:46 -0800482 }
483
484 // data includes the value and the value's length
485 size_t dataLength = mBlob.length + sizeof(mBlob.length);
486 // pad data to the AES_BLOCK_SIZE
487 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
488 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
489 // encrypted data includes the digest value
490 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
491 // move info after space for padding
492 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
493 // zero padding area
494 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
495
496 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800497
Kenny Root0c540aa2013-04-03 09:22:15 -0700498 if (isEncrypted()) {
499 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800500
Kenny Root0c540aa2013-04-03 09:22:15 -0700501 uint8_t vector[AES_BLOCK_SIZE];
502 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
503 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
504 aes_key, vector, AES_ENCRYPT);
505 }
506
Kenny Roota91203b2012-02-15 15:00:46 -0800507 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
508 size_t fileLength = encryptedLength + headerLength + mBlob.info;
509
510 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800511 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
512 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
513 if (out < 0) {
514 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800515 return SYSTEM_ERROR;
516 }
517 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
518 if (close(out) != 0) {
519 return SYSTEM_ERROR;
520 }
521 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800522 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800523 unlink(tmpFileName);
524 return SYSTEM_ERROR;
525 }
Kenny Root150ca932012-11-14 14:29:02 -0800526 if (rename(tmpFileName, filename) == -1) {
527 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
528 return SYSTEM_ERROR;
529 }
530 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800531 }
532
Kenny Root0c540aa2013-04-03 09:22:15 -0700533 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
534 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800535 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
536 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800537 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
538 }
539 // fileLength may be less than sizeof(mBlob) since the in
540 // memory version has extra padding to tolerate rounding up to
541 // the AES_BLOCK_SIZE
542 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
543 if (close(in) != 0) {
544 return SYSTEM_ERROR;
545 }
Kenny Root0c540aa2013-04-03 09:22:15 -0700546
547 if (isEncrypted() && (state != STATE_NO_ERROR)) {
548 return LOCKED;
549 }
550
Kenny Roota91203b2012-02-15 15:00:46 -0800551 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
552 if (fileLength < headerLength) {
553 return VALUE_CORRUPTED;
554 }
555
556 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Root0c540aa2013-04-03 09:22:15 -0700557 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800558 return VALUE_CORRUPTED;
559 }
Kenny Root0c540aa2013-04-03 09:22:15 -0700560
561 ssize_t digestedLength;
562 if (isEncrypted()) {
563 if (encryptedLength % AES_BLOCK_SIZE != 0) {
564 return VALUE_CORRUPTED;
565 }
566
567 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
568 mBlob.vector, AES_DECRYPT);
569 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
570 uint8_t computedDigest[MD5_DIGEST_LENGTH];
571 MD5(mBlob.digested, digestedLength, computedDigest);
572 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
573 return VALUE_CORRUPTED;
574 }
575 } else {
576 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800577 }
578
579 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
580 mBlob.length = ntohl(mBlob.length);
581 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
582 return VALUE_CORRUPTED;
583 }
584 if (mBlob.info != 0) {
585 // move info from after padding to after data
586 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
587 }
Kenny Root07438c82012-11-02 15:41:02 -0700588 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800589 }
590
591private:
592 struct blob mBlob;
593};
594
Kenny Root68b46312013-04-04 08:37:42 -0700595class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800596public:
Kenny Root68b46312013-04-04 08:37:42 -0700597 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
598 asprintf(&mUserDir, "user_%u", mUserId);
599 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
600 }
601
602 ~UserState() {
603 free(mUserDir);
604 free(mMasterKeyFile);
605 }
606
607 bool initialize() {
608 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
609 ALOGE("Could not create directory '%s'", mUserDir);
610 return false;
611 }
612
613 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800614 setState(STATE_LOCKED);
615 } else {
616 setState(STATE_UNINITIALIZED);
617 }
Kenny Root70e3a862012-02-15 17:20:23 -0800618
Kenny Root68b46312013-04-04 08:37:42 -0700619 return true;
620 }
621
622 uid_t getUserId() const {
623 return mUserId;
624 }
625
626 const char* getUserDirName() const {
627 return mUserDir;
628 }
629
630 const char* getMasterKeyFileName() const {
631 return mMasterKeyFile;
632 }
633
634 void setState(State state) {
635 mState = state;
636 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
637 mRetry = MAX_RETRY;
638 }
Kenny Roota91203b2012-02-15 15:00:46 -0800639 }
640
Kenny Root51878182012-03-13 12:53:19 -0700641 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800642 return mState;
643 }
644
Kenny Root51878182012-03-13 12:53:19 -0700645 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800646 return mRetry;
647 }
648
Kenny Root68b46312013-04-04 08:37:42 -0700649 void zeroizeMasterKeysInMemory() {
650 memset(mMasterKey, 0, sizeof(mMasterKey));
651 memset(mSalt, 0, sizeof(mSalt));
652 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
653 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800654 }
655
Kenny Root68b46312013-04-04 08:37:42 -0700656 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
657 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800658 return SYSTEM_ERROR;
659 }
Kenny Root68b46312013-04-04 08:37:42 -0700660 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800661 if (response != NO_ERROR) {
662 return response;
663 }
664 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700665 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800666 }
667
Kenny Root68b46312013-04-04 08:37:42 -0700668 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800669 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
670 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
671 AES_KEY passwordAesKey;
672 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700673 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Root0c540aa2013-04-03 09:22:15 -0700674 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800675 }
676
Kenny Root68b46312013-04-04 08:37:42 -0700677 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
678 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800679 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800680 return SYSTEM_ERROR;
681 }
682
683 // we read the raw blob to just to get the salt to generate
684 // the AES key, then we create the Blob to use with decryptBlob
685 blob rawBlob;
686 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
687 if (close(in) != 0) {
688 return SYSTEM_ERROR;
689 }
690 // find salt at EOF if present, otherwise we have an old file
691 uint8_t* salt;
692 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
693 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
694 } else {
695 salt = NULL;
696 }
697 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
698 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
699 AES_KEY passwordAesKey;
700 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
701 Blob masterKeyBlob(rawBlob);
Kenny Root0c540aa2013-04-03 09:22:15 -0700702 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
703 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800704 if (response == SYSTEM_ERROR) {
Kenny Root0c540aa2013-04-03 09:22:15 -0700705 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800706 }
707 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
708 // if salt was missing, generate one and write a new master key file with the salt.
709 if (salt == NULL) {
Kenny Root68b46312013-04-04 08:37:42 -0700710 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800711 return SYSTEM_ERROR;
712 }
Kenny Root68b46312013-04-04 08:37:42 -0700713 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800714 }
715 if (response == NO_ERROR) {
716 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
717 setupMasterKeys();
718 }
719 return response;
720 }
721 if (mRetry <= 0) {
722 reset();
723 return UNINITIALIZED;
724 }
725 --mRetry;
726 switch (mRetry) {
727 case 0: return WRONG_PASSWORD_0;
728 case 1: return WRONG_PASSWORD_1;
729 case 2: return WRONG_PASSWORD_2;
730 case 3: return WRONG_PASSWORD_3;
731 default: return WRONG_PASSWORD_3;
732 }
733 }
734
Kenny Root68b46312013-04-04 08:37:42 -0700735 AES_KEY* getEncryptionKey() {
736 return &mMasterKeyEncryption;
737 }
738
739 AES_KEY* getDecryptionKey() {
740 return &mMasterKeyDecryption;
741 }
742
Kenny Roota91203b2012-02-15 15:00:46 -0800743 bool reset() {
Kenny Root68b46312013-04-04 08:37:42 -0700744 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800745 if (!dir) {
Kenny Root68b46312013-04-04 08:37:42 -0700746 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800747 return false;
748 }
Kenny Root68b46312013-04-04 08:37:42 -0700749
750 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800751 while ((file = readdir(dir)) != NULL) {
Kenny Root68b46312013-04-04 08:37:42 -0700752 // We only care about files.
753 if (file->d_type != DT_REG) {
754 continue;
755 }
756
757 // Skip anything that starts with a "."
758 if (file->d_name[0] == '.') {
759 continue;
760 }
761
762 // Find the current file's UID.
763 char* end;
764 unsigned long thisUid = strtoul(file->d_name, &end, 10);
765 if (end[0] != '_' || end[1] == 0) {
766 continue;
767 }
768
769 // Skip if this is not our user.
770 if (get_user_id(thisUid) != mUserId) {
771 continue;
772 }
773
774 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800775 }
776 closedir(dir);
777 return true;
778 }
779
Kenny Root68b46312013-04-04 08:37:42 -0700780private:
781 static const int MASTER_KEY_SIZE_BYTES = 16;
782 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
783
784 static const int MAX_RETRY = 4;
785 static const size_t SALT_SIZE = 16;
786
787 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
788 uint8_t* salt) {
789 size_t saltSize;
790 if (salt != NULL) {
791 saltSize = SALT_SIZE;
792 } else {
793 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
794 salt = (uint8_t*) "keystore";
795 // sizeof = 9, not strlen = 8
796 saltSize = sizeof("keystore");
797 }
798
799 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
800 saltSize, 8192, keySize, key);
801 }
802
803 bool generateSalt(Entropy* entropy) {
804 return entropy->generate_random_data(mSalt, sizeof(mSalt));
805 }
806
807 bool generateMasterKey(Entropy* entropy) {
808 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
809 return false;
810 }
811 if (!generateSalt(entropy)) {
812 return false;
813 }
814 return true;
815 }
816
817 void setupMasterKeys() {
818 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
819 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
820 setState(STATE_NO_ERROR);
821 }
822
823 uid_t mUserId;
824
825 char* mUserDir;
826 char* mMasterKeyFile;
827
828 State mState;
829 int8_t mRetry;
830
831 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
832 uint8_t mSalt[SALT_SIZE];
833
834 AES_KEY mMasterKeyEncryption;
835 AES_KEY mMasterKeyDecryption;
836};
837
838typedef struct {
839 uint32_t uid;
840 const uint8_t* filename;
841} grant_t;
842
843class KeyStore {
844public:
845 KeyStore(Entropy* entropy, keymaster_device_t* device)
846 : mEntropy(entropy)
847 , mDevice(device)
848 {
849 memset(&mMetaData, '\0', sizeof(mMetaData));
850 }
851
852 ~KeyStore() {
853 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
854 it != mGrants.end(); it++) {
855 delete *it;
856 mGrants.erase(it);
857 }
858
859 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
860 it != mMasterKeys.end(); it++) {
861 delete *it;
862 mMasterKeys.erase(it);
863 }
864 }
865
866 keymaster_device_t* getDevice() const {
867 return mDevice;
868 }
869
870 ResponseCode initialize() {
871 readMetaData();
872 if (upgradeKeystore()) {
873 writeMetaData();
874 }
875
876 return ::NO_ERROR;
877 }
878
879 State getState(uid_t uid) {
880 return getUserState(uid)->getState();
881 }
882
883 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
884 UserState* userState = getUserState(uid);
885 return userState->initialize(pw, mEntropy);
886 }
887
888 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
889 uid_t user_id = get_user_id(uid);
890 UserState* userState = getUserState(user_id);
891 return userState->writeMasterKey(pw, mEntropy);
892 }
893
894 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
895 uid_t user_id = get_user_id(uid);
896 UserState* userState = getUserState(user_id);
897 return userState->readMasterKey(pw, mEntropy);
898 }
899
900 android::String8 getKeyName(const android::String8& keyName) {
901 char encoded[encode_key_length(keyName)];
902 encode_key(encoded, keyName);
903 return android::String8(encoded);
904 }
905
906 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
907 char encoded[encode_key_length(keyName)];
908 encode_key(encoded, keyName);
909 return android::String8::format("%u_%s", uid, encoded);
910 }
911
912 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
913 char encoded[encode_key_length(keyName)];
914 encode_key(encoded, keyName);
915 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
916 encoded);
917 }
918
919 bool reset(uid_t uid) {
920 UserState* userState = getUserState(uid);
921 userState->zeroizeMasterKeysInMemory();
922 userState->setState(STATE_UNINITIALIZED);
923 return userState->reset();
924 }
925
926 bool isEmpty(uid_t uid) const {
927 const UserState* userState = getUserState(uid);
928 if (userState == NULL) {
929 return true;
930 }
931
932 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800933 struct dirent* file;
934 if (!dir) {
935 return true;
936 }
937 bool result = true;
Kenny Root68b46312013-04-04 08:37:42 -0700938
939 char filename[NAME_MAX];
940 int n = snprintf(filename, sizeof(filename), "%u_", uid);
941
Kenny Roota91203b2012-02-15 15:00:46 -0800942 while ((file = readdir(dir)) != NULL) {
Kenny Root68b46312013-04-04 08:37:42 -0700943 // We only care about files.
944 if (file->d_type != DT_REG) {
945 continue;
946 }
947
948 // Skip anything that starts with a "."
949 if (file->d_name[0] == '.') {
950 continue;
951 }
952
953 if (!strncmp(file->d_name, filename, n)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800954 result = false;
955 break;
956 }
957 }
958 closedir(dir);
959 return result;
960 }
961
Kenny Root68b46312013-04-04 08:37:42 -0700962 void lock(uid_t uid) {
963 UserState* userState = getUserState(uid);
964 userState->zeroizeMasterKeysInMemory();
965 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -0800966 }
967
Kenny Root68b46312013-04-04 08:37:42 -0700968 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
969 UserState* userState = getUserState(uid);
Kenny Root0c540aa2013-04-03 09:22:15 -0700970 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
971 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -0700972 if (rc != NO_ERROR) {
973 return rc;
974 }
975
976 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -0700977 if (version < CURRENT_BLOB_VERSION) {
Kenny Root7a310fb2013-04-04 08:39:57 -0700978 /* If we upgrade the key, we need to write it to disk again. Then
979 * it must be read it again since the blob is encrypted each time
980 * it's written.
981 */
Kenny Root68b46312013-04-04 08:37:42 -0700982 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
983 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Root0c540aa2013-04-03 09:22:15 -0700984 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
985 userState->getState())) != NO_ERROR) {
Kenny Root7a310fb2013-04-04 08:39:57 -0700986 return rc;
987 }
988 }
Kenny Root822c3a92012-03-23 16:34:39 -0700989 }
990
Kenny Rootd53bc922013-03-21 14:10:15 -0700991 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -0700992 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
993 return KEY_NOT_FOUND;
994 }
995
996 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -0800997 }
998
Kenny Root68b46312013-04-04 08:37:42 -0700999 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1000 UserState* userState = getUserState(uid);
Kenny Root0c540aa2013-04-03 09:22:15 -07001001 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1002 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001003 }
1004
Kenny Root07438c82012-11-02 15:41:02 -07001005 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root68b46312013-04-04 08:37:42 -07001006 const grant_t* existing = getGrant(filename, granteeUid);
1007 if (existing == NULL) {
1008 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001009 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001010 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root68b46312013-04-04 08:37:42 -07001011 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001012 }
1013 }
1014
Kenny Root07438c82012-11-02 15:41:02 -07001015 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root68b46312013-04-04 08:37:42 -07001016 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1017 it != mGrants.end(); it++) {
1018 grant_t* grant = *it;
1019 if (grant->uid == granteeUid
1020 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1021 mGrants.erase(it);
1022 return true;
1023 }
Kenny Root70e3a862012-02-15 17:20:23 -08001024 }
Kenny Root70e3a862012-02-15 17:20:23 -08001025 return false;
1026 }
1027
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001028 bool hasGrant(const char* filename, const uid_t uid) const {
1029 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001030 }
1031
Kenny Root0c540aa2013-04-03 09:22:15 -07001032 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1033 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001034 uint8_t* data;
1035 size_t dataLength;
1036 int rc;
1037
1038 if (mDevice->import_keypair == NULL) {
1039 ALOGE("Keymaster doesn't support import!");
1040 return SYSTEM_ERROR;
1041 }
1042
Kenny Root07438c82012-11-02 15:41:02 -07001043 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001044 if (rc) {
1045 ALOGE("Error while importing keypair: %d", rc);
1046 return SYSTEM_ERROR;
1047 }
1048
1049 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1050 free(data);
1051
Kenny Root0c540aa2013-04-03 09:22:15 -07001052 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1053
Kenny Root68b46312013-04-04 08:37:42 -07001054 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001055 }
1056
Kenny Root43061232013-03-29 11:15:50 -07001057 bool isHardwareBacked() const {
Kenny Root4d93d242013-04-04 17:12:25 -07001058 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
Kenny Root43061232013-03-29 11:15:50 -07001059 }
1060
Kenny Root68b46312013-04-04 08:37:42 -07001061 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1062 const BlobType type) {
Kenny Root02d44fe2013-09-09 11:15:54 -07001063 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root68b46312013-04-04 08:37:42 -07001064
1065 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1066 if (responseCode == NO_ERROR) {
1067 return responseCode;
1068 }
1069
1070 // If this is one of the legacy UID->UID mappings, use it.
1071 uid_t euid = get_keystore_euid(uid);
1072 if (euid != uid) {
Kenny Root02d44fe2013-09-09 11:15:54 -07001073 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root68b46312013-04-04 08:37:42 -07001074 responseCode = get(filepath8.string(), keyBlob, type, uid);
1075 if (responseCode == NO_ERROR) {
1076 return responseCode;
1077 }
1078 }
1079
1080 // They might be using a granted key.
Kenny Root02d44fe2013-09-09 11:15:54 -07001081 android::String8 filename8 = getKeyName(keyName);
Kenny Root68b46312013-04-04 08:37:42 -07001082 char* end;
Kenny Root02d44fe2013-09-09 11:15:54 -07001083 strtoul(filename8.string(), &end, 10);
Kenny Root68b46312013-04-04 08:37:42 -07001084 if (end[0] != '_' || end[1] == 0) {
1085 return KEY_NOT_FOUND;
1086 }
Kenny Root02d44fe2013-09-09 11:15:54 -07001087 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1088 filename8.string());
Kenny Root68b46312013-04-04 08:37:42 -07001089 if (!hasGrant(filepath8.string(), uid)) {
1090 return responseCode;
1091 }
1092
1093 // It is a granted key. Try to load it.
1094 return get(filepath8.string(), keyBlob, type, uid);
1095 }
1096
1097 /**
1098 * Returns any existing UserState or creates it if it doesn't exist.
1099 */
1100 UserState* getUserState(uid_t uid) {
1101 uid_t userId = get_user_id(uid);
1102
1103 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1104 it != mMasterKeys.end(); it++) {
1105 UserState* state = *it;
1106 if (state->getUserId() == userId) {
1107 return state;
1108 }
1109 }
1110
1111 UserState* userState = new UserState(userId);
1112 if (!userState->initialize()) {
1113 /* There's not much we can do if initialization fails. Trying to
1114 * unlock the keystore for that user will fail as well, so any
1115 * subsequent request for this user will just return SYSTEM_ERROR.
1116 */
1117 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1118 }
1119 mMasterKeys.add(userState);
1120 return userState;
1121 }
1122
1123 /**
1124 * Returns NULL if the UserState doesn't already exist.
1125 */
1126 const UserState* getUserState(uid_t uid) const {
1127 uid_t userId = get_user_id(uid);
1128
1129 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1130 it != mMasterKeys.end(); it++) {
1131 UserState* state = *it;
1132 if (state->getUserId() == userId) {
1133 return state;
1134 }
1135 }
1136
1137 return NULL;
1138 }
1139
Kenny Roota91203b2012-02-15 15:00:46 -08001140private:
Kenny Root68b46312013-04-04 08:37:42 -07001141 static const char* sOldMasterKey;
1142 static const char* sMetaDataFile;
Kenny Roota91203b2012-02-15 15:00:46 -08001143 Entropy* mEntropy;
1144
Kenny Root70e3a862012-02-15 17:20:23 -08001145 keymaster_device_t* mDevice;
1146
Kenny Root68b46312013-04-04 08:37:42 -07001147 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001148
Kenny Root68b46312013-04-04 08:37:42 -07001149 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001150
Kenny Root68b46312013-04-04 08:37:42 -07001151 typedef struct {
1152 uint32_t version;
1153 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001154
Kenny Root68b46312013-04-04 08:37:42 -07001155 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001156
Kenny Root68b46312013-04-04 08:37:42 -07001157 const grant_t* getGrant(const char* filename, uid_t uid) const {
1158 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1159 it != mGrants.end(); it++) {
1160 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001161 if (grant->uid == uid
Kenny Root68b46312013-04-04 08:37:42 -07001162 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001163 return grant;
1164 }
1165 }
Kenny Root70e3a862012-02-15 17:20:23 -08001166 return NULL;
1167 }
1168
Kenny Root822c3a92012-03-23 16:34:39 -07001169 /**
1170 * Upgrade code. This will upgrade the key from the current version
1171 * to whatever is newest.
1172 */
Kenny Root68b46312013-04-04 08:37:42 -07001173 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1174 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001175 bool updated = false;
1176 uint8_t version = oldVersion;
1177
1178 /* From V0 -> V1: All old types were unknown */
1179 if (version == 0) {
1180 ALOGV("upgrading to version 1 and setting type %d", type);
1181
1182 blob->setType(type);
1183 if (type == TYPE_KEY_PAIR) {
Kenny Root68b46312013-04-04 08:37:42 -07001184 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001185 }
1186 version = 1;
1187 updated = true;
1188 }
1189
Kenny Root0c540aa2013-04-03 09:22:15 -07001190 /* From V1 -> V2: All old keys were encrypted */
1191 if (version == 1) {
1192 ALOGV("upgrading to version 2");
1193
1194 blob->setEncrypted(true);
1195 version = 2;
1196 updated = true;
1197 }
1198
Kenny Root822c3a92012-03-23 16:34:39 -07001199 /*
1200 * If we've updated, set the key blob to the right version
1201 * and write it.
Kenny Root7a310fb2013-04-04 08:39:57 -07001202 */
Kenny Root822c3a92012-03-23 16:34:39 -07001203 if (updated) {
1204 ALOGV("updated and writing file %s", filename);
1205 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001206 }
Kenny Root7a310fb2013-04-04 08:39:57 -07001207
1208 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001209 }
1210
1211 /**
1212 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1213 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1214 * Then it overwrites the original blob with the new blob
1215 * format that is returned from the keymaster.
1216 */
Kenny Root68b46312013-04-04 08:37:42 -07001217 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001218 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1219 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1220 if (b.get() == NULL) {
1221 ALOGE("Problem instantiating BIO");
1222 return SYSTEM_ERROR;
1223 }
1224
1225 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1226 if (pkey.get() == NULL) {
1227 ALOGE("Couldn't read old PEM file");
1228 return SYSTEM_ERROR;
1229 }
1230
1231 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1232 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1233 if (len < 0) {
1234 ALOGE("Couldn't measure PKCS#8 length");
1235 return SYSTEM_ERROR;
1236 }
1237
Kenny Root70c98892013-02-07 09:10:36 -08001238 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1239 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001240 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1241 ALOGE("Couldn't convert to PKCS#8");
1242 return SYSTEM_ERROR;
1243 }
1244
Kenny Root0c540aa2013-04-03 09:22:15 -07001245 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1246 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001247 if (rc != NO_ERROR) {
1248 return rc;
1249 }
1250
Kenny Root68b46312013-04-04 08:37:42 -07001251 return get(filename, blob, TYPE_KEY_PAIR, uid);
1252 }
1253
1254 void readMetaData() {
1255 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1256 if (in < 0) {
1257 return;
1258 }
1259 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1260 if (fileLength != sizeof(mMetaData)) {
1261 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1262 sizeof(mMetaData));
1263 }
1264 close(in);
1265 }
1266
1267 void writeMetaData() {
1268 const char* tmpFileName = ".metadata.tmp";
1269 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1270 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1271 if (out < 0) {
1272 ALOGE("couldn't write metadata file: %s", strerror(errno));
1273 return;
1274 }
1275 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1276 if (fileLength != sizeof(mMetaData)) {
1277 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1278 sizeof(mMetaData));
1279 }
1280 close(out);
1281 rename(tmpFileName, sMetaDataFile);
1282 }
1283
1284 bool upgradeKeystore() {
1285 bool upgraded = false;
1286
1287 if (mMetaData.version == 0) {
1288 UserState* userState = getUserState(0);
1289
1290 // Initialize first so the directory is made.
1291 userState->initialize();
1292
1293 // Migrate the old .masterkey file to user 0.
1294 if (access(sOldMasterKey, R_OK) == 0) {
1295 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1296 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1297 return false;
1298 }
1299 }
1300
1301 // Initialize again in case we had a key.
1302 userState->initialize();
1303
1304 // Try to migrate existing keys.
1305 DIR* dir = opendir(".");
1306 if (!dir) {
1307 // Give up now; maybe we can upgrade later.
1308 ALOGE("couldn't open keystore's directory; something is wrong");
1309 return false;
1310 }
1311
1312 struct dirent* file;
1313 while ((file = readdir(dir)) != NULL) {
1314 // We only care about files.
1315 if (file->d_type != DT_REG) {
1316 continue;
1317 }
1318
1319 // Skip anything that starts with a "."
1320 if (file->d_name[0] == '.') {
1321 continue;
1322 }
1323
1324 // Find the current file's user.
1325 char* end;
1326 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1327 if (end[0] != '_' || end[1] == 0) {
1328 continue;
1329 }
1330 UserState* otherUser = getUserState(thisUid);
1331 if (otherUser->getUserId() != 0) {
1332 unlinkat(dirfd(dir), file->d_name, 0);
1333 }
1334
1335 // Rename the file into user directory.
1336 DIR* otherdir = opendir(otherUser->getUserDirName());
1337 if (otherdir == NULL) {
1338 ALOGW("couldn't open user directory for rename");
1339 continue;
1340 }
1341 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1342 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1343 }
1344 closedir(otherdir);
1345 }
1346 closedir(dir);
1347
1348 mMetaData.version = 1;
1349 upgraded = true;
1350 }
1351
1352 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001353 }
Kenny Roota91203b2012-02-15 15:00:46 -08001354};
1355
Kenny Root68b46312013-04-04 08:37:42 -07001356const char* KeyStore::sOldMasterKey = ".masterkey";
1357const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001358
Kenny Root07438c82012-11-02 15:41:02 -07001359namespace android {
1360class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1361public:
1362 KeyStoreProxy(KeyStore* keyStore)
1363 : mKeyStore(keyStore)
1364 {
Kenny Roota91203b2012-02-15 15:00:46 -08001365 }
Kenny Roota91203b2012-02-15 15:00:46 -08001366
Kenny Root07438c82012-11-02 15:41:02 -07001367 void binderDied(const wp<IBinder>&) {
1368 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001369 }
Kenny Roota91203b2012-02-15 15:00:46 -08001370
Kenny Root07438c82012-11-02 15:41:02 -07001371 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001372 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1373 if (!has_permission(callingUid, P_TEST)) {
1374 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001375 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001376 }
Kenny Roota91203b2012-02-15 15:00:46 -08001377
Kenny Root68b46312013-04-04 08:37:42 -07001378 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001379 }
1380
Kenny Root07438c82012-11-02 15:41:02 -07001381 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001382 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1383 if (!has_permission(callingUid, P_GET)) {
1384 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001385 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001386 }
Kenny Root07438c82012-11-02 15:41:02 -07001387
Kenny Root07438c82012-11-02 15:41:02 -07001388 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001389 Blob keyBlob;
Kenny Root49468902013-03-19 13:41:33 -07001390
Kenny Root68b46312013-04-04 08:37:42 -07001391 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001392 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001393 if (responseCode != ::NO_ERROR) {
Kenny Root68b46312013-04-04 08:37:42 -07001394 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001395 *item = NULL;
1396 *itemLength = 0;
1397 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001398 }
Kenny Roota91203b2012-02-15 15:00:46 -08001399
Kenny Root07438c82012-11-02 15:41:02 -07001400 *item = (uint8_t*) malloc(keyBlob.getLength());
1401 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1402 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001403
Kenny Root07438c82012-11-02 15:41:02 -07001404 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001405 }
1406
Kenny Root0c540aa2013-04-03 09:22:15 -07001407 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1408 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001409 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1410 if (!has_permission(callingUid, P_INSERT)) {
1411 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001412 return ::PERMISSION_DENIED;
1413 }
Kenny Root07438c82012-11-02 15:41:02 -07001414
Kenny Root0c540aa2013-04-03 09:22:15 -07001415 State state = mKeyStore->getState(callingUid);
1416 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1417 ALOGD("calling get in state: %d", state);
1418 return state;
1419 }
1420
Kenny Root49468902013-03-19 13:41:33 -07001421 if (targetUid == -1) {
1422 targetUid = callingUid;
1423 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001424 return ::PERMISSION_DENIED;
1425 }
1426
Kenny Root07438c82012-11-02 15:41:02 -07001427 String8 name8(name);
Kenny Root68b46312013-04-04 08:37:42 -07001428 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001429
1430 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Root68b46312013-04-04 08:37:42 -07001431 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001432 }
1433
Kenny Root49468902013-03-19 13:41:33 -07001434 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001435 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1436 if (!has_permission(callingUid, P_DELETE)) {
1437 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001438 return ::PERMISSION_DENIED;
1439 }
Kenny Root70e3a862012-02-15 17:20:23 -08001440
Kenny Root49468902013-03-19 13:41:33 -07001441 if (targetUid == -1) {
1442 targetUid = callingUid;
1443 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001444 return ::PERMISSION_DENIED;
1445 }
1446
Kenny Root07438c82012-11-02 15:41:02 -07001447 String8 name8(name);
Kenny Root68b46312013-04-04 08:37:42 -07001448 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001449
1450 Blob keyBlob;
Kenny Root68b46312013-04-04 08:37:42 -07001451 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
1452 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001453 if (responseCode != ::NO_ERROR) {
1454 return responseCode;
1455 }
1456 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001457 }
1458
Kenny Root49468902013-03-19 13:41:33 -07001459 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001460 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1461 if (!has_permission(callingUid, P_EXIST)) {
1462 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001463 return ::PERMISSION_DENIED;
1464 }
Kenny Root70e3a862012-02-15 17:20:23 -08001465
Kenny Root49468902013-03-19 13:41:33 -07001466 if (targetUid == -1) {
1467 targetUid = callingUid;
1468 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001469 return ::PERMISSION_DENIED;
1470 }
1471
Kenny Root07438c82012-11-02 15:41:02 -07001472 String8 name8(name);
Kenny Root68b46312013-04-04 08:37:42 -07001473 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001474
Kenny Root68b46312013-04-04 08:37:42 -07001475 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001476 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1477 }
1478 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001479 }
1480
Kenny Root49468902013-03-19 13:41:33 -07001481 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001482 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1483 if (!has_permission(callingUid, P_SAW)) {
1484 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001485 return ::PERMISSION_DENIED;
1486 }
Kenny Root70e3a862012-02-15 17:20:23 -08001487
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 Root68b46312013-04-04 08:37:42 -07001494 UserState* userState = mKeyStore->getUserState(targetUid);
1495 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001496 if (!dir) {
Kenny Root68b46312013-04-04 08:37:42 -07001497 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001498 return ::SYSTEM_ERROR;
1499 }
Kenny Root70e3a862012-02-15 17:20:23 -08001500
Kenny Root07438c82012-11-02 15:41:02 -07001501 const String8 prefix8(prefix);
Kenny Root68b46312013-04-04 08:37:42 -07001502 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1503 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001504
Kenny Root07438c82012-11-02 15:41:02 -07001505 struct dirent* file;
1506 while ((file = readdir(dir)) != NULL) {
Kenny Root68b46312013-04-04 08:37:42 -07001507 // We only care about files.
1508 if (file->d_type != DT_REG) {
1509 continue;
1510 }
1511
1512 // Skip anything that starts with a "."
1513 if (file->d_name[0] == '.') {
1514 continue;
1515 }
1516
1517 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001518 const char* p = &file->d_name[n];
1519 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001520
Kenny Root07438c82012-11-02 15:41:02 -07001521 size_t extra = decode_key_length(p, plen);
1522 char *match = (char*) malloc(extra + 1);
1523 if (match != NULL) {
1524 decode_key(match, p, plen);
1525 matches->push(String16(match, extra));
1526 free(match);
1527 } else {
1528 ALOGW("could not allocate match of size %zd", extra);
1529 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001530 }
1531 }
Kenny Root07438c82012-11-02 15:41:02 -07001532 closedir(dir);
1533
1534 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001535 }
1536
Kenny Root07438c82012-11-02 15:41:02 -07001537 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001538 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1539 if (!has_permission(callingUid, P_RESET)) {
1540 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001541 return ::PERMISSION_DENIED;
1542 }
1543
Kenny Root68b46312013-04-04 08:37:42 -07001544 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001545
1546 const keymaster_device_t* device = mKeyStore->getDevice();
1547 if (device == NULL) {
1548 ALOGE("No keymaster device!");
1549 return ::SYSTEM_ERROR;
1550 }
1551
1552 if (device->delete_all == NULL) {
1553 ALOGV("keymaster device doesn't implement delete_all");
1554 return rc;
1555 }
1556
1557 if (device->delete_all(device)) {
1558 ALOGE("Problem calling keymaster's delete_all");
1559 return ::SYSTEM_ERROR;
1560 }
1561
Kenny Root9a53d3e2012-08-14 10:47:54 -07001562 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001563 }
1564
Kenny Root07438c82012-11-02 15:41:02 -07001565 /*
1566 * Here is the history. To improve the security, the parameters to generate the
1567 * master key has been changed. To make a seamless transition, we update the
1568 * file using the same password when the user unlock it for the first time. If
1569 * any thing goes wrong during the transition, the new file will not overwrite
1570 * the old one. This avoids permanent damages of the existing data.
1571 */
1572 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001573 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1574 if (!has_permission(callingUid, P_PASSWORD)) {
1575 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001576 return ::PERMISSION_DENIED;
1577 }
Kenny Root70e3a862012-02-15 17:20:23 -08001578
Kenny Root07438c82012-11-02 15:41:02 -07001579 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001580
Kenny Root68b46312013-04-04 08:37:42 -07001581 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001582 case ::STATE_UNINITIALIZED: {
1583 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root68b46312013-04-04 08:37:42 -07001584 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001585 }
1586 case ::STATE_NO_ERROR: {
1587 // rewrite master key with new password.
Kenny Root68b46312013-04-04 08:37:42 -07001588 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001589 }
1590 case ::STATE_LOCKED: {
1591 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root68b46312013-04-04 08:37:42 -07001592 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001593 }
1594 }
1595 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001596 }
1597
Kenny Root07438c82012-11-02 15:41:02 -07001598 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001599 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1600 if (!has_permission(callingUid, P_LOCK)) {
1601 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001602 return ::PERMISSION_DENIED;
1603 }
Kenny Root70e3a862012-02-15 17:20:23 -08001604
Kenny Root68b46312013-04-04 08:37:42 -07001605 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001606 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001607 ALOGD("calling lock in state: %d", state);
1608 return state;
1609 }
1610
Kenny Root68b46312013-04-04 08:37:42 -07001611 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001612 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001613 }
1614
Kenny Root07438c82012-11-02 15:41:02 -07001615 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001616 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1617 if (!has_permission(callingUid, P_UNLOCK)) {
1618 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001619 return ::PERMISSION_DENIED;
1620 }
1621
Kenny Root68b46312013-04-04 08:37:42 -07001622 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001623 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001624 ALOGD("calling unlock when not locked");
1625 return state;
1626 }
1627
1628 const String8 password8(pw);
1629 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001630 }
1631
Kenny Root07438c82012-11-02 15:41:02 -07001632 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001633 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1634 if (!has_permission(callingUid, P_ZERO)) {
1635 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001636 return -1;
1637 }
Kenny Root70e3a862012-02-15 17:20:23 -08001638
Kenny Root68b46312013-04-04 08:37:42 -07001639 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001640 }
1641
Kenny Root0c540aa2013-04-03 09:22:15 -07001642 int32_t generate(const String16& name, int targetUid, int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001643 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1644 if (!has_permission(callingUid, P_INSERT)) {
1645 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001646 return ::PERMISSION_DENIED;
1647 }
Kenny Root70e3a862012-02-15 17:20:23 -08001648
Kenny Root49468902013-03-19 13:41:33 -07001649 if (targetUid == -1) {
1650 targetUid = callingUid;
1651 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001652 return ::PERMISSION_DENIED;
1653 }
1654
Kenny Root68b46312013-04-04 08:37:42 -07001655 State state = mKeyStore->getState(callingUid);
Kenny Root0c540aa2013-04-03 09:22:15 -07001656 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1657 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001658 return state;
1659 }
Kenny Root70e3a862012-02-15 17:20:23 -08001660
Kenny Root07438c82012-11-02 15:41:02 -07001661 uint8_t* data;
1662 size_t dataLength;
1663 int rc;
1664
1665 const keymaster_device_t* device = mKeyStore->getDevice();
1666 if (device == NULL) {
1667 return ::SYSTEM_ERROR;
1668 }
1669
1670 if (device->generate_keypair == NULL) {
1671 return ::SYSTEM_ERROR;
1672 }
1673
1674 keymaster_rsa_keygen_params_t rsa_params;
1675 rsa_params.modulus_size = 2048;
1676 rsa_params.public_exponent = 0x10001;
1677
1678 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1679 if (rc) {
1680 return ::SYSTEM_ERROR;
1681 }
1682
Kenny Root68b46312013-04-04 08:37:42 -07001683 String8 name8(name);
1684 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001685
1686 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1687 free(data);
1688
Kenny Root68b46312013-04-04 08:37:42 -07001689 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001690 }
1691
Kenny Root0c540aa2013-04-03 09:22:15 -07001692 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1693 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001694 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1695 if (!has_permission(callingUid, P_INSERT)) {
1696 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001697 return ::PERMISSION_DENIED;
1698 }
Kenny Root07438c82012-11-02 15:41:02 -07001699
Kenny Root49468902013-03-19 13:41:33 -07001700 if (targetUid == -1) {
1701 targetUid = callingUid;
1702 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001703 return ::PERMISSION_DENIED;
1704 }
1705
Kenny Root68b46312013-04-04 08:37:42 -07001706 State state = mKeyStore->getState(callingUid);
Kenny Root0c540aa2013-04-03 09:22:15 -07001707 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001708 ALOGD("calling import in state: %d", state);
1709 return state;
1710 }
1711
1712 String8 name8(name);
Kenny Root360f51f2013-04-16 18:08:03 -07001713 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001714
Kenny Root0c540aa2013-04-03 09:22:15 -07001715 return mKeyStore->importKey(data, length, filename.string(), callingUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001716 }
1717
Kenny Root07438c82012-11-02 15:41:02 -07001718 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1719 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001720 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1721 if (!has_permission(callingUid, P_SIGN)) {
1722 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001723 return ::PERMISSION_DENIED;
1724 }
Kenny Root07438c82012-11-02 15:41:02 -07001725
Kenny Root07438c82012-11-02 15:41:02 -07001726 Blob keyBlob;
1727 String8 name8(name);
1728
Kenny Rootd38a0b02013-02-13 12:59:14 -08001729 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001730 int rc;
1731
Kenny Root68b46312013-04-04 08:37:42 -07001732 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001733 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001734 if (responseCode != ::NO_ERROR) {
1735 return responseCode;
1736 }
1737
1738 const keymaster_device_t* device = mKeyStore->getDevice();
1739 if (device == NULL) {
1740 ALOGE("no keymaster device; cannot sign");
1741 return ::SYSTEM_ERROR;
1742 }
1743
1744 if (device->sign_data == NULL) {
1745 ALOGE("device doesn't implement signing");
1746 return ::SYSTEM_ERROR;
1747 }
1748
1749 keymaster_rsa_sign_params_t params;
1750 params.digest_type = DIGEST_NONE;
1751 params.padding_type = PADDING_NONE;
1752
1753 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1754 data, length, out, outLength);
1755 if (rc) {
1756 ALOGW("device couldn't sign data");
1757 return ::SYSTEM_ERROR;
1758 }
1759
1760 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001761 }
1762
Kenny Root07438c82012-11-02 15:41:02 -07001763 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1764 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001765 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1766 if (!has_permission(callingUid, P_VERIFY)) {
1767 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001768 return ::PERMISSION_DENIED;
1769 }
Kenny Root70e3a862012-02-15 17:20:23 -08001770
Kenny Root68b46312013-04-04 08:37:42 -07001771 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001772 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001773 ALOGD("calling verify in state: %d", state);
1774 return state;
1775 }
Kenny Root70e3a862012-02-15 17:20:23 -08001776
Kenny Root07438c82012-11-02 15:41:02 -07001777 Blob keyBlob;
1778 String8 name8(name);
1779 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001780
Kenny Root68b46312013-04-04 08:37:42 -07001781 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001782 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001783 if (responseCode != ::NO_ERROR) {
1784 return responseCode;
1785 }
Kenny Root70e3a862012-02-15 17:20:23 -08001786
Kenny Root07438c82012-11-02 15:41:02 -07001787 const keymaster_device_t* device = mKeyStore->getDevice();
1788 if (device == NULL) {
1789 return ::SYSTEM_ERROR;
1790 }
Kenny Root70e3a862012-02-15 17:20:23 -08001791
Kenny Root07438c82012-11-02 15:41:02 -07001792 if (device->verify_data == NULL) {
1793 return ::SYSTEM_ERROR;
1794 }
Kenny Root70e3a862012-02-15 17:20:23 -08001795
Kenny Root07438c82012-11-02 15:41:02 -07001796 keymaster_rsa_sign_params_t params;
1797 params.digest_type = DIGEST_NONE;
1798 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001799
Kenny Root07438c82012-11-02 15:41:02 -07001800 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1801 data, dataLength, signature, signatureLength);
1802 if (rc) {
1803 return ::SYSTEM_ERROR;
1804 } else {
1805 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001806 }
1807 }
Kenny Root07438c82012-11-02 15:41:02 -07001808
1809 /*
1810 * TODO: The abstraction between things stored in hardware and regular blobs
1811 * of data stored on the filesystem should be moved down to keystore itself.
1812 * Unfortunately the Java code that calls this has naming conventions that it
1813 * knows about. Ideally keystore shouldn't be used to store random blobs of
1814 * data.
1815 *
1816 * Until that happens, it's necessary to have a separate "get_pubkey" and
1817 * "del_key" since the Java code doesn't really communicate what it's
1818 * intentions are.
1819 */
1820 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001821 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1822 if (!has_permission(callingUid, P_GET)) {
1823 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001824 return ::PERMISSION_DENIED;
1825 }
Kenny Root07438c82012-11-02 15:41:02 -07001826
Kenny Root07438c82012-11-02 15:41:02 -07001827 Blob keyBlob;
1828 String8 name8(name);
1829
Kenny Rootd38a0b02013-02-13 12:59:14 -08001830 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001831
Kenny Root68b46312013-04-04 08:37:42 -07001832 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07001833 TYPE_KEY_PAIR);
1834 if (responseCode != ::NO_ERROR) {
1835 return responseCode;
1836 }
1837
1838 const keymaster_device_t* device = mKeyStore->getDevice();
1839 if (device == NULL) {
1840 return ::SYSTEM_ERROR;
1841 }
1842
1843 if (device->get_keypair_public == NULL) {
1844 ALOGE("device has no get_keypair_public implementation!");
1845 return ::SYSTEM_ERROR;
1846 }
1847
1848 int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
1849 pubkeyLength);
1850 if (rc) {
1851 return ::SYSTEM_ERROR;
1852 }
1853
1854 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001855 }
Kenny Root07438c82012-11-02 15:41:02 -07001856
Kenny Root49468902013-03-19 13:41:33 -07001857 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001858 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1859 if (!has_permission(callingUid, P_DELETE)) {
1860 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001861 return ::PERMISSION_DENIED;
1862 }
Kenny Root07438c82012-11-02 15:41:02 -07001863
Kenny Root49468902013-03-19 13:41:33 -07001864 if (targetUid == -1) {
1865 targetUid = callingUid;
1866 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001867 return ::PERMISSION_DENIED;
1868 }
1869
Kenny Root07438c82012-11-02 15:41:02 -07001870 String8 name8(name);
Kenny Root68b46312013-04-04 08:37:42 -07001871 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001872
1873 Blob keyBlob;
Kenny Root68b46312013-04-04 08:37:42 -07001874 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
1875 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001876 if (responseCode != ::NO_ERROR) {
1877 return responseCode;
1878 }
1879
1880 ResponseCode rc = ::NO_ERROR;
1881
1882 const keymaster_device_t* device = mKeyStore->getDevice();
1883 if (device == NULL) {
1884 rc = ::SYSTEM_ERROR;
1885 } else {
1886 // A device doesn't have to implement delete_keypair.
1887 if (device->delete_keypair != NULL) {
1888 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1889 rc = ::SYSTEM_ERROR;
1890 }
1891 }
1892 }
1893
1894 if (rc != ::NO_ERROR) {
1895 return rc;
1896 }
1897
1898 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1899 }
1900
1901 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001902 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1903 if (!has_permission(callingUid, P_GRANT)) {
1904 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001905 return ::PERMISSION_DENIED;
1906 }
Kenny Root07438c82012-11-02 15:41:02 -07001907
Kenny Root68b46312013-04-04 08:37:42 -07001908 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001909 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001910 ALOGD("calling grant in state: %d", state);
1911 return state;
1912 }
1913
1914 String8 name8(name);
Kenny Root68b46312013-04-04 08:37:42 -07001915 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001916
Kenny Root68b46312013-04-04 08:37:42 -07001917 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001918 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1919 }
1920
Kenny Root68b46312013-04-04 08:37:42 -07001921 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07001922 return ::NO_ERROR;
1923 }
1924
1925 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001926 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1927 if (!has_permission(callingUid, P_GRANT)) {
1928 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001929 return ::PERMISSION_DENIED;
1930 }
Kenny Root07438c82012-11-02 15:41:02 -07001931
Kenny Root68b46312013-04-04 08:37:42 -07001932 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001933 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001934 ALOGD("calling ungrant in state: %d", state);
1935 return state;
1936 }
1937
1938 String8 name8(name);
Kenny Root68b46312013-04-04 08:37:42 -07001939 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001940
Kenny Root68b46312013-04-04 08:37:42 -07001941 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001942 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1943 }
1944
Kenny Root68b46312013-04-04 08:37:42 -07001945 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07001946 }
1947
1948 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001949 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1950 if (!has_permission(callingUid, P_GET)) {
1951 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08001952 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001953 }
Kenny Root07438c82012-11-02 15:41:02 -07001954
1955 String8 name8(name);
Kenny Root68b46312013-04-04 08:37:42 -07001956 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001957
Kenny Root68b46312013-04-04 08:37:42 -07001958 if (access(filename.string(), R_OK) == -1) {
1959 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08001960 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001961 }
1962
Kenny Root68b46312013-04-04 08:37:42 -07001963 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07001964 if (fd < 0) {
Kenny Root68b46312013-04-04 08:37:42 -07001965 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08001966 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001967 }
1968
1969 struct stat s;
1970 int ret = fstat(fd, &s);
1971 close(fd);
1972 if (ret == -1) {
Kenny Root68b46312013-04-04 08:37:42 -07001973 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08001974 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001975 }
1976
Kenny Root36a9e232013-02-04 14:24:15 -08001977 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07001978 }
1979
Kenny Rootd53bc922013-03-21 14:10:15 -07001980 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
1981 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07001982 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Rootd53bc922013-03-21 14:10:15 -07001983 if (!has_permission(callingUid, P_DUPLICATE)) {
1984 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07001985 return -1L;
1986 }
1987
Kenny Root68b46312013-04-04 08:37:42 -07001988 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07001989 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07001990 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07001991 return state;
1992 }
1993
Kenny Rootd53bc922013-03-21 14:10:15 -07001994 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
1995 srcUid = callingUid;
1996 } else if (!is_granted_to(callingUid, srcUid)) {
1997 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07001998 return ::PERMISSION_DENIED;
1999 }
2000
Kenny Rootd53bc922013-03-21 14:10:15 -07002001 if (destUid == -1) {
2002 destUid = callingUid;
2003 }
2004
2005 if (srcUid != destUid) {
2006 if (static_cast<uid_t>(srcUid) != callingUid) {
2007 ALOGD("can only duplicate from caller to other or to same uid: "
2008 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2009 return ::PERMISSION_DENIED;
2010 }
2011
2012 if (!is_granted_to(callingUid, destUid)) {
2013 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2014 return ::PERMISSION_DENIED;
2015 }
2016 }
2017
2018 String8 source8(srcKey);
Kenny Root68b46312013-04-04 08:37:42 -07002019 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002020
Kenny Rootd53bc922013-03-21 14:10:15 -07002021 String8 target8(destKey);
Kenny Root68b46312013-04-04 08:37:42 -07002022 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002023
Kenny Root68b46312013-04-04 08:37:42 -07002024 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2025 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002026 return ::SYSTEM_ERROR;
2027 }
2028
Kenny Rootd53bc922013-03-21 14:10:15 -07002029 Blob keyBlob;
Kenny Root68b46312013-04-04 08:37:42 -07002030 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
2031 callingUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002032 if (responseCode != ::NO_ERROR) {
2033 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002034 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002035
Kenny Root68b46312013-04-04 08:37:42 -07002036 return mKeyStore->put(targetFile.string(), &keyBlob, callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002037 }
2038
Kenny Root43061232013-03-29 11:15:50 -07002039 int32_t is_hardware_backed() {
2040 return mKeyStore->isHardwareBacked() ? 1 : 0;
2041 }
2042
Kenny Root2ecc7a12013-04-01 16:29:11 -07002043 int32_t clear_uid(int64_t targetUid) {
2044 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2045 if (!has_permission(callingUid, P_CLEAR_UID)) {
2046 ALOGW("permission denied for %d: clear_uid", callingUid);
2047 return ::PERMISSION_DENIED;
2048 }
2049
Kenny Root68b46312013-04-04 08:37:42 -07002050 State state = mKeyStore->getState(callingUid);
Kenny Root2ecc7a12013-04-01 16:29:11 -07002051 if (!isKeystoreUnlocked(state)) {
2052 ALOGD("calling clear_uid in state: %d", state);
2053 return state;
2054 }
2055
2056 const keymaster_device_t* device = mKeyStore->getDevice();
2057 if (device == NULL) {
Kenny Root68b46312013-04-04 08:37:42 -07002058 ALOGW("can't get keymaster device");
Kenny Root2ecc7a12013-04-01 16:29:11 -07002059 return ::SYSTEM_ERROR;
2060 }
2061
Kenny Root68b46312013-04-04 08:37:42 -07002062 UserState* userState = mKeyStore->getUserState(callingUid);
2063 DIR* dir = opendir(userState->getUserDirName());
Kenny Root2ecc7a12013-04-01 16:29:11 -07002064 if (!dir) {
Kenny Root68b46312013-04-04 08:37:42 -07002065 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Root2ecc7a12013-04-01 16:29:11 -07002066 return ::SYSTEM_ERROR;
2067 }
2068
Kenny Root68b46312013-04-04 08:37:42 -07002069 char prefix[NAME_MAX];
2070 int n = snprintf(prefix, NAME_MAX, "%u_", static_cast<uid_t>(targetUid));
Kenny Root2ecc7a12013-04-01 16:29:11 -07002071
2072 ResponseCode rc = ::NO_ERROR;
2073
2074 struct dirent* file;
2075 while ((file = readdir(dir)) != NULL) {
Kenny Root68b46312013-04-04 08:37:42 -07002076 // We only care about files.
2077 if (file->d_type != DT_REG) {
Kenny Root2ecc7a12013-04-01 16:29:11 -07002078 continue;
2079 }
2080
Kenny Root68b46312013-04-04 08:37:42 -07002081 // Skip anything that starts with a "."
2082 if (file->d_name[0] == '.') {
2083 continue;
2084 }
Kenny Root2ecc7a12013-04-01 16:29:11 -07002085
Kenny Root68b46312013-04-04 08:37:42 -07002086 if (strncmp(prefix, file->d_name, n)) {
2087 continue;
2088 }
2089
2090 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Root2ecc7a12013-04-01 16:29:11 -07002091 Blob keyBlob;
Kenny Root68b46312013-04-04 08:37:42 -07002092 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, callingUid)
2093 != ::NO_ERROR) {
2094 ALOGW("couldn't open %s", filename.string());
Kenny Root2ecc7a12013-04-01 16:29:11 -07002095 continue;
2096 }
2097
2098 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2099 // A device doesn't have to implement delete_keypair.
2100 if (device->delete_keypair != NULL) {
2101 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2102 rc = ::SYSTEM_ERROR;
Kenny Root68b46312013-04-04 08:37:42 -07002103 ALOGW("device couldn't remove %s", filename.string());
Kenny Root2ecc7a12013-04-01 16:29:11 -07002104 }
2105 }
2106 }
2107
Kenny Rootaae26fc2013-04-12 11:31:50 -07002108 if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
Kenny Root2ecc7a12013-04-01 16:29:11 -07002109 rc = ::SYSTEM_ERROR;
Kenny Root68b46312013-04-04 08:37:42 -07002110 ALOGW("couldn't unlink %s", filename.string());
Kenny Root2ecc7a12013-04-01 16:29:11 -07002111 }
2112 }
2113 closedir(dir);
2114
2115 return rc;
2116 }
2117
Kenny Root07438c82012-11-02 15:41:02 -07002118private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002119 inline bool isKeystoreUnlocked(State state) {
2120 switch (state) {
2121 case ::STATE_NO_ERROR:
2122 return true;
2123 case ::STATE_UNINITIALIZED:
2124 case ::STATE_LOCKED:
2125 return false;
2126 }
2127 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002128 }
2129
2130 ::KeyStore* mKeyStore;
2131};
2132
2133}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002134
2135int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002136 if (argc < 2) {
2137 ALOGE("A directory must be specified!");
2138 return 1;
2139 }
2140 if (chdir(argv[1]) == -1) {
2141 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2142 return 1;
2143 }
2144
2145 Entropy entropy;
2146 if (!entropy.open()) {
2147 return 1;
2148 }
Kenny Root70e3a862012-02-15 17:20:23 -08002149
2150 keymaster_device_t* dev;
2151 if (keymaster_device_initialize(&dev)) {
2152 ALOGE("keystore keymaster could not be initialized; exiting");
2153 return 1;
2154 }
2155
Kenny Root70e3a862012-02-15 17:20:23 -08002156 KeyStore keyStore(&entropy, dev);
Kenny Root68b46312013-04-04 08:37:42 -07002157 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002158 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2159 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2160 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2161 if (ret != android::OK) {
2162 ALOGE("Couldn't register binder service!");
2163 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002164 }
Kenny Root07438c82012-11-02 15:41:02 -07002165
2166 /*
2167 * We're the only thread in existence, so we're just going to process
2168 * Binder transaction as a single-threaded program.
2169 */
2170 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002171
2172 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002173 return 1;
2174}