blob: 482e21b047635be18858ccc052bea5bcb35e9b31 [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,
367 * the second is the blob's type, and the third byte is reserved. 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;
388 uint8_t reserved;
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 Root07438c82012-11-02 15:41:02 -0700405static const uint8_t CURRENT_BLOB_VERSION = 1;
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 Roota91203b2012-02-15 15:00:46 -0800419 }
420
421 Blob(blob b) {
422 mBlob = b;
423 }
424
425 Blob() {}
426
Kenny Root51878182012-03-13 12:53:19 -0700427 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800428 return mBlob.value;
429 }
430
Kenny Root51878182012-03-13 12:53:19 -0700431 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800432 return mBlob.length;
433 }
434
Kenny Root51878182012-03-13 12:53:19 -0700435 const uint8_t* getInfo() const {
436 return mBlob.value + mBlob.length;
437 }
438
439 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800440 return mBlob.info;
441 }
442
Kenny Root822c3a92012-03-23 16:34:39 -0700443 uint8_t getVersion() const {
444 return mBlob.version;
445 }
446
447 void setVersion(uint8_t version) {
448 mBlob.version = version;
449 }
450
451 BlobType getType() const {
452 return BlobType(mBlob.type);
453 }
454
455 void setType(BlobType type) {
456 mBlob.type = uint8_t(type);
457 }
458
Kenny Roota91203b2012-02-15 15:00:46 -0800459 ResponseCode encryptBlob(const char* filename, AES_KEY *aes_key, Entropy* entropy) {
460 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
Kenny Root150ca932012-11-14 14:29:02 -0800461 ALOGW("Could not read random data for: %s", filename);
Kenny Roota91203b2012-02-15 15:00:46 -0800462 return SYSTEM_ERROR;
463 }
464
465 // data includes the value and the value's length
466 size_t dataLength = mBlob.length + sizeof(mBlob.length);
467 // pad data to the AES_BLOCK_SIZE
468 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
469 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
470 // encrypted data includes the digest value
471 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
472 // move info after space for padding
473 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
474 // zero padding area
475 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
476
477 mBlob.length = htonl(mBlob.length);
478 MD5(mBlob.digested, digestedLength, mBlob.digest);
479
480 uint8_t vector[AES_BLOCK_SIZE];
481 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
482 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
483 aes_key, vector, AES_ENCRYPT);
484
Kenny Root822c3a92012-03-23 16:34:39 -0700485 mBlob.reserved = 0;
Kenny Roota91203b2012-02-15 15:00:46 -0800486 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
487 size_t fileLength = encryptedLength + headerLength + mBlob.info;
488
489 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800490 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
491 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
492 if (out < 0) {
493 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800494 return SYSTEM_ERROR;
495 }
496 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
497 if (close(out) != 0) {
498 return SYSTEM_ERROR;
499 }
500 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800501 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800502 unlink(tmpFileName);
503 return SYSTEM_ERROR;
504 }
Kenny Root150ca932012-11-14 14:29:02 -0800505 if (rename(tmpFileName, filename) == -1) {
506 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
507 return SYSTEM_ERROR;
508 }
509 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800510 }
511
512 ResponseCode decryptBlob(const char* filename, AES_KEY *aes_key) {
Kenny Root150ca932012-11-14 14:29:02 -0800513 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
514 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800515 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
516 }
517 // fileLength may be less than sizeof(mBlob) since the in
518 // memory version has extra padding to tolerate rounding up to
519 // the AES_BLOCK_SIZE
520 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
521 if (close(in) != 0) {
522 return SYSTEM_ERROR;
523 }
524 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
525 if (fileLength < headerLength) {
526 return VALUE_CORRUPTED;
527 }
528
529 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
530 if (encryptedLength < 0 || encryptedLength % AES_BLOCK_SIZE != 0) {
531 return VALUE_CORRUPTED;
532 }
533 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
534 mBlob.vector, AES_DECRYPT);
535 size_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
536 uint8_t computedDigest[MD5_DIGEST_LENGTH];
537 MD5(mBlob.digested, digestedLength, computedDigest);
538 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
539 return VALUE_CORRUPTED;
540 }
541
542 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
543 mBlob.length = ntohl(mBlob.length);
544 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
545 return VALUE_CORRUPTED;
546 }
547 if (mBlob.info != 0) {
548 // move info from after padding to after data
549 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
550 }
Kenny Root07438c82012-11-02 15:41:02 -0700551 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800552 }
553
554private:
555 struct blob mBlob;
556};
557
Kenny Root655b9582013-04-04 08:37:42 -0700558class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800559public:
Kenny Root655b9582013-04-04 08:37:42 -0700560 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
561 asprintf(&mUserDir, "user_%u", mUserId);
562 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
563 }
564
565 ~UserState() {
566 free(mUserDir);
567 free(mMasterKeyFile);
568 }
569
570 bool initialize() {
571 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
572 ALOGE("Could not create directory '%s'", mUserDir);
573 return false;
574 }
575
576 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800577 setState(STATE_LOCKED);
578 } else {
579 setState(STATE_UNINITIALIZED);
580 }
Kenny Root70e3a862012-02-15 17:20:23 -0800581
Kenny Root655b9582013-04-04 08:37:42 -0700582 return true;
583 }
584
585 uid_t getUserId() const {
586 return mUserId;
587 }
588
589 const char* getUserDirName() const {
590 return mUserDir;
591 }
592
593 const char* getMasterKeyFileName() const {
594 return mMasterKeyFile;
595 }
596
597 void setState(State state) {
598 mState = state;
599 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
600 mRetry = MAX_RETRY;
601 }
Kenny Roota91203b2012-02-15 15:00:46 -0800602 }
603
Kenny Root51878182012-03-13 12:53:19 -0700604 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800605 return mState;
606 }
607
Kenny Root51878182012-03-13 12:53:19 -0700608 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800609 return mRetry;
610 }
611
Kenny Root655b9582013-04-04 08:37:42 -0700612 void zeroizeMasterKeysInMemory() {
613 memset(mMasterKey, 0, sizeof(mMasterKey));
614 memset(mSalt, 0, sizeof(mSalt));
615 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
616 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800617 }
618
Kenny Root655b9582013-04-04 08:37:42 -0700619 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
620 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800621 return SYSTEM_ERROR;
622 }
Kenny Root655b9582013-04-04 08:37:42 -0700623 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800624 if (response != NO_ERROR) {
625 return response;
626 }
627 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700628 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800629 }
630
Kenny Root655b9582013-04-04 08:37:42 -0700631 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800632 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
633 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
634 AES_KEY passwordAesKey;
635 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700636 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Root655b9582013-04-04 08:37:42 -0700637 return masterKeyBlob.encryptBlob(mMasterKeyFile, &passwordAesKey, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800638 }
639
Kenny Root655b9582013-04-04 08:37:42 -0700640 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
641 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800642 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800643 return SYSTEM_ERROR;
644 }
645
646 // we read the raw blob to just to get the salt to generate
647 // the AES key, then we create the Blob to use with decryptBlob
648 blob rawBlob;
649 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
650 if (close(in) != 0) {
651 return SYSTEM_ERROR;
652 }
653 // find salt at EOF if present, otherwise we have an old file
654 uint8_t* salt;
655 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
656 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
657 } else {
658 salt = NULL;
659 }
660 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
661 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
662 AES_KEY passwordAesKey;
663 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
664 Blob masterKeyBlob(rawBlob);
Kenny Root655b9582013-04-04 08:37:42 -0700665 ResponseCode response = masterKeyBlob.decryptBlob(mMasterKeyFile, &passwordAesKey);
Kenny Roota91203b2012-02-15 15:00:46 -0800666 if (response == SYSTEM_ERROR) {
667 return SYSTEM_ERROR;
668 }
669 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
670 // if salt was missing, generate one and write a new master key file with the salt.
671 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700672 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800673 return SYSTEM_ERROR;
674 }
Kenny Root655b9582013-04-04 08:37:42 -0700675 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800676 }
677 if (response == NO_ERROR) {
678 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
679 setupMasterKeys();
680 }
681 return response;
682 }
683 if (mRetry <= 0) {
684 reset();
685 return UNINITIALIZED;
686 }
687 --mRetry;
688 switch (mRetry) {
689 case 0: return WRONG_PASSWORD_0;
690 case 1: return WRONG_PASSWORD_1;
691 case 2: return WRONG_PASSWORD_2;
692 case 3: return WRONG_PASSWORD_3;
693 default: return WRONG_PASSWORD_3;
694 }
695 }
696
Kenny Root655b9582013-04-04 08:37:42 -0700697 AES_KEY* getEncryptionKey() {
698 return &mMasterKeyEncryption;
699 }
700
701 AES_KEY* getDecryptionKey() {
702 return &mMasterKeyDecryption;
703 }
704
Kenny Roota91203b2012-02-15 15:00:46 -0800705 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700706 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800707 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700708 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800709 return false;
710 }
Kenny Root655b9582013-04-04 08:37:42 -0700711
712 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800713 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700714 // We only care about files.
715 if (file->d_type != DT_REG) {
716 continue;
717 }
718
719 // Skip anything that starts with a "."
720 if (file->d_name[0] == '.') {
721 continue;
722 }
723
724 // Find the current file's UID.
725 char* end;
726 unsigned long thisUid = strtoul(file->d_name, &end, 10);
727 if (end[0] != '_' || end[1] == 0) {
728 continue;
729 }
730
731 // Skip if this is not our user.
732 if (get_user_id(thisUid) != mUserId) {
733 continue;
734 }
735
736 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800737 }
738 closedir(dir);
739 return true;
740 }
741
Kenny Root655b9582013-04-04 08:37:42 -0700742private:
743 static const int MASTER_KEY_SIZE_BYTES = 16;
744 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
745
746 static const int MAX_RETRY = 4;
747 static const size_t SALT_SIZE = 16;
748
749 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
750 uint8_t* salt) {
751 size_t saltSize;
752 if (salt != NULL) {
753 saltSize = SALT_SIZE;
754 } else {
755 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
756 salt = (uint8_t*) "keystore";
757 // sizeof = 9, not strlen = 8
758 saltSize = sizeof("keystore");
759 }
760
761 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
762 saltSize, 8192, keySize, key);
763 }
764
765 bool generateSalt(Entropy* entropy) {
766 return entropy->generate_random_data(mSalt, sizeof(mSalt));
767 }
768
769 bool generateMasterKey(Entropy* entropy) {
770 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
771 return false;
772 }
773 if (!generateSalt(entropy)) {
774 return false;
775 }
776 return true;
777 }
778
779 void setupMasterKeys() {
780 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
781 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
782 setState(STATE_NO_ERROR);
783 }
784
785 uid_t mUserId;
786
787 char* mUserDir;
788 char* mMasterKeyFile;
789
790 State mState;
791 int8_t mRetry;
792
793 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
794 uint8_t mSalt[SALT_SIZE];
795
796 AES_KEY mMasterKeyEncryption;
797 AES_KEY mMasterKeyDecryption;
798};
799
800typedef struct {
801 uint32_t uid;
802 const uint8_t* filename;
803} grant_t;
804
805class KeyStore {
806public:
807 KeyStore(Entropy* entropy, keymaster_device_t* device)
808 : mEntropy(entropy)
809 , mDevice(device)
810 {
811 memset(&mMetaData, '\0', sizeof(mMetaData));
812 }
813
814 ~KeyStore() {
815 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
816 it != mGrants.end(); it++) {
817 delete *it;
818 mGrants.erase(it);
819 }
820
821 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
822 it != mMasterKeys.end(); it++) {
823 delete *it;
824 mMasterKeys.erase(it);
825 }
826 }
827
828 keymaster_device_t* getDevice() const {
829 return mDevice;
830 }
831
832 ResponseCode initialize() {
833 readMetaData();
834 if (upgradeKeystore()) {
835 writeMetaData();
836 }
837
838 return ::NO_ERROR;
839 }
840
841 State getState(uid_t uid) {
842 return getUserState(uid)->getState();
843 }
844
845 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
846 UserState* userState = getUserState(uid);
847 return userState->initialize(pw, mEntropy);
848 }
849
850 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
851 uid_t user_id = get_user_id(uid);
852 UserState* userState = getUserState(user_id);
853 return userState->writeMasterKey(pw, mEntropy);
854 }
855
856 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
857 uid_t user_id = get_user_id(uid);
858 UserState* userState = getUserState(user_id);
859 return userState->readMasterKey(pw, mEntropy);
860 }
861
862 android::String8 getKeyName(const android::String8& keyName) {
863 char encoded[encode_key_length(keyName)];
864 encode_key(encoded, keyName);
865 return android::String8(encoded);
866 }
867
868 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
869 char encoded[encode_key_length(keyName)];
870 encode_key(encoded, keyName);
871 return android::String8::format("%u_%s", uid, encoded);
872 }
873
874 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
875 char encoded[encode_key_length(keyName)];
876 encode_key(encoded, keyName);
877 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
878 encoded);
879 }
880
881 bool reset(uid_t uid) {
882 UserState* userState = getUserState(uid);
883 userState->zeroizeMasterKeysInMemory();
884 userState->setState(STATE_UNINITIALIZED);
885 return userState->reset();
886 }
887
888 bool isEmpty(uid_t uid) const {
889 const UserState* userState = getUserState(uid);
890 if (userState == NULL) {
891 return true;
892 }
893
894 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800895 struct dirent* file;
896 if (!dir) {
897 return true;
898 }
899 bool result = true;
Kenny Root655b9582013-04-04 08:37:42 -0700900
901 char filename[NAME_MAX];
902 int n = snprintf(filename, sizeof(filename), "%u_", uid);
903
Kenny Roota91203b2012-02-15 15:00:46 -0800904 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700905 // We only care about files.
906 if (file->d_type != DT_REG) {
907 continue;
908 }
909
910 // Skip anything that starts with a "."
911 if (file->d_name[0] == '.') {
912 continue;
913 }
914
915 if (!strncmp(file->d_name, filename, n)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800916 result = false;
917 break;
918 }
919 }
920 closedir(dir);
921 return result;
922 }
923
Kenny Root655b9582013-04-04 08:37:42 -0700924 void lock(uid_t uid) {
925 UserState* userState = getUserState(uid);
926 userState->zeroizeMasterKeysInMemory();
927 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -0800928 }
929
Kenny Root655b9582013-04-04 08:37:42 -0700930 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
931 UserState* userState = getUserState(uid);
932 ResponseCode rc = keyBlob->decryptBlob(filename, userState->getDecryptionKey());
Kenny Root822c3a92012-03-23 16:34:39 -0700933 if (rc != NO_ERROR) {
934 return rc;
935 }
936
937 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -0700938 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -0700939 /* If we upgrade the key, we need to write it to disk again. Then
940 * it must be read it again since the blob is encrypted each time
941 * it's written.
942 */
Kenny Root655b9582013-04-04 08:37:42 -0700943 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
944 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
945 || (rc = keyBlob->decryptBlob(filename, userState->getDecryptionKey()))
946 != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -0700947 return rc;
948 }
949 }
Kenny Root822c3a92012-03-23 16:34:39 -0700950 }
951
Kenny Rootd53bc922013-03-21 14:10:15 -0700952 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -0700953 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
954 return KEY_NOT_FOUND;
955 }
956
957 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -0800958 }
959
Kenny Root655b9582013-04-04 08:37:42 -0700960 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
961 UserState* userState = getUserState(uid);
962 return keyBlob->encryptBlob(filename, userState->getEncryptionKey(), mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800963 }
964
Kenny Root07438c82012-11-02 15:41:02 -0700965 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -0700966 const grant_t* existing = getGrant(filename, granteeUid);
967 if (existing == NULL) {
968 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -0700969 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700970 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -0700971 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -0800972 }
973 }
974
Kenny Root07438c82012-11-02 15:41:02 -0700975 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -0700976 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
977 it != mGrants.end(); it++) {
978 grant_t* grant = *it;
979 if (grant->uid == granteeUid
980 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
981 mGrants.erase(it);
982 return true;
983 }
Kenny Root70e3a862012-02-15 17:20:23 -0800984 }
Kenny Root70e3a862012-02-15 17:20:23 -0800985 return false;
986 }
987
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700988 bool hasGrant(const char* filename, const uid_t uid) const {
989 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -0800990 }
991
Kenny Root655b9582013-04-04 08:37:42 -0700992 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -0700993 uint8_t* data;
994 size_t dataLength;
995 int rc;
996
997 if (mDevice->import_keypair == NULL) {
998 ALOGE("Keymaster doesn't support import!");
999 return SYSTEM_ERROR;
1000 }
1001
Kenny Root07438c82012-11-02 15:41:02 -07001002 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001003 if (rc) {
1004 ALOGE("Error while importing keypair: %d", rc);
1005 return SYSTEM_ERROR;
1006 }
1007
1008 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1009 free(data);
1010
Kenny Root655b9582013-04-04 08:37:42 -07001011 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001012 }
1013
Kenny Root8ddf35a2013-03-29 11:15:50 -07001014 bool isHardwareBacked() const {
Kenny Root483407e2013-04-04 17:12:25 -07001015 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07001016 }
1017
Kenny Root655b9582013-04-04 08:37:42 -07001018 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1019 const BlobType type) {
1020 char filename[NAME_MAX];
1021 encode_key_for_uid(filename, uid, keyName);
1022
1023 UserState* userState = getUserState(uid);
1024 android::String8 filepath8;
1025
1026 filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1027 if (filepath8.string() == NULL) {
1028 ALOGW("can't create filepath for key %s", filename);
1029 return SYSTEM_ERROR;
1030 }
1031
1032 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1033 if (responseCode == NO_ERROR) {
1034 return responseCode;
1035 }
1036
1037 // If this is one of the legacy UID->UID mappings, use it.
1038 uid_t euid = get_keystore_euid(uid);
1039 if (euid != uid) {
1040 encode_key_for_uid(filename, euid, keyName);
1041 filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1042 responseCode = get(filepath8.string(), keyBlob, type, uid);
1043 if (responseCode == NO_ERROR) {
1044 return responseCode;
1045 }
1046 }
1047
1048 // They might be using a granted key.
1049 encode_key(filename, keyName);
1050 char* end;
1051 strtoul(filename, &end, 10);
1052 if (end[0] != '_' || end[1] == 0) {
1053 return KEY_NOT_FOUND;
1054 }
1055 filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
1056 if (!hasGrant(filepath8.string(), uid)) {
1057 return responseCode;
1058 }
1059
1060 // It is a granted key. Try to load it.
1061 return get(filepath8.string(), keyBlob, type, uid);
1062 }
1063
1064 /**
1065 * Returns any existing UserState or creates it if it doesn't exist.
1066 */
1067 UserState* getUserState(uid_t uid) {
1068 uid_t userId = get_user_id(uid);
1069
1070 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1071 it != mMasterKeys.end(); it++) {
1072 UserState* state = *it;
1073 if (state->getUserId() == userId) {
1074 return state;
1075 }
1076 }
1077
1078 UserState* userState = new UserState(userId);
1079 if (!userState->initialize()) {
1080 /* There's not much we can do if initialization fails. Trying to
1081 * unlock the keystore for that user will fail as well, so any
1082 * subsequent request for this user will just return SYSTEM_ERROR.
1083 */
1084 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1085 }
1086 mMasterKeys.add(userState);
1087 return userState;
1088 }
1089
1090 /**
1091 * Returns NULL if the UserState doesn't already exist.
1092 */
1093 const UserState* getUserState(uid_t uid) const {
1094 uid_t userId = get_user_id(uid);
1095
1096 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1097 it != mMasterKeys.end(); it++) {
1098 UserState* state = *it;
1099 if (state->getUserId() == userId) {
1100 return state;
1101 }
1102 }
1103
1104 return NULL;
1105 }
1106
Kenny Roota91203b2012-02-15 15:00:46 -08001107private:
Kenny Root655b9582013-04-04 08:37:42 -07001108 static const char* sOldMasterKey;
1109 static const char* sMetaDataFile;
Kenny Roota91203b2012-02-15 15:00:46 -08001110 Entropy* mEntropy;
1111
Kenny Root70e3a862012-02-15 17:20:23 -08001112 keymaster_device_t* mDevice;
1113
Kenny Root655b9582013-04-04 08:37:42 -07001114 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001115
Kenny Root655b9582013-04-04 08:37:42 -07001116 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001117
Kenny Root655b9582013-04-04 08:37:42 -07001118 typedef struct {
1119 uint32_t version;
1120 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001121
Kenny Root655b9582013-04-04 08:37:42 -07001122 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001123
Kenny Root655b9582013-04-04 08:37:42 -07001124 const grant_t* getGrant(const char* filename, uid_t uid) const {
1125 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1126 it != mGrants.end(); it++) {
1127 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001128 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001129 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001130 return grant;
1131 }
1132 }
Kenny Root70e3a862012-02-15 17:20:23 -08001133 return NULL;
1134 }
1135
Kenny Root822c3a92012-03-23 16:34:39 -07001136 /**
1137 * Upgrade code. This will upgrade the key from the current version
1138 * to whatever is newest.
1139 */
Kenny Root655b9582013-04-04 08:37:42 -07001140 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1141 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001142 bool updated = false;
1143 uint8_t version = oldVersion;
1144
1145 /* From V0 -> V1: All old types were unknown */
1146 if (version == 0) {
1147 ALOGV("upgrading to version 1 and setting type %d", type);
1148
1149 blob->setType(type);
1150 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001151 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001152 }
1153 version = 1;
1154 updated = true;
1155 }
1156
1157 /*
1158 * If we've updated, set the key blob to the right version
1159 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001160 */
Kenny Root822c3a92012-03-23 16:34:39 -07001161 if (updated) {
1162 ALOGV("updated and writing file %s", filename);
1163 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001164 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001165
1166 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001167 }
1168
1169 /**
1170 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1171 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1172 * Then it overwrites the original blob with the new blob
1173 * format that is returned from the keymaster.
1174 */
Kenny Root655b9582013-04-04 08:37:42 -07001175 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001176 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1177 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1178 if (b.get() == NULL) {
1179 ALOGE("Problem instantiating BIO");
1180 return SYSTEM_ERROR;
1181 }
1182
1183 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1184 if (pkey.get() == NULL) {
1185 ALOGE("Couldn't read old PEM file");
1186 return SYSTEM_ERROR;
1187 }
1188
1189 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1190 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1191 if (len < 0) {
1192 ALOGE("Couldn't measure PKCS#8 length");
1193 return SYSTEM_ERROR;
1194 }
1195
Kenny Root70c98892013-02-07 09:10:36 -08001196 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1197 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001198 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1199 ALOGE("Couldn't convert to PKCS#8");
1200 return SYSTEM_ERROR;
1201 }
1202
Kenny Root655b9582013-04-04 08:37:42 -07001203 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001204 if (rc != NO_ERROR) {
1205 return rc;
1206 }
1207
Kenny Root655b9582013-04-04 08:37:42 -07001208 return get(filename, blob, TYPE_KEY_PAIR, uid);
1209 }
1210
1211 void readMetaData() {
1212 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1213 if (in < 0) {
1214 return;
1215 }
1216 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1217 if (fileLength != sizeof(mMetaData)) {
1218 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1219 sizeof(mMetaData));
1220 }
1221 close(in);
1222 }
1223
1224 void writeMetaData() {
1225 const char* tmpFileName = ".metadata.tmp";
1226 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1227 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1228 if (out < 0) {
1229 ALOGE("couldn't write metadata file: %s", strerror(errno));
1230 return;
1231 }
1232 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1233 if (fileLength != sizeof(mMetaData)) {
1234 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1235 sizeof(mMetaData));
1236 }
1237 close(out);
1238 rename(tmpFileName, sMetaDataFile);
1239 }
1240
1241 bool upgradeKeystore() {
1242 bool upgraded = false;
1243
1244 if (mMetaData.version == 0) {
1245 UserState* userState = getUserState(0);
1246
1247 // Initialize first so the directory is made.
1248 userState->initialize();
1249
1250 // Migrate the old .masterkey file to user 0.
1251 if (access(sOldMasterKey, R_OK) == 0) {
1252 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1253 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1254 return false;
1255 }
1256 }
1257
1258 // Initialize again in case we had a key.
1259 userState->initialize();
1260
1261 // Try to migrate existing keys.
1262 DIR* dir = opendir(".");
1263 if (!dir) {
1264 // Give up now; maybe we can upgrade later.
1265 ALOGE("couldn't open keystore's directory; something is wrong");
1266 return false;
1267 }
1268
1269 struct dirent* file;
1270 while ((file = readdir(dir)) != NULL) {
1271 // We only care about files.
1272 if (file->d_type != DT_REG) {
1273 continue;
1274 }
1275
1276 // Skip anything that starts with a "."
1277 if (file->d_name[0] == '.') {
1278 continue;
1279 }
1280
1281 // Find the current file's user.
1282 char* end;
1283 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1284 if (end[0] != '_' || end[1] == 0) {
1285 continue;
1286 }
1287 UserState* otherUser = getUserState(thisUid);
1288 if (otherUser->getUserId() != 0) {
1289 unlinkat(dirfd(dir), file->d_name, 0);
1290 }
1291
1292 // Rename the file into user directory.
1293 DIR* otherdir = opendir(otherUser->getUserDirName());
1294 if (otherdir == NULL) {
1295 ALOGW("couldn't open user directory for rename");
1296 continue;
1297 }
1298 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1299 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1300 }
1301 closedir(otherdir);
1302 }
1303 closedir(dir);
1304
1305 mMetaData.version = 1;
1306 upgraded = true;
1307 }
1308
1309 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001310 }
Kenny Roota91203b2012-02-15 15:00:46 -08001311};
1312
Kenny Root655b9582013-04-04 08:37:42 -07001313const char* KeyStore::sOldMasterKey = ".masterkey";
1314const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001315
Kenny Root07438c82012-11-02 15:41:02 -07001316namespace android {
1317class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1318public:
1319 KeyStoreProxy(KeyStore* keyStore)
1320 : mKeyStore(keyStore)
1321 {
Kenny Roota91203b2012-02-15 15:00:46 -08001322 }
Kenny Roota91203b2012-02-15 15:00:46 -08001323
Kenny Root07438c82012-11-02 15:41:02 -07001324 void binderDied(const wp<IBinder>&) {
1325 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001326 }
Kenny Roota91203b2012-02-15 15:00:46 -08001327
Kenny Root07438c82012-11-02 15:41:02 -07001328 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001329 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1330 if (!has_permission(callingUid, P_TEST)) {
1331 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001332 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001333 }
Kenny Roota91203b2012-02-15 15:00:46 -08001334
Kenny Root655b9582013-04-04 08:37:42 -07001335 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001336 }
1337
Kenny Root07438c82012-11-02 15:41:02 -07001338 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001339 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1340 if (!has_permission(callingUid, P_GET)) {
1341 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001342 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001343 }
Kenny Root07438c82012-11-02 15:41:02 -07001344
Kenny Root655b9582013-04-04 08:37:42 -07001345 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001346 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001347 ALOGD("calling get in state: %d", state);
1348 return state;
Kenny Roota91203b2012-02-15 15:00:46 -08001349 }
Kenny Root07438c82012-11-02 15:41:02 -07001350
1351 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001352 Blob keyBlob;
Kenny Root49468902013-03-19 13:41:33 -07001353
Kenny Root655b9582013-04-04 08:37:42 -07001354 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001355 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001356 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001357 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001358 *item = NULL;
1359 *itemLength = 0;
1360 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001361 }
Kenny Roota91203b2012-02-15 15:00:46 -08001362
Kenny Root07438c82012-11-02 15:41:02 -07001363 *item = (uint8_t*) malloc(keyBlob.getLength());
1364 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1365 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001366
Kenny Root07438c82012-11-02 15:41:02 -07001367 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001368 }
1369
Kenny Root49468902013-03-19 13:41:33 -07001370 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001371 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1372 if (!has_permission(callingUid, P_INSERT)) {
1373 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001374 return ::PERMISSION_DENIED;
1375 }
Kenny Root07438c82012-11-02 15:41:02 -07001376
Kenny Root49468902013-03-19 13:41:33 -07001377 if (targetUid == -1) {
1378 targetUid = callingUid;
1379 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001380 return ::PERMISSION_DENIED;
1381 }
1382
Kenny Root655b9582013-04-04 08:37:42 -07001383 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001384 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001385 ALOGD("calling insert in state: %d", state);
1386 return state;
1387 }
1388
1389 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001390 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001391
1392 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Root655b9582013-04-04 08:37:42 -07001393 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001394 }
1395
Kenny Root49468902013-03-19 13:41:33 -07001396 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001397 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1398 if (!has_permission(callingUid, P_DELETE)) {
1399 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001400 return ::PERMISSION_DENIED;
1401 }
Kenny Root70e3a862012-02-15 17:20:23 -08001402
Kenny Root49468902013-03-19 13:41:33 -07001403 if (targetUid == -1) {
1404 targetUid = callingUid;
1405 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001406 return ::PERMISSION_DENIED;
1407 }
1408
Kenny Root07438c82012-11-02 15:41:02 -07001409 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001410 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001411
1412 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001413 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
1414 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001415 if (responseCode != ::NO_ERROR) {
1416 return responseCode;
1417 }
1418 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001419 }
1420
Kenny Root49468902013-03-19 13:41:33 -07001421 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001422 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1423 if (!has_permission(callingUid, P_EXIST)) {
1424 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001425 return ::PERMISSION_DENIED;
1426 }
Kenny Root70e3a862012-02-15 17:20:23 -08001427
Kenny Root49468902013-03-19 13:41:33 -07001428 if (targetUid == -1) {
1429 targetUid = callingUid;
1430 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001431 return ::PERMISSION_DENIED;
1432 }
1433
Kenny Root07438c82012-11-02 15:41:02 -07001434 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001435 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001436
Kenny Root655b9582013-04-04 08:37:42 -07001437 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001438 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1439 }
1440 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001441 }
1442
Kenny Root49468902013-03-19 13:41:33 -07001443 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001444 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1445 if (!has_permission(callingUid, P_SAW)) {
1446 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001447 return ::PERMISSION_DENIED;
1448 }
Kenny Root70e3a862012-02-15 17:20:23 -08001449
Kenny Root49468902013-03-19 13:41:33 -07001450 if (targetUid == -1) {
1451 targetUid = callingUid;
1452 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001453 return ::PERMISSION_DENIED;
1454 }
1455
Kenny Root655b9582013-04-04 08:37:42 -07001456 UserState* userState = mKeyStore->getUserState(targetUid);
1457 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001458 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07001459 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001460 return ::SYSTEM_ERROR;
1461 }
Kenny Root70e3a862012-02-15 17:20:23 -08001462
Kenny Root07438c82012-11-02 15:41:02 -07001463 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001464 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1465 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001466
Kenny Root07438c82012-11-02 15:41:02 -07001467 struct dirent* file;
1468 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001469 // We only care about files.
1470 if (file->d_type != DT_REG) {
1471 continue;
1472 }
1473
1474 // Skip anything that starts with a "."
1475 if (file->d_name[0] == '.') {
1476 continue;
1477 }
1478
1479 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001480 const char* p = &file->d_name[n];
1481 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001482
Kenny Root07438c82012-11-02 15:41:02 -07001483 size_t extra = decode_key_length(p, plen);
1484 char *match = (char*) malloc(extra + 1);
1485 if (match != NULL) {
1486 decode_key(match, p, plen);
1487 matches->push(String16(match, extra));
1488 free(match);
1489 } else {
1490 ALOGW("could not allocate match of size %zd", extra);
1491 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001492 }
1493 }
Kenny Root07438c82012-11-02 15:41:02 -07001494 closedir(dir);
1495
1496 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001497 }
1498
Kenny Root07438c82012-11-02 15:41:02 -07001499 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001500 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1501 if (!has_permission(callingUid, P_RESET)) {
1502 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001503 return ::PERMISSION_DENIED;
1504 }
1505
Kenny Root655b9582013-04-04 08:37:42 -07001506 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001507
1508 const keymaster_device_t* device = mKeyStore->getDevice();
1509 if (device == NULL) {
1510 ALOGE("No keymaster device!");
1511 return ::SYSTEM_ERROR;
1512 }
1513
1514 if (device->delete_all == NULL) {
1515 ALOGV("keymaster device doesn't implement delete_all");
1516 return rc;
1517 }
1518
1519 if (device->delete_all(device)) {
1520 ALOGE("Problem calling keymaster's delete_all");
1521 return ::SYSTEM_ERROR;
1522 }
1523
Kenny Root9a53d3e2012-08-14 10:47:54 -07001524 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001525 }
1526
Kenny Root07438c82012-11-02 15:41:02 -07001527 /*
1528 * Here is the history. To improve the security, the parameters to generate the
1529 * master key has been changed. To make a seamless transition, we update the
1530 * file using the same password when the user unlock it for the first time. If
1531 * any thing goes wrong during the transition, the new file will not overwrite
1532 * the old one. This avoids permanent damages of the existing data.
1533 */
1534 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001535 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1536 if (!has_permission(callingUid, P_PASSWORD)) {
1537 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001538 return ::PERMISSION_DENIED;
1539 }
Kenny Root70e3a862012-02-15 17:20:23 -08001540
Kenny Root07438c82012-11-02 15:41:02 -07001541 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001542
Kenny Root655b9582013-04-04 08:37:42 -07001543 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001544 case ::STATE_UNINITIALIZED: {
1545 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001546 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001547 }
1548 case ::STATE_NO_ERROR: {
1549 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001550 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001551 }
1552 case ::STATE_LOCKED: {
1553 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001554 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001555 }
1556 }
1557 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001558 }
1559
Kenny Root07438c82012-11-02 15:41:02 -07001560 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001561 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1562 if (!has_permission(callingUid, P_LOCK)) {
1563 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001564 return ::PERMISSION_DENIED;
1565 }
Kenny Root70e3a862012-02-15 17:20:23 -08001566
Kenny Root655b9582013-04-04 08:37:42 -07001567 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001568 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001569 ALOGD("calling lock in state: %d", state);
1570 return state;
1571 }
1572
Kenny Root655b9582013-04-04 08:37:42 -07001573 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001574 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001575 }
1576
Kenny Root07438c82012-11-02 15:41:02 -07001577 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001578 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1579 if (!has_permission(callingUid, P_UNLOCK)) {
1580 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001581 return ::PERMISSION_DENIED;
1582 }
1583
Kenny Root655b9582013-04-04 08:37:42 -07001584 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001585 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001586 ALOGD("calling unlock when not locked");
1587 return state;
1588 }
1589
1590 const String8 password8(pw);
1591 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001592 }
1593
Kenny Root07438c82012-11-02 15:41:02 -07001594 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001595 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1596 if (!has_permission(callingUid, P_ZERO)) {
1597 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001598 return -1;
1599 }
Kenny Root70e3a862012-02-15 17:20:23 -08001600
Kenny Root655b9582013-04-04 08:37:42 -07001601 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001602 }
1603
Kenny Root49468902013-03-19 13:41:33 -07001604 int32_t generate(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001605 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1606 if (!has_permission(callingUid, P_INSERT)) {
1607 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001608 return ::PERMISSION_DENIED;
1609 }
Kenny Root70e3a862012-02-15 17:20:23 -08001610
Kenny Root49468902013-03-19 13:41:33 -07001611 if (targetUid == -1) {
1612 targetUid = callingUid;
1613 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001614 return ::PERMISSION_DENIED;
1615 }
1616
Kenny Root655b9582013-04-04 08:37:42 -07001617 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001618 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001619 ALOGD("calling generate in state: %d", state);
1620 return state;
1621 }
Kenny Root70e3a862012-02-15 17:20:23 -08001622
Kenny Root07438c82012-11-02 15:41:02 -07001623 uint8_t* data;
1624 size_t dataLength;
1625 int rc;
1626
1627 const keymaster_device_t* device = mKeyStore->getDevice();
1628 if (device == NULL) {
1629 return ::SYSTEM_ERROR;
1630 }
1631
1632 if (device->generate_keypair == NULL) {
1633 return ::SYSTEM_ERROR;
1634 }
1635
1636 keymaster_rsa_keygen_params_t rsa_params;
1637 rsa_params.modulus_size = 2048;
1638 rsa_params.public_exponent = 0x10001;
1639
1640 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1641 if (rc) {
1642 return ::SYSTEM_ERROR;
1643 }
1644
Kenny Root655b9582013-04-04 08:37:42 -07001645 String8 name8(name);
1646 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001647
1648 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1649 free(data);
1650
Kenny Root655b9582013-04-04 08:37:42 -07001651 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001652 }
1653
Kenny Root49468902013-03-19 13:41:33 -07001654 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001655 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1656 if (!has_permission(callingUid, P_INSERT)) {
1657 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001658 return ::PERMISSION_DENIED;
1659 }
Kenny Root07438c82012-11-02 15:41:02 -07001660
Kenny Root49468902013-03-19 13:41:33 -07001661 if (targetUid == -1) {
1662 targetUid = callingUid;
1663 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001664 return ::PERMISSION_DENIED;
1665 }
1666
Kenny Root655b9582013-04-04 08:37:42 -07001667 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001668 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001669 ALOGD("calling import in state: %d", state);
1670 return state;
1671 }
1672
1673 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001674 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001675
Kenny Root655b9582013-04-04 08:37:42 -07001676 return mKeyStore->importKey(data, length, filename.string(), callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001677 }
1678
Kenny Root07438c82012-11-02 15:41:02 -07001679 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1680 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001681 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1682 if (!has_permission(callingUid, P_SIGN)) {
1683 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001684 return ::PERMISSION_DENIED;
1685 }
Kenny Root07438c82012-11-02 15:41:02 -07001686
Kenny Root655b9582013-04-04 08:37:42 -07001687 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001688 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001689 ALOGD("calling sign in state: %d", state);
1690 return state;
1691 }
1692
1693 Blob keyBlob;
1694 String8 name8(name);
1695
Kenny Rootd38a0b02013-02-13 12:59:14 -08001696 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001697 int rc;
1698
Kenny Root655b9582013-04-04 08:37:42 -07001699 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001700 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001701 if (responseCode != ::NO_ERROR) {
1702 return responseCode;
1703 }
1704
1705 const keymaster_device_t* device = mKeyStore->getDevice();
1706 if (device == NULL) {
1707 ALOGE("no keymaster device; cannot sign");
1708 return ::SYSTEM_ERROR;
1709 }
1710
1711 if (device->sign_data == NULL) {
1712 ALOGE("device doesn't implement signing");
1713 return ::SYSTEM_ERROR;
1714 }
1715
1716 keymaster_rsa_sign_params_t params;
1717 params.digest_type = DIGEST_NONE;
1718 params.padding_type = PADDING_NONE;
1719
1720 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1721 data, length, out, outLength);
1722 if (rc) {
1723 ALOGW("device couldn't sign data");
1724 return ::SYSTEM_ERROR;
1725 }
1726
1727 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001728 }
1729
Kenny Root07438c82012-11-02 15:41:02 -07001730 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1731 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001732 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1733 if (!has_permission(callingUid, P_VERIFY)) {
1734 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001735 return ::PERMISSION_DENIED;
1736 }
Kenny Root70e3a862012-02-15 17:20:23 -08001737
Kenny Root655b9582013-04-04 08:37:42 -07001738 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001739 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001740 ALOGD("calling verify in state: %d", state);
1741 return state;
1742 }
Kenny Root70e3a862012-02-15 17:20:23 -08001743
Kenny Root07438c82012-11-02 15:41:02 -07001744 Blob keyBlob;
1745 String8 name8(name);
1746 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001747
Kenny Root655b9582013-04-04 08:37:42 -07001748 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001749 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001750 if (responseCode != ::NO_ERROR) {
1751 return responseCode;
1752 }
Kenny Root70e3a862012-02-15 17:20:23 -08001753
Kenny Root07438c82012-11-02 15:41:02 -07001754 const keymaster_device_t* device = mKeyStore->getDevice();
1755 if (device == NULL) {
1756 return ::SYSTEM_ERROR;
1757 }
Kenny Root70e3a862012-02-15 17:20:23 -08001758
Kenny Root07438c82012-11-02 15:41:02 -07001759 if (device->verify_data == NULL) {
1760 return ::SYSTEM_ERROR;
1761 }
Kenny Root70e3a862012-02-15 17:20:23 -08001762
Kenny Root07438c82012-11-02 15:41:02 -07001763 keymaster_rsa_sign_params_t params;
1764 params.digest_type = DIGEST_NONE;
1765 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001766
Kenny Root07438c82012-11-02 15:41:02 -07001767 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1768 data, dataLength, signature, signatureLength);
1769 if (rc) {
1770 return ::SYSTEM_ERROR;
1771 } else {
1772 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001773 }
1774 }
Kenny Root07438c82012-11-02 15:41:02 -07001775
1776 /*
1777 * TODO: The abstraction between things stored in hardware and regular blobs
1778 * of data stored on the filesystem should be moved down to keystore itself.
1779 * Unfortunately the Java code that calls this has naming conventions that it
1780 * knows about. Ideally keystore shouldn't be used to store random blobs of
1781 * data.
1782 *
1783 * Until that happens, it's necessary to have a separate "get_pubkey" and
1784 * "del_key" since the Java code doesn't really communicate what it's
1785 * intentions are.
1786 */
1787 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001788 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1789 if (!has_permission(callingUid, P_GET)) {
1790 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001791 return ::PERMISSION_DENIED;
1792 }
Kenny Root07438c82012-11-02 15:41:02 -07001793
Kenny Root655b9582013-04-04 08:37:42 -07001794 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001795 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001796 ALOGD("calling get_pubkey in state: %d", state);
1797 return state;
1798 }
1799
1800 Blob keyBlob;
1801 String8 name8(name);
1802
Kenny Rootd38a0b02013-02-13 12:59:14 -08001803 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001804
Kenny Root655b9582013-04-04 08:37:42 -07001805 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07001806 TYPE_KEY_PAIR);
1807 if (responseCode != ::NO_ERROR) {
1808 return responseCode;
1809 }
1810
1811 const keymaster_device_t* device = mKeyStore->getDevice();
1812 if (device == NULL) {
1813 return ::SYSTEM_ERROR;
1814 }
1815
1816 if (device->get_keypair_public == NULL) {
1817 ALOGE("device has no get_keypair_public implementation!");
1818 return ::SYSTEM_ERROR;
1819 }
1820
1821 int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
1822 pubkeyLength);
1823 if (rc) {
1824 return ::SYSTEM_ERROR;
1825 }
1826
1827 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001828 }
Kenny Root07438c82012-11-02 15:41:02 -07001829
Kenny Root49468902013-03-19 13:41:33 -07001830 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001831 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1832 if (!has_permission(callingUid, P_DELETE)) {
1833 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001834 return ::PERMISSION_DENIED;
1835 }
Kenny Root07438c82012-11-02 15:41:02 -07001836
Kenny Root49468902013-03-19 13:41:33 -07001837 if (targetUid == -1) {
1838 targetUid = callingUid;
1839 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001840 return ::PERMISSION_DENIED;
1841 }
1842
Kenny Root07438c82012-11-02 15:41:02 -07001843 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001844 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001845
1846 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001847 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
1848 callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001849 if (responseCode != ::NO_ERROR) {
1850 return responseCode;
1851 }
1852
1853 ResponseCode rc = ::NO_ERROR;
1854
1855 const keymaster_device_t* device = mKeyStore->getDevice();
1856 if (device == NULL) {
1857 rc = ::SYSTEM_ERROR;
1858 } else {
1859 // A device doesn't have to implement delete_keypair.
1860 if (device->delete_keypair != NULL) {
1861 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1862 rc = ::SYSTEM_ERROR;
1863 }
1864 }
1865 }
1866
1867 if (rc != ::NO_ERROR) {
1868 return rc;
1869 }
1870
1871 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1872 }
1873
1874 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001875 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1876 if (!has_permission(callingUid, P_GRANT)) {
1877 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001878 return ::PERMISSION_DENIED;
1879 }
Kenny Root07438c82012-11-02 15:41:02 -07001880
Kenny Root655b9582013-04-04 08:37:42 -07001881 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001882 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001883 ALOGD("calling grant in state: %d", state);
1884 return state;
1885 }
1886
1887 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
Kenny Root655b9582013-04-04 08:37:42 -07001890 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001891 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1892 }
1893
Kenny Root655b9582013-04-04 08:37:42 -07001894 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07001895 return ::NO_ERROR;
1896 }
1897
1898 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001899 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1900 if (!has_permission(callingUid, P_GRANT)) {
1901 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001902 return ::PERMISSION_DENIED;
1903 }
Kenny Root07438c82012-11-02 15:41:02 -07001904
Kenny Root655b9582013-04-04 08:37:42 -07001905 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001906 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001907 ALOGD("calling ungrant in state: %d", state);
1908 return state;
1909 }
1910
1911 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001912 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001913
Kenny Root655b9582013-04-04 08:37:42 -07001914 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001915 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1916 }
1917
Kenny Root655b9582013-04-04 08:37:42 -07001918 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07001919 }
1920
1921 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001922 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1923 if (!has_permission(callingUid, P_GET)) {
1924 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08001925 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001926 }
Kenny Root07438c82012-11-02 15:41:02 -07001927
1928 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001929 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001930
Kenny Root655b9582013-04-04 08:37:42 -07001931 if (access(filename.string(), R_OK) == -1) {
1932 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08001933 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001934 }
1935
Kenny Root655b9582013-04-04 08:37:42 -07001936 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07001937 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07001938 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08001939 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001940 }
1941
1942 struct stat s;
1943 int ret = fstat(fd, &s);
1944 close(fd);
1945 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07001946 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08001947 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001948 }
1949
Kenny Root36a9e232013-02-04 14:24:15 -08001950 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07001951 }
1952
Kenny Rootd53bc922013-03-21 14:10:15 -07001953 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
1954 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07001955 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Rootd53bc922013-03-21 14:10:15 -07001956 if (!has_permission(callingUid, P_DUPLICATE)) {
1957 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07001958 return -1L;
1959 }
1960
Kenny Root655b9582013-04-04 08:37:42 -07001961 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07001962 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07001963 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07001964 return state;
1965 }
1966
Kenny Rootd53bc922013-03-21 14:10:15 -07001967 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
1968 srcUid = callingUid;
1969 } else if (!is_granted_to(callingUid, srcUid)) {
1970 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07001971 return ::PERMISSION_DENIED;
1972 }
1973
Kenny Rootd53bc922013-03-21 14:10:15 -07001974 if (destUid == -1) {
1975 destUid = callingUid;
1976 }
1977
1978 if (srcUid != destUid) {
1979 if (static_cast<uid_t>(srcUid) != callingUid) {
1980 ALOGD("can only duplicate from caller to other or to same uid: "
1981 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
1982 return ::PERMISSION_DENIED;
1983 }
1984
1985 if (!is_granted_to(callingUid, destUid)) {
1986 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
1987 return ::PERMISSION_DENIED;
1988 }
1989 }
1990
1991 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07001992 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07001993
Kenny Rootd53bc922013-03-21 14:10:15 -07001994 String8 target8(destKey);
Kenny Root655b9582013-04-04 08:37:42 -07001995 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07001996
Kenny Root655b9582013-04-04 08:37:42 -07001997 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
1998 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07001999 return ::SYSTEM_ERROR;
2000 }
2001
Kenny Rootd53bc922013-03-21 14:10:15 -07002002 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002003 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
2004 callingUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002005 if (responseCode != ::NO_ERROR) {
2006 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002007 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002008
Kenny Root655b9582013-04-04 08:37:42 -07002009 return mKeyStore->put(targetFile.string(), &keyBlob, callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002010 }
2011
Kenny Root8ddf35a2013-03-29 11:15:50 -07002012 int32_t is_hardware_backed() {
2013 return mKeyStore->isHardwareBacked() ? 1 : 0;
2014 }
2015
Kenny Roota9bb5492013-04-01 16:29:11 -07002016 int32_t clear_uid(int64_t targetUid) {
2017 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2018 if (!has_permission(callingUid, P_CLEAR_UID)) {
2019 ALOGW("permission denied for %d: clear_uid", callingUid);
2020 return ::PERMISSION_DENIED;
2021 }
2022
Kenny Root655b9582013-04-04 08:37:42 -07002023 State state = mKeyStore->getState(callingUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002024 if (!isKeystoreUnlocked(state)) {
2025 ALOGD("calling clear_uid in state: %d", state);
2026 return state;
2027 }
2028
2029 const keymaster_device_t* device = mKeyStore->getDevice();
2030 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002031 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002032 return ::SYSTEM_ERROR;
2033 }
2034
Kenny Root655b9582013-04-04 08:37:42 -07002035 UserState* userState = mKeyStore->getUserState(callingUid);
2036 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota9bb5492013-04-01 16:29:11 -07002037 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07002038 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Roota9bb5492013-04-01 16:29:11 -07002039 return ::SYSTEM_ERROR;
2040 }
2041
Kenny Root655b9582013-04-04 08:37:42 -07002042 char prefix[NAME_MAX];
2043 int n = snprintf(prefix, NAME_MAX, "%u_", static_cast<uid_t>(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002044
2045 ResponseCode rc = ::NO_ERROR;
2046
2047 struct dirent* file;
2048 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002049 // We only care about files.
2050 if (file->d_type != DT_REG) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002051 continue;
2052 }
2053
Kenny Root655b9582013-04-04 08:37:42 -07002054 // Skip anything that starts with a "."
2055 if (file->d_name[0] == '.') {
2056 continue;
2057 }
Kenny Roota9bb5492013-04-01 16:29:11 -07002058
Kenny Root655b9582013-04-04 08:37:42 -07002059 if (strncmp(prefix, file->d_name, n)) {
2060 continue;
2061 }
2062
2063 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Roota9bb5492013-04-01 16:29:11 -07002064 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002065 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, callingUid)
2066 != ::NO_ERROR) {
2067 ALOGW("couldn't open %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002068 continue;
2069 }
2070
2071 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2072 // A device doesn't have to implement delete_keypair.
2073 if (device->delete_keypair != NULL) {
2074 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2075 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002076 ALOGW("device couldn't remove %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002077 }
2078 }
2079 }
2080
Kenny Root655b9582013-04-04 08:37:42 -07002081 if (unlinkat(dirfd(dir), filename.string(), 0) && errno != ENOENT) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002082 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002083 ALOGW("couldn't unlink %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002084 }
2085 }
2086 closedir(dir);
2087
2088 return rc;
2089 }
2090
Kenny Root07438c82012-11-02 15:41:02 -07002091private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002092 inline bool isKeystoreUnlocked(State state) {
2093 switch (state) {
2094 case ::STATE_NO_ERROR:
2095 return true;
2096 case ::STATE_UNINITIALIZED:
2097 case ::STATE_LOCKED:
2098 return false;
2099 }
2100 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002101 }
2102
2103 ::KeyStore* mKeyStore;
2104};
2105
2106}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002107
2108int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002109 if (argc < 2) {
2110 ALOGE("A directory must be specified!");
2111 return 1;
2112 }
2113 if (chdir(argv[1]) == -1) {
2114 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2115 return 1;
2116 }
2117
2118 Entropy entropy;
2119 if (!entropy.open()) {
2120 return 1;
2121 }
Kenny Root70e3a862012-02-15 17:20:23 -08002122
2123 keymaster_device_t* dev;
2124 if (keymaster_device_initialize(&dev)) {
2125 ALOGE("keystore keymaster could not be initialized; exiting");
2126 return 1;
2127 }
2128
Kenny Root70e3a862012-02-15 17:20:23 -08002129 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002130 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002131 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2132 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2133 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2134 if (ret != android::OK) {
2135 ALOGE("Couldn't register binder service!");
2136 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002137 }
Kenny Root07438c82012-11-02 15:41:02 -07002138
2139 /*
2140 * We're the only thread in existence, so we're just going to process
2141 * Binder transaction as a single-threaded program.
2142 */
2143 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002144
2145 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002146 return 1;
2147}