blob: 5729dbdc5e7ce372746fe481393984eaaa122a4b [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 Root655b9582013-04-04 08:37:42 -070045#include <utils/String8.h>
Kenny Root822c3a92012-03-23 16:34:39 -070046#include <utils/UniquePtr.h>
Kenny Root655b9582013-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 Roota9bb5492013-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 Root655b9582013-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 Root655b9582013-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 Root655b9582013-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 Root655b9582013-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 Root655b9582013-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 -0700264static int encode_key_for_uid(char* out, uid_t uid, const android::String8& keyName) {
Kenny Root70e3a862012-02-15 17:20:23 -0800265 int n = snprintf(out, NAME_MAX, "%u_", uid);
266 out += n;
267
Kenny Root07438c82012-11-02 15:41:02 -0700268 return n + encode_key(out, keyName);
Kenny Roota91203b2012-02-15 15:00:46 -0800269}
270
Kenny Root07438c82012-11-02 15:41:02 -0700271/*
272 * Converts from the "escaped" format on disk to actual name.
273 * This will be smaller than the input string.
274 *
275 * Characters that should combine with the next at the end will be truncated.
276 */
277static size_t decode_key_length(const char* in, size_t length) {
278 size_t outLength = 0;
279
280 for (const char* end = in + length; in < end; in++) {
281 /* This combines with the next character. */
282 if (*in < '0' || *in > '~') {
283 continue;
284 }
285
286 outLength++;
287 }
288 return outLength;
289}
290
291static void decode_key(char* out, const char* in, size_t length) {
292 for (const char* end = in + length; in < end; in++) {
293 if (*in < '0' || *in > '~') {
294 /* Truncate combining characters at the end. */
295 if (in + 1 >= end) {
296 break;
297 }
298
299 *out = (*in++ - '+') << 6;
300 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800301 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700302 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800303 }
304 }
305 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800306}
307
308static size_t readFully(int fd, uint8_t* data, size_t size) {
309 size_t remaining = size;
310 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800311 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800312 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800313 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800314 }
315 data += n;
316 remaining -= n;
317 }
318 return size;
319}
320
321static size_t writeFully(int fd, uint8_t* data, size_t size) {
322 size_t remaining = size;
323 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800324 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
325 if (n < 0) {
326 ALOGW("write failed: %s", strerror(errno));
327 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800328 }
329 data += n;
330 remaining -= n;
331 }
332 return size;
333}
334
335class Entropy {
336public:
337 Entropy() : mRandom(-1) {}
338 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800339 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800340 close(mRandom);
341 }
342 }
343
344 bool open() {
345 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800346 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
347 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800348 ALOGE("open: %s: %s", randomDevice, strerror(errno));
349 return false;
350 }
351 return true;
352 }
353
Kenny Root51878182012-03-13 12:53:19 -0700354 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800355 return (readFully(mRandom, data, size) == size);
356 }
357
358private:
359 int mRandom;
360};
361
362/* Here is the file format. There are two parts in blob.value, the secret and
363 * the description. The secret is stored in ciphertext, and its original size
364 * can be found in blob.length. The description is stored after the secret in
365 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700366 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700367 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800368 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
369 * and decryptBlob(). Thus they should not be accessed from outside. */
370
Kenny Root822c3a92012-03-23 16:34:39 -0700371/* ** Note to future implementors of encryption: **
372 * Currently this is the construction:
373 * metadata || Enc(MD5(data) || data)
374 *
375 * This should be the construction used for encrypting if re-implementing:
376 *
377 * Derive independent keys for encryption and MAC:
378 * Kenc = AES_encrypt(masterKey, "Encrypt")
379 * Kmac = AES_encrypt(masterKey, "MAC")
380 *
381 * Store this:
382 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
383 * HMAC(Kmac, metadata || Enc(data))
384 */
Kenny Roota91203b2012-02-15 15:00:46 -0800385struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700386 uint8_t version;
387 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700388 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800389 uint8_t info;
390 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700391 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800392 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700393 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800394 int32_t length; // in network byte order when encrypted
395 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
396};
397
Kenny Root822c3a92012-03-23 16:34:39 -0700398typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700399 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700400 TYPE_GENERIC = 1,
401 TYPE_MASTER_KEY = 2,
402 TYPE_KEY_PAIR = 3,
403} BlobType;
404
Kenny Rootf9119d62013-04-03 09:22:15 -0700405static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700406
Kenny Roota91203b2012-02-15 15:00:46 -0800407class Blob {
408public:
Kenny Root07438c82012-11-02 15:41:02 -0700409 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
410 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800411 mBlob.length = valueLength;
412 memcpy(mBlob.value, value, valueLength);
413
414 mBlob.info = infoLength;
415 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700416
Kenny Root07438c82012-11-02 15:41:02 -0700417 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700418 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700419
420 mBlob.flags = KEYSTORE_FLAG_NONE;
Kenny Roota91203b2012-02-15 15:00:46 -0800421 }
422
423 Blob(blob b) {
424 mBlob = b;
425 }
426
427 Blob() {}
428
Kenny Root51878182012-03-13 12:53:19 -0700429 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800430 return mBlob.value;
431 }
432
Kenny Root51878182012-03-13 12:53:19 -0700433 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800434 return mBlob.length;
435 }
436
Kenny Root51878182012-03-13 12:53:19 -0700437 const uint8_t* getInfo() const {
438 return mBlob.value + mBlob.length;
439 }
440
441 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800442 return mBlob.info;
443 }
444
Kenny Root822c3a92012-03-23 16:34:39 -0700445 uint8_t getVersion() const {
446 return mBlob.version;
447 }
448
Kenny Rootf9119d62013-04-03 09:22:15 -0700449 bool isEncrypted() const {
450 if (mBlob.version < 2) {
451 return true;
452 }
453
454 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
455 }
456
457 void setEncrypted(bool encrypted) {
458 if (encrypted) {
459 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
460 } else {
461 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
462 }
463 }
464
Kenny Root822c3a92012-03-23 16:34:39 -0700465 void setVersion(uint8_t version) {
466 mBlob.version = version;
467 }
468
469 BlobType getType() const {
470 return BlobType(mBlob.type);
471 }
472
473 void setType(BlobType type) {
474 mBlob.type = uint8_t(type);
475 }
476
Kenny Rootf9119d62013-04-03 09:22:15 -0700477 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
478 ALOGV("writing blob %s", filename);
479 if (isEncrypted()) {
480 if (state != STATE_NO_ERROR) {
481 ALOGD("couldn't insert encrypted blob while not unlocked");
482 return LOCKED;
483 }
484
485 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
486 ALOGW("Could not read random data for: %s", filename);
487 return SYSTEM_ERROR;
488 }
Kenny Roota91203b2012-02-15 15:00:46 -0800489 }
490
491 // data includes the value and the value's length
492 size_t dataLength = mBlob.length + sizeof(mBlob.length);
493 // pad data to the AES_BLOCK_SIZE
494 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
495 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
496 // encrypted data includes the digest value
497 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
498 // move info after space for padding
499 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
500 // zero padding area
501 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
502
503 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800504
Kenny Rootf9119d62013-04-03 09:22:15 -0700505 if (isEncrypted()) {
506 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800507
Kenny Rootf9119d62013-04-03 09:22:15 -0700508 uint8_t vector[AES_BLOCK_SIZE];
509 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
510 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
511 aes_key, vector, AES_ENCRYPT);
512 }
513
Kenny Roota91203b2012-02-15 15:00:46 -0800514 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
515 size_t fileLength = encryptedLength + headerLength + mBlob.info;
516
517 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800518 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
519 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
520 if (out < 0) {
521 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800522 return SYSTEM_ERROR;
523 }
524 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
525 if (close(out) != 0) {
526 return SYSTEM_ERROR;
527 }
528 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800529 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800530 unlink(tmpFileName);
531 return SYSTEM_ERROR;
532 }
Kenny Root150ca932012-11-14 14:29:02 -0800533 if (rename(tmpFileName, filename) == -1) {
534 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
535 return SYSTEM_ERROR;
536 }
537 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800538 }
539
Kenny Rootf9119d62013-04-03 09:22:15 -0700540 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
541 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800542 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
543 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800544 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
545 }
546 // fileLength may be less than sizeof(mBlob) since the in
547 // memory version has extra padding to tolerate rounding up to
548 // the AES_BLOCK_SIZE
549 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
550 if (close(in) != 0) {
551 return SYSTEM_ERROR;
552 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700553
554 if (isEncrypted() && (state != STATE_NO_ERROR)) {
555 return LOCKED;
556 }
557
Kenny Roota91203b2012-02-15 15:00:46 -0800558 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
559 if (fileLength < headerLength) {
560 return VALUE_CORRUPTED;
561 }
562
563 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700564 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800565 return VALUE_CORRUPTED;
566 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700567
568 ssize_t digestedLength;
569 if (isEncrypted()) {
570 if (encryptedLength % AES_BLOCK_SIZE != 0) {
571 return VALUE_CORRUPTED;
572 }
573
574 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
575 mBlob.vector, AES_DECRYPT);
576 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
577 uint8_t computedDigest[MD5_DIGEST_LENGTH];
578 MD5(mBlob.digested, digestedLength, computedDigest);
579 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
580 return VALUE_CORRUPTED;
581 }
582 } else {
583 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800584 }
585
586 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
587 mBlob.length = ntohl(mBlob.length);
588 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
589 return VALUE_CORRUPTED;
590 }
591 if (mBlob.info != 0) {
592 // move info from after padding to after data
593 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
594 }
Kenny Root07438c82012-11-02 15:41:02 -0700595 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800596 }
597
598private:
599 struct blob mBlob;
600};
601
Kenny Root655b9582013-04-04 08:37:42 -0700602class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800603public:
Kenny Root655b9582013-04-04 08:37:42 -0700604 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
605 asprintf(&mUserDir, "user_%u", mUserId);
606 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
607 }
608
609 ~UserState() {
610 free(mUserDir);
611 free(mMasterKeyFile);
612 }
613
614 bool initialize() {
615 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
616 ALOGE("Could not create directory '%s'", mUserDir);
617 return false;
618 }
619
620 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800621 setState(STATE_LOCKED);
622 } else {
623 setState(STATE_UNINITIALIZED);
624 }
Kenny Root70e3a862012-02-15 17:20:23 -0800625
Kenny Root655b9582013-04-04 08:37:42 -0700626 return true;
627 }
628
629 uid_t getUserId() const {
630 return mUserId;
631 }
632
633 const char* getUserDirName() const {
634 return mUserDir;
635 }
636
637 const char* getMasterKeyFileName() const {
638 return mMasterKeyFile;
639 }
640
641 void setState(State state) {
642 mState = state;
643 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
644 mRetry = MAX_RETRY;
645 }
Kenny Roota91203b2012-02-15 15:00:46 -0800646 }
647
Kenny Root51878182012-03-13 12:53:19 -0700648 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800649 return mState;
650 }
651
Kenny Root51878182012-03-13 12:53:19 -0700652 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800653 return mRetry;
654 }
655
Kenny Root655b9582013-04-04 08:37:42 -0700656 void zeroizeMasterKeysInMemory() {
657 memset(mMasterKey, 0, sizeof(mMasterKey));
658 memset(mSalt, 0, sizeof(mSalt));
659 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
660 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800661 }
662
Kenny Root655b9582013-04-04 08:37:42 -0700663 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
664 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800665 return SYSTEM_ERROR;
666 }
Kenny Root655b9582013-04-04 08:37:42 -0700667 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800668 if (response != NO_ERROR) {
669 return response;
670 }
671 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700672 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800673 }
674
Kenny Root655b9582013-04-04 08:37:42 -0700675 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800676 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
677 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
678 AES_KEY passwordAesKey;
679 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700680 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700681 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800682 }
683
Kenny Root655b9582013-04-04 08:37:42 -0700684 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
685 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800686 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800687 return SYSTEM_ERROR;
688 }
689
690 // we read the raw blob to just to get the salt to generate
691 // the AES key, then we create the Blob to use with decryptBlob
692 blob rawBlob;
693 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
694 if (close(in) != 0) {
695 return SYSTEM_ERROR;
696 }
697 // find salt at EOF if present, otherwise we have an old file
698 uint8_t* salt;
699 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
700 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
701 } else {
702 salt = NULL;
703 }
704 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
705 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
706 AES_KEY passwordAesKey;
707 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
708 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700709 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
710 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800711 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700712 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800713 }
714 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
715 // if salt was missing, generate one and write a new master key file with the salt.
716 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700717 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800718 return SYSTEM_ERROR;
719 }
Kenny Root655b9582013-04-04 08:37:42 -0700720 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800721 }
722 if (response == NO_ERROR) {
723 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
724 setupMasterKeys();
725 }
726 return response;
727 }
728 if (mRetry <= 0) {
729 reset();
730 return UNINITIALIZED;
731 }
732 --mRetry;
733 switch (mRetry) {
734 case 0: return WRONG_PASSWORD_0;
735 case 1: return WRONG_PASSWORD_1;
736 case 2: return WRONG_PASSWORD_2;
737 case 3: return WRONG_PASSWORD_3;
738 default: return WRONG_PASSWORD_3;
739 }
740 }
741
Kenny Root655b9582013-04-04 08:37:42 -0700742 AES_KEY* getEncryptionKey() {
743 return &mMasterKeyEncryption;
744 }
745
746 AES_KEY* getDecryptionKey() {
747 return &mMasterKeyDecryption;
748 }
749
Kenny Roota91203b2012-02-15 15:00:46 -0800750 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700751 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800752 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700753 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800754 return false;
755 }
Kenny Root655b9582013-04-04 08:37:42 -0700756
757 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800758 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700759 // We only care about files.
760 if (file->d_type != DT_REG) {
761 continue;
762 }
763
764 // Skip anything that starts with a "."
765 if (file->d_name[0] == '.') {
766 continue;
767 }
768
769 // Find the current file's UID.
770 char* end;
771 unsigned long thisUid = strtoul(file->d_name, &end, 10);
772 if (end[0] != '_' || end[1] == 0) {
773 continue;
774 }
775
776 // Skip if this is not our user.
777 if (get_user_id(thisUid) != mUserId) {
778 continue;
779 }
780
781 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800782 }
783 closedir(dir);
784 return true;
785 }
786
Kenny Root655b9582013-04-04 08:37:42 -0700787private:
788 static const int MASTER_KEY_SIZE_BYTES = 16;
789 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
790
791 static const int MAX_RETRY = 4;
792 static const size_t SALT_SIZE = 16;
793
794 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
795 uint8_t* salt) {
796 size_t saltSize;
797 if (salt != NULL) {
798 saltSize = SALT_SIZE;
799 } else {
800 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
801 salt = (uint8_t*) "keystore";
802 // sizeof = 9, not strlen = 8
803 saltSize = sizeof("keystore");
804 }
805
806 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
807 saltSize, 8192, keySize, key);
808 }
809
810 bool generateSalt(Entropy* entropy) {
811 return entropy->generate_random_data(mSalt, sizeof(mSalt));
812 }
813
814 bool generateMasterKey(Entropy* entropy) {
815 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
816 return false;
817 }
818 if (!generateSalt(entropy)) {
819 return false;
820 }
821 return true;
822 }
823
824 void setupMasterKeys() {
825 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
826 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
827 setState(STATE_NO_ERROR);
828 }
829
830 uid_t mUserId;
831
832 char* mUserDir;
833 char* mMasterKeyFile;
834
835 State mState;
836 int8_t mRetry;
837
838 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
839 uint8_t mSalt[SALT_SIZE];
840
841 AES_KEY mMasterKeyEncryption;
842 AES_KEY mMasterKeyDecryption;
843};
844
845typedef struct {
846 uint32_t uid;
847 const uint8_t* filename;
848} grant_t;
849
850class KeyStore {
851public:
852 KeyStore(Entropy* entropy, keymaster_device_t* device)
853 : mEntropy(entropy)
854 , mDevice(device)
855 {
856 memset(&mMetaData, '\0', sizeof(mMetaData));
857 }
858
859 ~KeyStore() {
860 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
861 it != mGrants.end(); it++) {
862 delete *it;
863 mGrants.erase(it);
864 }
865
866 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
867 it != mMasterKeys.end(); it++) {
868 delete *it;
869 mMasterKeys.erase(it);
870 }
871 }
872
873 keymaster_device_t* getDevice() const {
874 return mDevice;
875 }
876
877 ResponseCode initialize() {
878 readMetaData();
879 if (upgradeKeystore()) {
880 writeMetaData();
881 }
882
883 return ::NO_ERROR;
884 }
885
886 State getState(uid_t uid) {
887 return getUserState(uid)->getState();
888 }
889
890 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
891 UserState* userState = getUserState(uid);
892 return userState->initialize(pw, mEntropy);
893 }
894
895 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
896 uid_t user_id = get_user_id(uid);
897 UserState* userState = getUserState(user_id);
898 return userState->writeMasterKey(pw, mEntropy);
899 }
900
901 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
902 uid_t user_id = get_user_id(uid);
903 UserState* userState = getUserState(user_id);
904 return userState->readMasterKey(pw, mEntropy);
905 }
906
907 android::String8 getKeyName(const android::String8& keyName) {
908 char encoded[encode_key_length(keyName)];
909 encode_key(encoded, keyName);
910 return android::String8(encoded);
911 }
912
913 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
914 char encoded[encode_key_length(keyName)];
915 encode_key(encoded, keyName);
916 return android::String8::format("%u_%s", uid, encoded);
917 }
918
919 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
920 char encoded[encode_key_length(keyName)];
921 encode_key(encoded, keyName);
922 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
923 encoded);
924 }
925
926 bool reset(uid_t uid) {
927 UserState* userState = getUserState(uid);
928 userState->zeroizeMasterKeysInMemory();
929 userState->setState(STATE_UNINITIALIZED);
930 return userState->reset();
931 }
932
933 bool isEmpty(uid_t uid) const {
934 const UserState* userState = getUserState(uid);
935 if (userState == NULL) {
936 return true;
937 }
938
939 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800940 struct dirent* file;
941 if (!dir) {
942 return true;
943 }
944 bool result = true;
Kenny Root655b9582013-04-04 08:37:42 -0700945
946 char filename[NAME_MAX];
947 int n = snprintf(filename, sizeof(filename), "%u_", uid);
948
Kenny Roota91203b2012-02-15 15:00:46 -0800949 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700950 // We only care about files.
951 if (file->d_type != DT_REG) {
952 continue;
953 }
954
955 // Skip anything that starts with a "."
956 if (file->d_name[0] == '.') {
957 continue;
958 }
959
960 if (!strncmp(file->d_name, filename, n)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800961 result = false;
962 break;
963 }
964 }
965 closedir(dir);
966 return result;
967 }
968
Kenny Root655b9582013-04-04 08:37:42 -0700969 void lock(uid_t uid) {
970 UserState* userState = getUserState(uid);
971 userState->zeroizeMasterKeysInMemory();
972 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -0800973 }
974
Kenny Root655b9582013-04-04 08:37:42 -0700975 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
976 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -0700977 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
978 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -0700979 if (rc != NO_ERROR) {
980 return rc;
981 }
982
983 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -0700984 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -0700985 /* If we upgrade the key, we need to write it to disk again. Then
986 * it must be read it again since the blob is encrypted each time
987 * it's written.
988 */
Kenny Root655b9582013-04-04 08:37:42 -0700989 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
990 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -0700991 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
992 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -0700993 return rc;
994 }
995 }
Kenny Root822c3a92012-03-23 16:34:39 -0700996 }
997
Kenny Rootd53bc922013-03-21 14:10:15 -0700998 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -0700999 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1000 return KEY_NOT_FOUND;
1001 }
1002
1003 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001004 }
1005
Kenny Root655b9582013-04-04 08:37:42 -07001006 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1007 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001008 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1009 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001010 }
1011
Kenny Root07438c82012-11-02 15:41:02 -07001012 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001013 const grant_t* existing = getGrant(filename, granteeUid);
1014 if (existing == NULL) {
1015 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001016 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001017 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001018 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001019 }
1020 }
1021
Kenny Root07438c82012-11-02 15:41:02 -07001022 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001023 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1024 it != mGrants.end(); it++) {
1025 grant_t* grant = *it;
1026 if (grant->uid == granteeUid
1027 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1028 mGrants.erase(it);
1029 return true;
1030 }
Kenny Root70e3a862012-02-15 17:20:23 -08001031 }
Kenny Root70e3a862012-02-15 17:20:23 -08001032 return false;
1033 }
1034
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001035 bool hasGrant(const char* filename, const uid_t uid) const {
1036 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001037 }
1038
Kenny Rootf9119d62013-04-03 09:22:15 -07001039 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1040 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001041 uint8_t* data;
1042 size_t dataLength;
1043 int rc;
1044
1045 if (mDevice->import_keypair == NULL) {
1046 ALOGE("Keymaster doesn't support import!");
1047 return SYSTEM_ERROR;
1048 }
1049
Kenny Root07438c82012-11-02 15:41:02 -07001050 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001051 if (rc) {
1052 ALOGE("Error while importing keypair: %d", rc);
1053 return SYSTEM_ERROR;
1054 }
1055
1056 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1057 free(data);
1058
Kenny Rootf9119d62013-04-03 09:22:15 -07001059 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1060
Kenny Root655b9582013-04-04 08:37:42 -07001061 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001062 }
1063
Kenny Root8ddf35a2013-03-29 11:15:50 -07001064 bool isHardwareBacked() const {
Kenny Root483407e2013-04-04 17:12:25 -07001065 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07001066 }
1067
Kenny Root655b9582013-04-04 08:37:42 -07001068 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1069 const BlobType type) {
1070 char filename[NAME_MAX];
1071 encode_key_for_uid(filename, uid, keyName);
1072
1073 UserState* userState = getUserState(uid);
1074 android::String8 filepath8;
1075
1076 filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1077 if (filepath8.string() == NULL) {
1078 ALOGW("can't create filepath for key %s", filename);
1079 return SYSTEM_ERROR;
1080 }
1081
1082 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1083 if (responseCode == NO_ERROR) {
1084 return responseCode;
1085 }
1086
1087 // If this is one of the legacy UID->UID mappings, use it.
1088 uid_t euid = get_keystore_euid(uid);
1089 if (euid != uid) {
1090 encode_key_for_uid(filename, euid, keyName);
1091 filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1092 responseCode = get(filepath8.string(), keyBlob, type, uid);
1093 if (responseCode == NO_ERROR) {
1094 return responseCode;
1095 }
1096 }
1097
1098 // They might be using a granted key.
1099 encode_key(filename, keyName);
1100 char* end;
1101 strtoul(filename, &end, 10);
1102 if (end[0] != '_' || end[1] == 0) {
1103 return KEY_NOT_FOUND;
1104 }
1105 filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1106 if (!hasGrant(filepath8.string(), uid)) {
1107 return responseCode;
1108 }
1109
1110 // It is a granted key. Try to load it.
1111 return get(filepath8.string(), keyBlob, type, uid);
1112 }
1113
1114 /**
1115 * Returns any existing UserState or creates it if it doesn't exist.
1116 */
1117 UserState* getUserState(uid_t uid) {
1118 uid_t userId = get_user_id(uid);
1119
1120 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1121 it != mMasterKeys.end(); it++) {
1122 UserState* state = *it;
1123 if (state->getUserId() == userId) {
1124 return state;
1125 }
1126 }
1127
1128 UserState* userState = new UserState(userId);
1129 if (!userState->initialize()) {
1130 /* There's not much we can do if initialization fails. Trying to
1131 * unlock the keystore for that user will fail as well, so any
1132 * subsequent request for this user will just return SYSTEM_ERROR.
1133 */
1134 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1135 }
1136 mMasterKeys.add(userState);
1137 return userState;
1138 }
1139
1140 /**
1141 * Returns NULL if the UserState doesn't already exist.
1142 */
1143 const UserState* getUserState(uid_t uid) const {
1144 uid_t userId = get_user_id(uid);
1145
1146 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1147 it != mMasterKeys.end(); it++) {
1148 UserState* state = *it;
1149 if (state->getUserId() == userId) {
1150 return state;
1151 }
1152 }
1153
1154 return NULL;
1155 }
1156
Kenny Roota91203b2012-02-15 15:00:46 -08001157private:
Kenny Root655b9582013-04-04 08:37:42 -07001158 static const char* sOldMasterKey;
1159 static const char* sMetaDataFile;
Kenny Roota91203b2012-02-15 15:00:46 -08001160 Entropy* mEntropy;
1161
Kenny Root70e3a862012-02-15 17:20:23 -08001162 keymaster_device_t* mDevice;
1163
Kenny Root655b9582013-04-04 08:37:42 -07001164 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001165
Kenny Root655b9582013-04-04 08:37:42 -07001166 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001167
Kenny Root655b9582013-04-04 08:37:42 -07001168 typedef struct {
1169 uint32_t version;
1170 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001171
Kenny Root655b9582013-04-04 08:37:42 -07001172 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001173
Kenny Root655b9582013-04-04 08:37:42 -07001174 const grant_t* getGrant(const char* filename, uid_t uid) const {
1175 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1176 it != mGrants.end(); it++) {
1177 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001178 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001179 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001180 return grant;
1181 }
1182 }
Kenny Root70e3a862012-02-15 17:20:23 -08001183 return NULL;
1184 }
1185
Kenny Root822c3a92012-03-23 16:34:39 -07001186 /**
1187 * Upgrade code. This will upgrade the key from the current version
1188 * to whatever is newest.
1189 */
Kenny Root655b9582013-04-04 08:37:42 -07001190 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1191 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001192 bool updated = false;
1193 uint8_t version = oldVersion;
1194
1195 /* From V0 -> V1: All old types were unknown */
1196 if (version == 0) {
1197 ALOGV("upgrading to version 1 and setting type %d", type);
1198
1199 blob->setType(type);
1200 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001201 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001202 }
1203 version = 1;
1204 updated = true;
1205 }
1206
Kenny Rootf9119d62013-04-03 09:22:15 -07001207 /* From V1 -> V2: All old keys were encrypted */
1208 if (version == 1) {
1209 ALOGV("upgrading to version 2");
1210
1211 blob->setEncrypted(true);
1212 version = 2;
1213 updated = true;
1214 }
1215
Kenny Root822c3a92012-03-23 16:34:39 -07001216 /*
1217 * If we've updated, set the key blob to the right version
1218 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001219 */
Kenny Root822c3a92012-03-23 16:34:39 -07001220 if (updated) {
1221 ALOGV("updated and writing file %s", filename);
1222 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001223 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001224
1225 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001226 }
1227
1228 /**
1229 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1230 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1231 * Then it overwrites the original blob with the new blob
1232 * format that is returned from the keymaster.
1233 */
Kenny Root655b9582013-04-04 08:37:42 -07001234 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001235 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1236 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1237 if (b.get() == NULL) {
1238 ALOGE("Problem instantiating BIO");
1239 return SYSTEM_ERROR;
1240 }
1241
1242 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1243 if (pkey.get() == NULL) {
1244 ALOGE("Couldn't read old PEM file");
1245 return SYSTEM_ERROR;
1246 }
1247
1248 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1249 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1250 if (len < 0) {
1251 ALOGE("Couldn't measure PKCS#8 length");
1252 return SYSTEM_ERROR;
1253 }
1254
Kenny Root70c98892013-02-07 09:10:36 -08001255 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1256 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001257 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1258 ALOGE("Couldn't convert to PKCS#8");
1259 return SYSTEM_ERROR;
1260 }
1261
Kenny Rootf9119d62013-04-03 09:22:15 -07001262 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1263 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001264 if (rc != NO_ERROR) {
1265 return rc;
1266 }
1267
Kenny Root655b9582013-04-04 08:37:42 -07001268 return get(filename, blob, TYPE_KEY_PAIR, uid);
1269 }
1270
1271 void readMetaData() {
1272 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1273 if (in < 0) {
1274 return;
1275 }
1276 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1277 if (fileLength != sizeof(mMetaData)) {
1278 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1279 sizeof(mMetaData));
1280 }
1281 close(in);
1282 }
1283
1284 void writeMetaData() {
1285 const char* tmpFileName = ".metadata.tmp";
1286 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1287 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1288 if (out < 0) {
1289 ALOGE("couldn't write metadata file: %s", strerror(errno));
1290 return;
1291 }
1292 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1293 if (fileLength != sizeof(mMetaData)) {
1294 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1295 sizeof(mMetaData));
1296 }
1297 close(out);
1298 rename(tmpFileName, sMetaDataFile);
1299 }
1300
1301 bool upgradeKeystore() {
1302 bool upgraded = false;
1303
1304 if (mMetaData.version == 0) {
1305 UserState* userState = getUserState(0);
1306
1307 // Initialize first so the directory is made.
1308 userState->initialize();
1309
1310 // Migrate the old .masterkey file to user 0.
1311 if (access(sOldMasterKey, R_OK) == 0) {
1312 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1313 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1314 return false;
1315 }
1316 }
1317
1318 // Initialize again in case we had a key.
1319 userState->initialize();
1320
1321 // Try to migrate existing keys.
1322 DIR* dir = opendir(".");
1323 if (!dir) {
1324 // Give up now; maybe we can upgrade later.
1325 ALOGE("couldn't open keystore's directory; something is wrong");
1326 return false;
1327 }
1328
1329 struct dirent* file;
1330 while ((file = readdir(dir)) != NULL) {
1331 // We only care about files.
1332 if (file->d_type != DT_REG) {
1333 continue;
1334 }
1335
1336 // Skip anything that starts with a "."
1337 if (file->d_name[0] == '.') {
1338 continue;
1339 }
1340
1341 // Find the current file's user.
1342 char* end;
1343 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1344 if (end[0] != '_' || end[1] == 0) {
1345 continue;
1346 }
1347 UserState* otherUser = getUserState(thisUid);
1348 if (otherUser->getUserId() != 0) {
1349 unlinkat(dirfd(dir), file->d_name, 0);
1350 }
1351
1352 // Rename the file into user directory.
1353 DIR* otherdir = opendir(otherUser->getUserDirName());
1354 if (otherdir == NULL) {
1355 ALOGW("couldn't open user directory for rename");
1356 continue;
1357 }
1358 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1359 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1360 }
1361 closedir(otherdir);
1362 }
1363 closedir(dir);
1364
1365 mMetaData.version = 1;
1366 upgraded = true;
1367 }
1368
1369 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001370 }
Kenny Roota91203b2012-02-15 15:00:46 -08001371};
1372
Kenny Root655b9582013-04-04 08:37:42 -07001373const char* KeyStore::sOldMasterKey = ".masterkey";
1374const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001375
Kenny Root07438c82012-11-02 15:41:02 -07001376namespace android {
1377class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1378public:
1379 KeyStoreProxy(KeyStore* keyStore)
1380 : mKeyStore(keyStore)
1381 {
Kenny Roota91203b2012-02-15 15:00:46 -08001382 }
Kenny Roota91203b2012-02-15 15:00:46 -08001383
Kenny Root07438c82012-11-02 15:41:02 -07001384 void binderDied(const wp<IBinder>&) {
1385 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001386 }
Kenny Roota91203b2012-02-15 15:00:46 -08001387
Kenny Root07438c82012-11-02 15:41:02 -07001388 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001389 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1390 if (!has_permission(callingUid, P_TEST)) {
1391 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001392 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001393 }
Kenny Roota91203b2012-02-15 15:00:46 -08001394
Kenny Root655b9582013-04-04 08:37:42 -07001395 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001396 }
1397
Kenny Root07438c82012-11-02 15:41:02 -07001398 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001399 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1400 if (!has_permission(callingUid, P_GET)) {
1401 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001402 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001403 }
Kenny Root07438c82012-11-02 15:41:02 -07001404
Kenny Root07438c82012-11-02 15:41:02 -07001405 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001406 Blob keyBlob;
Kenny Root49468902013-03-19 13:41:33 -07001407
Kenny Root655b9582013-04-04 08:37:42 -07001408 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001409 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001410 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001411 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001412 *item = NULL;
1413 *itemLength = 0;
1414 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001415 }
Kenny Roota91203b2012-02-15 15:00:46 -08001416
Kenny Root07438c82012-11-02 15:41:02 -07001417 *item = (uint8_t*) malloc(keyBlob.getLength());
1418 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1419 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001420
Kenny Root07438c82012-11-02 15:41:02 -07001421 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001422 }
1423
Kenny Rootf9119d62013-04-03 09:22:15 -07001424 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1425 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001426 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1427 if (!has_permission(callingUid, P_INSERT)) {
1428 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001429 return ::PERMISSION_DENIED;
1430 }
Kenny Root07438c82012-11-02 15:41:02 -07001431
Kenny Rootf9119d62013-04-03 09:22:15 -07001432 State state = mKeyStore->getState(callingUid);
1433 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1434 ALOGD("calling get in state: %d", state);
1435 return state;
1436 }
1437
Kenny Root49468902013-03-19 13:41:33 -07001438 if (targetUid == -1) {
1439 targetUid = callingUid;
1440 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001441 return ::PERMISSION_DENIED;
1442 }
1443
Kenny Root07438c82012-11-02 15:41:02 -07001444 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001445 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001446
1447 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Root655b9582013-04-04 08:37:42 -07001448 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001449 }
1450
Kenny Root49468902013-03-19 13:41:33 -07001451 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001452 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1453 if (!has_permission(callingUid, P_DELETE)) {
1454 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001455 return ::PERMISSION_DENIED;
1456 }
Kenny Root70e3a862012-02-15 17:20:23 -08001457
Kenny Root49468902013-03-19 13:41:33 -07001458 if (targetUid == -1) {
1459 targetUid = callingUid;
1460 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001461 return ::PERMISSION_DENIED;
1462 }
1463
Kenny Root07438c82012-11-02 15:41:02 -07001464 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001465 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001466
1467 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001468 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
1469 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001470 if (responseCode != ::NO_ERROR) {
1471 return responseCode;
1472 }
1473 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001474 }
1475
Kenny Root49468902013-03-19 13:41:33 -07001476 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001477 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1478 if (!has_permission(callingUid, P_EXIST)) {
1479 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001480 return ::PERMISSION_DENIED;
1481 }
Kenny Root70e3a862012-02-15 17:20:23 -08001482
Kenny Root49468902013-03-19 13:41:33 -07001483 if (targetUid == -1) {
1484 targetUid = callingUid;
1485 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001486 return ::PERMISSION_DENIED;
1487 }
1488
Kenny Root07438c82012-11-02 15:41:02 -07001489 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001490 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001491
Kenny Root655b9582013-04-04 08:37:42 -07001492 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001493 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1494 }
1495 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001496 }
1497
Kenny Root49468902013-03-19 13:41:33 -07001498 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001499 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1500 if (!has_permission(callingUid, P_SAW)) {
1501 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001502 return ::PERMISSION_DENIED;
1503 }
Kenny Root70e3a862012-02-15 17:20:23 -08001504
Kenny Root49468902013-03-19 13:41:33 -07001505 if (targetUid == -1) {
1506 targetUid = callingUid;
1507 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001508 return ::PERMISSION_DENIED;
1509 }
1510
Kenny Root655b9582013-04-04 08:37:42 -07001511 UserState* userState = mKeyStore->getUserState(targetUid);
1512 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001513 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07001514 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001515 return ::SYSTEM_ERROR;
1516 }
Kenny Root70e3a862012-02-15 17:20:23 -08001517
Kenny Root07438c82012-11-02 15:41:02 -07001518 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001519 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1520 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001521
Kenny Root07438c82012-11-02 15:41:02 -07001522 struct dirent* file;
1523 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001524 // We only care about files.
1525 if (file->d_type != DT_REG) {
1526 continue;
1527 }
1528
1529 // Skip anything that starts with a "."
1530 if (file->d_name[0] == '.') {
1531 continue;
1532 }
1533
1534 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001535 const char* p = &file->d_name[n];
1536 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001537
Kenny Root07438c82012-11-02 15:41:02 -07001538 size_t extra = decode_key_length(p, plen);
1539 char *match = (char*) malloc(extra + 1);
1540 if (match != NULL) {
1541 decode_key(match, p, plen);
1542 matches->push(String16(match, extra));
1543 free(match);
1544 } else {
1545 ALOGW("could not allocate match of size %zd", extra);
1546 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001547 }
1548 }
Kenny Root07438c82012-11-02 15:41:02 -07001549 closedir(dir);
1550
1551 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001552 }
1553
Kenny Root07438c82012-11-02 15:41:02 -07001554 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001555 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1556 if (!has_permission(callingUid, P_RESET)) {
1557 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001558 return ::PERMISSION_DENIED;
1559 }
1560
Kenny Root655b9582013-04-04 08:37:42 -07001561 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001562
1563 const keymaster_device_t* device = mKeyStore->getDevice();
1564 if (device == NULL) {
1565 ALOGE("No keymaster device!");
1566 return ::SYSTEM_ERROR;
1567 }
1568
1569 if (device->delete_all == NULL) {
1570 ALOGV("keymaster device doesn't implement delete_all");
1571 return rc;
1572 }
1573
1574 if (device->delete_all(device)) {
1575 ALOGE("Problem calling keymaster's delete_all");
1576 return ::SYSTEM_ERROR;
1577 }
1578
Kenny Root9a53d3e2012-08-14 10:47:54 -07001579 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001580 }
1581
Kenny Root07438c82012-11-02 15:41:02 -07001582 /*
1583 * Here is the history. To improve the security, the parameters to generate the
1584 * master key has been changed. To make a seamless transition, we update the
1585 * file using the same password when the user unlock it for the first time. If
1586 * any thing goes wrong during the transition, the new file will not overwrite
1587 * the old one. This avoids permanent damages of the existing data.
1588 */
1589 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001590 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1591 if (!has_permission(callingUid, P_PASSWORD)) {
1592 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001593 return ::PERMISSION_DENIED;
1594 }
Kenny Root70e3a862012-02-15 17:20:23 -08001595
Kenny Root07438c82012-11-02 15:41:02 -07001596 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001597
Kenny Root655b9582013-04-04 08:37:42 -07001598 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001599 case ::STATE_UNINITIALIZED: {
1600 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001601 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001602 }
1603 case ::STATE_NO_ERROR: {
1604 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001605 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001606 }
1607 case ::STATE_LOCKED: {
1608 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001609 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001610 }
1611 }
1612 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001613 }
1614
Kenny Root07438c82012-11-02 15:41:02 -07001615 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001616 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1617 if (!has_permission(callingUid, P_LOCK)) {
1618 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001619 return ::PERMISSION_DENIED;
1620 }
Kenny Root70e3a862012-02-15 17:20:23 -08001621
Kenny Root655b9582013-04-04 08:37:42 -07001622 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001623 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001624 ALOGD("calling lock in state: %d", state);
1625 return state;
1626 }
1627
Kenny Root655b9582013-04-04 08:37:42 -07001628 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001629 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001630 }
1631
Kenny Root07438c82012-11-02 15:41:02 -07001632 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001633 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1634 if (!has_permission(callingUid, P_UNLOCK)) {
1635 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001636 return ::PERMISSION_DENIED;
1637 }
1638
Kenny Root655b9582013-04-04 08:37:42 -07001639 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001640 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001641 ALOGD("calling unlock when not locked");
1642 return state;
1643 }
1644
1645 const String8 password8(pw);
1646 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001647 }
1648
Kenny Root07438c82012-11-02 15:41:02 -07001649 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001650 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1651 if (!has_permission(callingUid, P_ZERO)) {
1652 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001653 return -1;
1654 }
Kenny Root70e3a862012-02-15 17:20:23 -08001655
Kenny Root655b9582013-04-04 08:37:42 -07001656 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001657 }
1658
Kenny Rootf9119d62013-04-03 09:22:15 -07001659 int32_t generate(const String16& name, int targetUid, int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001660 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1661 if (!has_permission(callingUid, P_INSERT)) {
1662 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001663 return ::PERMISSION_DENIED;
1664 }
Kenny Root70e3a862012-02-15 17:20:23 -08001665
Kenny Root49468902013-03-19 13:41:33 -07001666 if (targetUid == -1) {
1667 targetUid = callingUid;
1668 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001669 return ::PERMISSION_DENIED;
1670 }
1671
Kenny Root655b9582013-04-04 08:37:42 -07001672 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001673 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1674 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001675 return state;
1676 }
Kenny Root70e3a862012-02-15 17:20:23 -08001677
Kenny Root07438c82012-11-02 15:41:02 -07001678 uint8_t* data;
1679 size_t dataLength;
1680 int rc;
1681
1682 const keymaster_device_t* device = mKeyStore->getDevice();
1683 if (device == NULL) {
1684 return ::SYSTEM_ERROR;
1685 }
1686
1687 if (device->generate_keypair == NULL) {
1688 return ::SYSTEM_ERROR;
1689 }
1690
1691 keymaster_rsa_keygen_params_t rsa_params;
1692 rsa_params.modulus_size = 2048;
1693 rsa_params.public_exponent = 0x10001;
1694
1695 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1696 if (rc) {
1697 return ::SYSTEM_ERROR;
1698 }
1699
Kenny Root655b9582013-04-04 08:37:42 -07001700 String8 name8(name);
1701 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001702
1703 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1704 free(data);
1705
Kenny Root655b9582013-04-04 08:37:42 -07001706 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001707 }
1708
Kenny Rootf9119d62013-04-03 09:22:15 -07001709 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1710 int32_t flags) {
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: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001714 return ::PERMISSION_DENIED;
1715 }
Kenny Root07438c82012-11-02 15:41:02 -07001716
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)) {
Kenny Root07438c82012-11-02 15:41:02 -07001725 ALOGD("calling import in state: %d", state);
1726 return state;
1727 }
1728
1729 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001730 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001731
Kenny Rootf9119d62013-04-03 09:22:15 -07001732 return mKeyStore->importKey(data, length, filename.string(), callingUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001733 }
1734
Kenny Root07438c82012-11-02 15:41:02 -07001735 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1736 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001737 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1738 if (!has_permission(callingUid, P_SIGN)) {
1739 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001740 return ::PERMISSION_DENIED;
1741 }
Kenny Root07438c82012-11-02 15:41:02 -07001742
Kenny Root07438c82012-11-02 15:41:02 -07001743 Blob keyBlob;
1744 String8 name8(name);
1745
Kenny Rootd38a0b02013-02-13 12:59:14 -08001746 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001747 int rc;
1748
Kenny Root655b9582013-04-04 08:37:42 -07001749 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001750 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001751 if (responseCode != ::NO_ERROR) {
1752 return responseCode;
1753 }
1754
1755 const keymaster_device_t* device = mKeyStore->getDevice();
1756 if (device == NULL) {
1757 ALOGE("no keymaster device; cannot sign");
1758 return ::SYSTEM_ERROR;
1759 }
1760
1761 if (device->sign_data == NULL) {
1762 ALOGE("device doesn't implement signing");
1763 return ::SYSTEM_ERROR;
1764 }
1765
1766 keymaster_rsa_sign_params_t params;
1767 params.digest_type = DIGEST_NONE;
1768 params.padding_type = PADDING_NONE;
1769
1770 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1771 data, length, out, outLength);
1772 if (rc) {
1773 ALOGW("device couldn't sign data");
1774 return ::SYSTEM_ERROR;
1775 }
1776
1777 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001778 }
1779
Kenny Root07438c82012-11-02 15:41:02 -07001780 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1781 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001782 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1783 if (!has_permission(callingUid, P_VERIFY)) {
1784 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001785 return ::PERMISSION_DENIED;
1786 }
Kenny Root70e3a862012-02-15 17:20:23 -08001787
Kenny Root655b9582013-04-04 08:37:42 -07001788 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001789 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001790 ALOGD("calling verify in state: %d", state);
1791 return state;
1792 }
Kenny Root70e3a862012-02-15 17:20:23 -08001793
Kenny Root07438c82012-11-02 15:41:02 -07001794 Blob keyBlob;
1795 String8 name8(name);
1796 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001797
Kenny Root655b9582013-04-04 08:37:42 -07001798 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001799 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001800 if (responseCode != ::NO_ERROR) {
1801 return responseCode;
1802 }
Kenny Root70e3a862012-02-15 17:20:23 -08001803
Kenny Root07438c82012-11-02 15:41:02 -07001804 const keymaster_device_t* device = mKeyStore->getDevice();
1805 if (device == NULL) {
1806 return ::SYSTEM_ERROR;
1807 }
Kenny Root70e3a862012-02-15 17:20:23 -08001808
Kenny Root07438c82012-11-02 15:41:02 -07001809 if (device->verify_data == NULL) {
1810 return ::SYSTEM_ERROR;
1811 }
Kenny Root70e3a862012-02-15 17:20:23 -08001812
Kenny Root07438c82012-11-02 15:41:02 -07001813 keymaster_rsa_sign_params_t params;
1814 params.digest_type = DIGEST_NONE;
1815 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001816
Kenny Root07438c82012-11-02 15:41:02 -07001817 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1818 data, dataLength, signature, signatureLength);
1819 if (rc) {
1820 return ::SYSTEM_ERROR;
1821 } else {
1822 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001823 }
1824 }
Kenny Root07438c82012-11-02 15:41:02 -07001825
1826 /*
1827 * TODO: The abstraction between things stored in hardware and regular blobs
1828 * of data stored on the filesystem should be moved down to keystore itself.
1829 * Unfortunately the Java code that calls this has naming conventions that it
1830 * knows about. Ideally keystore shouldn't be used to store random blobs of
1831 * data.
1832 *
1833 * Until that happens, it's necessary to have a separate "get_pubkey" and
1834 * "del_key" since the Java code doesn't really communicate what it's
1835 * intentions are.
1836 */
1837 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001838 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1839 if (!has_permission(callingUid, P_GET)) {
1840 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001841 return ::PERMISSION_DENIED;
1842 }
Kenny Root07438c82012-11-02 15:41:02 -07001843
Kenny Root07438c82012-11-02 15:41:02 -07001844 Blob keyBlob;
1845 String8 name8(name);
1846
Kenny Rootd38a0b02013-02-13 12:59:14 -08001847 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001848
Kenny Root655b9582013-04-04 08:37:42 -07001849 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07001850 TYPE_KEY_PAIR);
1851 if (responseCode != ::NO_ERROR) {
1852 return responseCode;
1853 }
1854
1855 const keymaster_device_t* device = mKeyStore->getDevice();
1856 if (device == NULL) {
1857 return ::SYSTEM_ERROR;
1858 }
1859
1860 if (device->get_keypair_public == NULL) {
1861 ALOGE("device has no get_keypair_public implementation!");
1862 return ::SYSTEM_ERROR;
1863 }
1864
1865 int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
1866 pubkeyLength);
1867 if (rc) {
1868 return ::SYSTEM_ERROR;
1869 }
1870
1871 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001872 }
Kenny Root07438c82012-11-02 15:41:02 -07001873
Kenny Root49468902013-03-19 13:41:33 -07001874 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001875 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1876 if (!has_permission(callingUid, P_DELETE)) {
1877 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001878 return ::PERMISSION_DENIED;
1879 }
Kenny Root07438c82012-11-02 15:41:02 -07001880
Kenny Root49468902013-03-19 13:41:33 -07001881 if (targetUid == -1) {
1882 targetUid = callingUid;
1883 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001884 return ::PERMISSION_DENIED;
1885 }
1886
Kenny Root07438c82012-11-02 15:41:02 -07001887 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001888 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001889
1890 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001891 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
1892 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001893 if (responseCode != ::NO_ERROR) {
1894 return responseCode;
1895 }
1896
1897 ResponseCode rc = ::NO_ERROR;
1898
1899 const keymaster_device_t* device = mKeyStore->getDevice();
1900 if (device == NULL) {
1901 rc = ::SYSTEM_ERROR;
1902 } else {
1903 // A device doesn't have to implement delete_keypair.
1904 if (device->delete_keypair != NULL) {
1905 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1906 rc = ::SYSTEM_ERROR;
1907 }
1908 }
1909 }
1910
1911 if (rc != ::NO_ERROR) {
1912 return rc;
1913 }
1914
1915 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1916 }
1917
1918 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001919 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1920 if (!has_permission(callingUid, P_GRANT)) {
1921 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001922 return ::PERMISSION_DENIED;
1923 }
Kenny Root07438c82012-11-02 15:41:02 -07001924
Kenny Root655b9582013-04-04 08:37:42 -07001925 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001926 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001927 ALOGD("calling grant in state: %d", state);
1928 return state;
1929 }
1930
1931 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001932 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001933
Kenny Root655b9582013-04-04 08:37:42 -07001934 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001935 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1936 }
1937
Kenny Root655b9582013-04-04 08:37:42 -07001938 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07001939 return ::NO_ERROR;
1940 }
1941
1942 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001943 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1944 if (!has_permission(callingUid, P_GRANT)) {
1945 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001946 return ::PERMISSION_DENIED;
1947 }
Kenny Root07438c82012-11-02 15:41:02 -07001948
Kenny Root655b9582013-04-04 08:37:42 -07001949 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001950 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001951 ALOGD("calling ungrant in state: %d", state);
1952 return state;
1953 }
1954
1955 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001956 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001957
Kenny Root655b9582013-04-04 08:37:42 -07001958 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001959 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1960 }
1961
Kenny Root655b9582013-04-04 08:37:42 -07001962 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07001963 }
1964
1965 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001966 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1967 if (!has_permission(callingUid, P_GET)) {
1968 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08001969 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001970 }
Kenny Root07438c82012-11-02 15:41:02 -07001971
1972 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001973 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001974
Kenny Root655b9582013-04-04 08:37:42 -07001975 if (access(filename.string(), R_OK) == -1) {
1976 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08001977 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001978 }
1979
Kenny Root655b9582013-04-04 08:37:42 -07001980 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07001981 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07001982 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08001983 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001984 }
1985
1986 struct stat s;
1987 int ret = fstat(fd, &s);
1988 close(fd);
1989 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07001990 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08001991 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001992 }
1993
Kenny Root36a9e232013-02-04 14:24:15 -08001994 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07001995 }
1996
Kenny Rootd53bc922013-03-21 14:10:15 -07001997 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
1998 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07001999 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Rootd53bc922013-03-21 14:10:15 -07002000 if (!has_permission(callingUid, P_DUPLICATE)) {
2001 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002002 return -1L;
2003 }
2004
Kenny Root655b9582013-04-04 08:37:42 -07002005 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002006 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002007 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002008 return state;
2009 }
2010
Kenny Rootd53bc922013-03-21 14:10:15 -07002011 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2012 srcUid = callingUid;
2013 } else if (!is_granted_to(callingUid, srcUid)) {
2014 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002015 return ::PERMISSION_DENIED;
2016 }
2017
Kenny Rootd53bc922013-03-21 14:10:15 -07002018 if (destUid == -1) {
2019 destUid = callingUid;
2020 }
2021
2022 if (srcUid != destUid) {
2023 if (static_cast<uid_t>(srcUid) != callingUid) {
2024 ALOGD("can only duplicate from caller to other or to same uid: "
2025 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2026 return ::PERMISSION_DENIED;
2027 }
2028
2029 if (!is_granted_to(callingUid, destUid)) {
2030 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2031 return ::PERMISSION_DENIED;
2032 }
2033 }
2034
2035 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002036 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002037
Kenny Rootd53bc922013-03-21 14:10:15 -07002038 String8 target8(destKey);
Kenny Root655b9582013-04-04 08:37:42 -07002039 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002040
Kenny Root655b9582013-04-04 08:37:42 -07002041 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2042 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002043 return ::SYSTEM_ERROR;
2044 }
2045
Kenny Rootd53bc922013-03-21 14:10:15 -07002046 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002047 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
2048 callingUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002049 if (responseCode != ::NO_ERROR) {
2050 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002051 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002052
Kenny Root655b9582013-04-04 08:37:42 -07002053 return mKeyStore->put(targetFile.string(), &keyBlob, callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002054 }
2055
Kenny Root8ddf35a2013-03-29 11:15:50 -07002056 int32_t is_hardware_backed() {
2057 return mKeyStore->isHardwareBacked() ? 1 : 0;
2058 }
2059
Kenny Roota9bb5492013-04-01 16:29:11 -07002060 int32_t clear_uid(int64_t targetUid) {
2061 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2062 if (!has_permission(callingUid, P_CLEAR_UID)) {
2063 ALOGW("permission denied for %d: clear_uid", callingUid);
2064 return ::PERMISSION_DENIED;
2065 }
2066
Kenny Root655b9582013-04-04 08:37:42 -07002067 State state = mKeyStore->getState(callingUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002068 if (!isKeystoreUnlocked(state)) {
2069 ALOGD("calling clear_uid in state: %d", state);
2070 return state;
2071 }
2072
2073 const keymaster_device_t* device = mKeyStore->getDevice();
2074 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002075 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002076 return ::SYSTEM_ERROR;
2077 }
2078
Kenny Root655b9582013-04-04 08:37:42 -07002079 UserState* userState = mKeyStore->getUserState(callingUid);
2080 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota9bb5492013-04-01 16:29:11 -07002081 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07002082 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Roota9bb5492013-04-01 16:29:11 -07002083 return ::SYSTEM_ERROR;
2084 }
2085
Kenny Root655b9582013-04-04 08:37:42 -07002086 char prefix[NAME_MAX];
2087 int n = snprintf(prefix, NAME_MAX, "%u_", static_cast<uid_t>(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002088
2089 ResponseCode rc = ::NO_ERROR;
2090
2091 struct dirent* file;
2092 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002093 // We only care about files.
2094 if (file->d_type != DT_REG) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002095 continue;
2096 }
2097
Kenny Root655b9582013-04-04 08:37:42 -07002098 // Skip anything that starts with a "."
2099 if (file->d_name[0] == '.') {
2100 continue;
2101 }
Kenny Roota9bb5492013-04-01 16:29:11 -07002102
Kenny Root655b9582013-04-04 08:37:42 -07002103 if (strncmp(prefix, file->d_name, n)) {
2104 continue;
2105 }
2106
2107 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Roota9bb5492013-04-01 16:29:11 -07002108 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002109 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, callingUid)
2110 != ::NO_ERROR) {
2111 ALOGW("couldn't open %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002112 continue;
2113 }
2114
2115 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2116 // A device doesn't have to implement delete_keypair.
2117 if (device->delete_keypair != NULL) {
2118 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2119 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002120 ALOGW("device couldn't remove %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002121 }
2122 }
2123 }
2124
Kenny Root5f531242013-04-12 11:31:50 -07002125 if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002126 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002127 ALOGW("couldn't unlink %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002128 }
2129 }
2130 closedir(dir);
2131
2132 return rc;
2133 }
2134
Kenny Root07438c82012-11-02 15:41:02 -07002135private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002136 inline bool isKeystoreUnlocked(State state) {
2137 switch (state) {
2138 case ::STATE_NO_ERROR:
2139 return true;
2140 case ::STATE_UNINITIALIZED:
2141 case ::STATE_LOCKED:
2142 return false;
2143 }
2144 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002145 }
2146
2147 ::KeyStore* mKeyStore;
2148};
2149
2150}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002151
2152int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002153 if (argc < 2) {
2154 ALOGE("A directory must be specified!");
2155 return 1;
2156 }
2157 if (chdir(argv[1]) == -1) {
2158 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2159 return 1;
2160 }
2161
2162 Entropy entropy;
2163 if (!entropy.open()) {
2164 return 1;
2165 }
Kenny Root70e3a862012-02-15 17:20:23 -08002166
2167 keymaster_device_t* dev;
2168 if (keymaster_device_initialize(&dev)) {
2169 ALOGE("keystore keymaster could not be initialized; exiting");
2170 return 1;
2171 }
2172
Kenny Root70e3a862012-02-15 17:20:23 -08002173 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002174 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002175 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2176 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2177 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2178 if (ret != android::OK) {
2179 ALOGE("Couldn't register binder service!");
2180 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002181 }
Kenny Root07438c82012-11-02 15:41:02 -07002182
2183 /*
2184 * We're the only thread in existence, so we're just going to process
2185 * Binder transaction as a single-threaded program.
2186 */
2187 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002188
2189 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002190 return 1;
2191}