blob: 09bcf335bdd935c8b66b77c69d3e5d64c22b4306 [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>
27#include <fcntl.h>
28#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070029#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080030#include <sys/types.h>
31#include <sys/socket.h>
32#include <sys/stat.h>
33#include <sys/time.h>
34#include <arpa/inet.h>
35
36#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070037#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080038#include <openssl/evp.h>
39#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070040#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080041
Kenny Root70e3a862012-02-15 17:20:23 -080042#include <hardware/keymaster.h>
43
Kenny Root822c3a92012-03-23 16:34:39 -070044#include <utils/UniquePtr.h>
45
Kenny Root70e3a862012-02-15 17:20:23 -080046#include <cutils/list.h>
47
Kenny Root07438c82012-11-02 15:41:02 -070048#include <keystore/IKeystoreService.h>
49#include <binder/IPCThreadState.h>
50#include <binder/IServiceManager.h>
51
Kenny Roota91203b2012-02-15 15:00:46 -080052#include <cutils/log.h>
53#include <cutils/sockets.h>
54#include <private/android_filesystem_config.h>
55
Kenny Root07438c82012-11-02 15:41:02 -070056#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080057
58/* KeyStore is a secured storage for key-value pairs. In this implementation,
59 * each file stores one key-value pair. Keys are encoded in file names, and
60 * values are encrypted with checksums. The encryption key is protected by a
61 * user-defined password. To keep things simple, buffers are always larger than
62 * the maximum space we needed, so boundary checks on buffers are omitted. */
63
64#define KEY_SIZE ((NAME_MAX - 15) / 2)
65#define VALUE_SIZE 32768
66#define PASSWORD_SIZE VALUE_SIZE
67
Kenny Root822c3a92012-03-23 16:34:39 -070068
69struct BIO_Delete {
70 void operator()(BIO* p) const {
71 BIO_free(p);
72 }
73};
74typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
75
76struct EVP_PKEY_Delete {
77 void operator()(EVP_PKEY* p) const {
78 EVP_PKEY_free(p);
79 }
80};
81typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
82
83struct PKCS8_PRIV_KEY_INFO_Delete {
84 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
85 PKCS8_PRIV_KEY_INFO_free(p);
86 }
87};
88typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
89
90
Kenny Root70e3a862012-02-15 17:20:23 -080091static int keymaster_device_initialize(keymaster_device_t** dev) {
92 int rc;
93
94 const hw_module_t* mod;
95 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
96 if (rc) {
97 ALOGE("could not find any keystore module");
98 goto out;
99 }
100
101 rc = keymaster_open(mod, dev);
102 if (rc) {
103 ALOGE("could not open keymaster device in %s (%s)",
104 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
105 goto out;
106 }
107
108 return 0;
109
110out:
111 *dev = NULL;
112 return rc;
113}
114
115static void keymaster_device_release(keymaster_device_t* dev) {
116 keymaster_close(dev);
117}
118
Kenny Root07438c82012-11-02 15:41:02 -0700119/***************
120 * PERMISSIONS *
121 ***************/
122
123/* Here are the permissions, actions, users, and the main function. */
124typedef enum {
125 P_TEST = 1 << 0,
126 P_GET = 1 << 1,
127 P_INSERT = 1 << 2,
128 P_DELETE = 1 << 3,
129 P_EXIST = 1 << 4,
130 P_SAW = 1 << 5,
131 P_RESET = 1 << 6,
132 P_PASSWORD = 1 << 7,
133 P_LOCK = 1 << 8,
134 P_UNLOCK = 1 << 9,
135 P_ZERO = 1 << 10,
136 P_SIGN = 1 << 11,
137 P_VERIFY = 1 << 12,
138 P_GRANT = 1 << 13,
139} perm_t;
140
141static struct user_euid {
142 uid_t uid;
143 uid_t euid;
144} user_euids[] = {
145 {AID_VPN, AID_SYSTEM},
146 {AID_WIFI, AID_SYSTEM},
147 {AID_ROOT, AID_SYSTEM},
148};
149
150static struct user_perm {
151 uid_t uid;
152 perm_t perms;
153} user_perms[] = {
154 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
155 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
156 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
157 {AID_ROOT, static_cast<perm_t>(P_GET) },
158};
159
160static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
161 | P_VERIFY);
162
163static bool has_permission(uid_t uid, perm_t perm) {
164 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
165 struct user_perm user = user_perms[i];
166 if (user.uid == uid) {
167 return user.perms & perm;
168 }
169 }
170
171 return DEFAULT_PERMS & perm;
172}
173
Kenny Root49468902013-03-19 13:41:33 -0700174/**
175 * Returns the UID that the callingUid should act as. This is here for
176 * legacy support of the WiFi and VPN systems and should be removed
177 * when WiFi can operate in its own namespace.
178 */
Kenny Root07438c82012-11-02 15:41:02 -0700179static uid_t get_keystore_euid(uid_t uid) {
180 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
181 struct user_euid user = user_euids[i];
182 if (user.uid == uid) {
183 return user.euid;
184 }
185 }
186
187 return uid;
188}
189
Kenny Root49468902013-03-19 13:41:33 -0700190/**
191 * Returns true if the callingUid is allowed to interact in the targetUid's
192 * namespace.
193 */
194static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
195 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
196 struct user_euid user = user_euids[i];
197 if (user.euid == callingUid && user.uid == targetUid) {
198 return true;
199 }
200 }
201
202 return false;
203}
204
Kenny Roota91203b2012-02-15 15:00:46 -0800205/* Here is the encoding of keys. This is necessary in order to allow arbitrary
206 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
207 * into two bytes. The first byte is one of [+-.] which represents the first
208 * two bits of the character. The second byte encodes the rest of the bits into
209 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
210 * that Base64 cannot be used here due to the need of prefix match on keys. */
211
Kenny Root07438c82012-11-02 15:41:02 -0700212static int encode_key(char* out, const android::String8& keyName) {
213 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
214 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800215 for (int i = length; i > 0; --i, ++in, ++out) {
216 if (*in >= '0' && *in <= '~') {
217 *out = *in;
218 } else {
219 *out = '+' + (*in >> 6);
220 *++out = '0' + (*in & 0x3F);
221 ++length;
222 }
223 }
224 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800225 return length;
226}
227
Kenny Root07438c82012-11-02 15:41:02 -0700228static int encode_key_for_uid(char* out, uid_t uid, const android::String8& keyName) {
Kenny Root70e3a862012-02-15 17:20:23 -0800229 int n = snprintf(out, NAME_MAX, "%u_", uid);
230 out += n;
231
Kenny Root07438c82012-11-02 15:41:02 -0700232 return n + encode_key(out, keyName);
Kenny Roota91203b2012-02-15 15:00:46 -0800233}
234
Kenny Root07438c82012-11-02 15:41:02 -0700235/*
236 * Converts from the "escaped" format on disk to actual name.
237 * This will be smaller than the input string.
238 *
239 * Characters that should combine with the next at the end will be truncated.
240 */
241static size_t decode_key_length(const char* in, size_t length) {
242 size_t outLength = 0;
243
244 for (const char* end = in + length; in < end; in++) {
245 /* This combines with the next character. */
246 if (*in < '0' || *in > '~') {
247 continue;
248 }
249
250 outLength++;
251 }
252 return outLength;
253}
254
255static void decode_key(char* out, const char* in, size_t length) {
256 for (const char* end = in + length; in < end; in++) {
257 if (*in < '0' || *in > '~') {
258 /* Truncate combining characters at the end. */
259 if (in + 1 >= end) {
260 break;
261 }
262
263 *out = (*in++ - '+') << 6;
264 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800265 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700266 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800267 }
268 }
269 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800270}
271
272static size_t readFully(int fd, uint8_t* data, size_t size) {
273 size_t remaining = size;
274 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800275 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800276 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800277 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800278 }
279 data += n;
280 remaining -= n;
281 }
282 return size;
283}
284
285static size_t writeFully(int fd, uint8_t* data, size_t size) {
286 size_t remaining = size;
287 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800288 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
289 if (n < 0) {
290 ALOGW("write failed: %s", strerror(errno));
291 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800292 }
293 data += n;
294 remaining -= n;
295 }
296 return size;
297}
298
299class Entropy {
300public:
301 Entropy() : mRandom(-1) {}
302 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800303 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800304 close(mRandom);
305 }
306 }
307
308 bool open() {
309 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800310 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
311 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800312 ALOGE("open: %s: %s", randomDevice, strerror(errno));
313 return false;
314 }
315 return true;
316 }
317
Kenny Root51878182012-03-13 12:53:19 -0700318 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800319 return (readFully(mRandom, data, size) == size);
320 }
321
322private:
323 int mRandom;
324};
325
326/* Here is the file format. There are two parts in blob.value, the secret and
327 * the description. The secret is stored in ciphertext, and its original size
328 * can be found in blob.length. The description is stored after the secret in
329 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700330 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
331 * the second is the blob's type, and the third byte is reserved. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800332 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
333 * and decryptBlob(). Thus they should not be accessed from outside. */
334
Kenny Root822c3a92012-03-23 16:34:39 -0700335/* ** Note to future implementors of encryption: **
336 * Currently this is the construction:
337 * metadata || Enc(MD5(data) || data)
338 *
339 * This should be the construction used for encrypting if re-implementing:
340 *
341 * Derive independent keys for encryption and MAC:
342 * Kenc = AES_encrypt(masterKey, "Encrypt")
343 * Kmac = AES_encrypt(masterKey, "MAC")
344 *
345 * Store this:
346 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
347 * HMAC(Kmac, metadata || Enc(data))
348 */
Kenny Roota91203b2012-02-15 15:00:46 -0800349struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700350 uint8_t version;
351 uint8_t type;
352 uint8_t reserved;
Kenny Roota91203b2012-02-15 15:00:46 -0800353 uint8_t info;
354 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700355 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800356 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700357 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800358 int32_t length; // in network byte order when encrypted
359 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
360};
361
Kenny Root822c3a92012-03-23 16:34:39 -0700362typedef enum {
363 TYPE_GENERIC = 1,
364 TYPE_MASTER_KEY = 2,
365 TYPE_KEY_PAIR = 3,
366} BlobType;
367
Kenny Root07438c82012-11-02 15:41:02 -0700368static const uint8_t CURRENT_BLOB_VERSION = 1;
Kenny Root822c3a92012-03-23 16:34:39 -0700369
Kenny Roota91203b2012-02-15 15:00:46 -0800370class Blob {
371public:
Kenny Root07438c82012-11-02 15:41:02 -0700372 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
373 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800374 mBlob.length = valueLength;
375 memcpy(mBlob.value, value, valueLength);
376
377 mBlob.info = infoLength;
378 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700379
Kenny Root07438c82012-11-02 15:41:02 -0700380 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700381 mBlob.type = uint8_t(type);
Kenny Roota91203b2012-02-15 15:00:46 -0800382 }
383
384 Blob(blob b) {
385 mBlob = b;
386 }
387
388 Blob() {}
389
Kenny Root51878182012-03-13 12:53:19 -0700390 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800391 return mBlob.value;
392 }
393
Kenny Root51878182012-03-13 12:53:19 -0700394 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800395 return mBlob.length;
396 }
397
Kenny Root51878182012-03-13 12:53:19 -0700398 const uint8_t* getInfo() const {
399 return mBlob.value + mBlob.length;
400 }
401
402 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800403 return mBlob.info;
404 }
405
Kenny Root822c3a92012-03-23 16:34:39 -0700406 uint8_t getVersion() const {
407 return mBlob.version;
408 }
409
410 void setVersion(uint8_t version) {
411 mBlob.version = version;
412 }
413
414 BlobType getType() const {
415 return BlobType(mBlob.type);
416 }
417
418 void setType(BlobType type) {
419 mBlob.type = uint8_t(type);
420 }
421
Kenny Roota91203b2012-02-15 15:00:46 -0800422 ResponseCode encryptBlob(const char* filename, AES_KEY *aes_key, Entropy* entropy) {
423 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
Kenny Root150ca932012-11-14 14:29:02 -0800424 ALOGW("Could not read random data for: %s", filename);
Kenny Roota91203b2012-02-15 15:00:46 -0800425 return SYSTEM_ERROR;
426 }
427
428 // data includes the value and the value's length
429 size_t dataLength = mBlob.length + sizeof(mBlob.length);
430 // pad data to the AES_BLOCK_SIZE
431 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
432 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
433 // encrypted data includes the digest value
434 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
435 // move info after space for padding
436 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
437 // zero padding area
438 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
439
440 mBlob.length = htonl(mBlob.length);
441 MD5(mBlob.digested, digestedLength, mBlob.digest);
442
443 uint8_t vector[AES_BLOCK_SIZE];
444 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
445 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
446 aes_key, vector, AES_ENCRYPT);
447
Kenny Root822c3a92012-03-23 16:34:39 -0700448 mBlob.reserved = 0;
Kenny Roota91203b2012-02-15 15:00:46 -0800449 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
450 size_t fileLength = encryptedLength + headerLength + mBlob.info;
451
452 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800453 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
454 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
455 if (out < 0) {
456 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800457 return SYSTEM_ERROR;
458 }
459 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
460 if (close(out) != 0) {
461 return SYSTEM_ERROR;
462 }
463 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800464 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800465 unlink(tmpFileName);
466 return SYSTEM_ERROR;
467 }
Kenny Root150ca932012-11-14 14:29:02 -0800468 if (rename(tmpFileName, filename) == -1) {
469 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
470 return SYSTEM_ERROR;
471 }
472 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800473 }
474
475 ResponseCode decryptBlob(const char* filename, AES_KEY *aes_key) {
Kenny Root150ca932012-11-14 14:29:02 -0800476 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
477 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800478 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
479 }
480 // fileLength may be less than sizeof(mBlob) since the in
481 // memory version has extra padding to tolerate rounding up to
482 // the AES_BLOCK_SIZE
483 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
484 if (close(in) != 0) {
485 return SYSTEM_ERROR;
486 }
487 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
488 if (fileLength < headerLength) {
489 return VALUE_CORRUPTED;
490 }
491
492 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
493 if (encryptedLength < 0 || encryptedLength % AES_BLOCK_SIZE != 0) {
494 return VALUE_CORRUPTED;
495 }
496 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
497 mBlob.vector, AES_DECRYPT);
498 size_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
499 uint8_t computedDigest[MD5_DIGEST_LENGTH];
500 MD5(mBlob.digested, digestedLength, computedDigest);
501 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
502 return VALUE_CORRUPTED;
503 }
504
505 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
506 mBlob.length = ntohl(mBlob.length);
507 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
508 return VALUE_CORRUPTED;
509 }
510 if (mBlob.info != 0) {
511 // move info from after padding to after data
512 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
513 }
Kenny Root07438c82012-11-02 15:41:02 -0700514 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800515 }
516
517private:
518 struct blob mBlob;
519};
520
Kenny Root70e3a862012-02-15 17:20:23 -0800521typedef struct {
522 uint32_t uid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700523 const uint8_t* filename;
Kenny Root70e3a862012-02-15 17:20:23 -0800524
525 struct listnode plist;
526} grant_t;
527
Kenny Roota91203b2012-02-15 15:00:46 -0800528class KeyStore {
529public:
Kenny Root70e3a862012-02-15 17:20:23 -0800530 KeyStore(Entropy* entropy, keymaster_device_t* device)
Kenny Root51878182012-03-13 12:53:19 -0700531 : mEntropy(entropy)
Kenny Root70e3a862012-02-15 17:20:23 -0800532 , mDevice(device)
Kenny Root51878182012-03-13 12:53:19 -0700533 , mRetry(MAX_RETRY)
534 {
Kenny Roota91203b2012-02-15 15:00:46 -0800535 if (access(MASTER_KEY_FILE, R_OK) == 0) {
536 setState(STATE_LOCKED);
537 } else {
538 setState(STATE_UNINITIALIZED);
539 }
Kenny Root70e3a862012-02-15 17:20:23 -0800540
541 list_init(&mGrants);
Kenny Roota91203b2012-02-15 15:00:46 -0800542 }
543
Kenny Root51878182012-03-13 12:53:19 -0700544 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800545 return mState;
546 }
547
Kenny Root51878182012-03-13 12:53:19 -0700548 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800549 return mRetry;
550 }
551
Kenny Root70e3a862012-02-15 17:20:23 -0800552 keymaster_device_t* getDevice() const {
553 return mDevice;
554 }
555
Kenny Root07438c82012-11-02 15:41:02 -0700556 ResponseCode initialize(const android::String8& pw) {
Kenny Roota91203b2012-02-15 15:00:46 -0800557 if (!generateMasterKey()) {
558 return SYSTEM_ERROR;
559 }
560 ResponseCode response = writeMasterKey(pw);
561 if (response != NO_ERROR) {
562 return response;
563 }
564 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700565 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800566 }
567
Kenny Root07438c82012-11-02 15:41:02 -0700568 ResponseCode writeMasterKey(const android::String8& pw) {
Kenny Roota91203b2012-02-15 15:00:46 -0800569 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
570 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
571 AES_KEY passwordAesKey;
572 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700573 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Roota91203b2012-02-15 15:00:46 -0800574 return masterKeyBlob.encryptBlob(MASTER_KEY_FILE, &passwordAesKey, mEntropy);
575 }
576
Kenny Root07438c82012-11-02 15:41:02 -0700577 ResponseCode readMasterKey(const android::String8& pw) {
Kenny Root150ca932012-11-14 14:29:02 -0800578 int in = TEMP_FAILURE_RETRY(open(MASTER_KEY_FILE, O_RDONLY));
579 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800580 return SYSTEM_ERROR;
581 }
582
583 // we read the raw blob to just to get the salt to generate
584 // the AES key, then we create the Blob to use with decryptBlob
585 blob rawBlob;
586 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
587 if (close(in) != 0) {
588 return SYSTEM_ERROR;
589 }
590 // find salt at EOF if present, otherwise we have an old file
591 uint8_t* salt;
592 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
593 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
594 } else {
595 salt = NULL;
596 }
597 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
598 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
599 AES_KEY passwordAesKey;
600 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
601 Blob masterKeyBlob(rawBlob);
602 ResponseCode response = masterKeyBlob.decryptBlob(MASTER_KEY_FILE, &passwordAesKey);
603 if (response == SYSTEM_ERROR) {
604 return SYSTEM_ERROR;
605 }
606 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
607 // if salt was missing, generate one and write a new master key file with the salt.
608 if (salt == NULL) {
609 if (!generateSalt()) {
610 return SYSTEM_ERROR;
611 }
612 response = writeMasterKey(pw);
613 }
614 if (response == NO_ERROR) {
615 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
616 setupMasterKeys();
617 }
618 return response;
619 }
620 if (mRetry <= 0) {
621 reset();
622 return UNINITIALIZED;
623 }
624 --mRetry;
625 switch (mRetry) {
626 case 0: return WRONG_PASSWORD_0;
627 case 1: return WRONG_PASSWORD_1;
628 case 2: return WRONG_PASSWORD_2;
629 case 3: return WRONG_PASSWORD_3;
630 default: return WRONG_PASSWORD_3;
631 }
632 }
633
634 bool reset() {
635 clearMasterKeys();
636 setState(STATE_UNINITIALIZED);
637
638 DIR* dir = opendir(".");
639 struct dirent* file;
640
641 if (!dir) {
642 return false;
643 }
644 while ((file = readdir(dir)) != NULL) {
645 unlink(file->d_name);
646 }
647 closedir(dir);
648 return true;
649 }
650
Kenny Root51878182012-03-13 12:53:19 -0700651 bool isEmpty() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800652 DIR* dir = opendir(".");
653 struct dirent* file;
654 if (!dir) {
655 return true;
656 }
657 bool result = true;
658 while ((file = readdir(dir)) != NULL) {
659 if (isKeyFile(file->d_name)) {
660 result = false;
661 break;
662 }
663 }
664 closedir(dir);
665 return result;
666 }
667
668 void lock() {
669 clearMasterKeys();
670 setState(STATE_LOCKED);
671 }
672
Kenny Root822c3a92012-03-23 16:34:39 -0700673 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type) {
674 ResponseCode rc = keyBlob->decryptBlob(filename, &mMasterKeyDecryption);
675 if (rc != NO_ERROR) {
676 return rc;
677 }
678
679 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -0700680 if (version < CURRENT_BLOB_VERSION) {
Kenny Root822c3a92012-03-23 16:34:39 -0700681 upgrade(filename, keyBlob, version, type);
682 }
683
684 if (keyBlob->getType() != type) {
685 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
686 return KEY_NOT_FOUND;
687 }
688
689 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -0800690 }
691
692 ResponseCode put(const char* filename, Blob* keyBlob) {
693 return keyBlob->encryptBlob(filename, &mMasterKeyEncryption, mEntropy);
694 }
695
Kenny Root07438c82012-11-02 15:41:02 -0700696 void addGrant(const char* filename, uid_t granteeUid) {
697 grant_t *grant = getGrant(filename, granteeUid);
Kenny Root70e3a862012-02-15 17:20:23 -0800698 if (grant == NULL) {
699 grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -0700700 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700701 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root70e3a862012-02-15 17:20:23 -0800702 list_add_tail(&mGrants, &grant->plist);
703 }
704 }
705
Kenny Root07438c82012-11-02 15:41:02 -0700706 bool removeGrant(const char* filename, uid_t granteeUid) {
707 grant_t *grant = getGrant(filename, granteeUid);
Kenny Root70e3a862012-02-15 17:20:23 -0800708 if (grant != NULL) {
709 list_remove(&grant->plist);
710 delete grant;
711 return true;
712 }
713
714 return false;
715 }
716
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700717 bool hasGrant(const char* filename, const uid_t uid) const {
718 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -0800719 }
720
Kenny Root07438c82012-11-02 15:41:02 -0700721 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename) {
Kenny Root822c3a92012-03-23 16:34:39 -0700722 uint8_t* data;
723 size_t dataLength;
724 int rc;
725
726 if (mDevice->import_keypair == NULL) {
727 ALOGE("Keymaster doesn't support import!");
728 return SYSTEM_ERROR;
729 }
730
Kenny Root07438c82012-11-02 15:41:02 -0700731 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700732 if (rc) {
733 ALOGE("Error while importing keypair: %d", rc);
734 return SYSTEM_ERROR;
735 }
736
737 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
738 free(data);
739
740 return put(filename, &keyBlob);
741 }
742
Kenny Roota91203b2012-02-15 15:00:46 -0800743private:
744 static const char* MASTER_KEY_FILE;
745 static const int MASTER_KEY_SIZE_BYTES = 16;
746 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
747
748 static const int MAX_RETRY = 4;
749 static const size_t SALT_SIZE = 16;
750
751 Entropy* mEntropy;
752
Kenny Root70e3a862012-02-15 17:20:23 -0800753 keymaster_device_t* mDevice;
754
Kenny Roota91203b2012-02-15 15:00:46 -0800755 State mState;
756 int8_t mRetry;
757
758 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
759 uint8_t mSalt[SALT_SIZE];
760
761 AES_KEY mMasterKeyEncryption;
762 AES_KEY mMasterKeyDecryption;
763
Kenny Root70e3a862012-02-15 17:20:23 -0800764 struct listnode mGrants;
765
Kenny Roota91203b2012-02-15 15:00:46 -0800766 void setState(State state) {
767 mState = state;
768 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
769 mRetry = MAX_RETRY;
770 }
771 }
772
773 bool generateSalt() {
774 return mEntropy->generate_random_data(mSalt, sizeof(mSalt));
775 }
776
777 bool generateMasterKey() {
778 if (!mEntropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
779 return false;
780 }
781 if (!generateSalt()) {
782 return false;
783 }
784 return true;
785 }
786
787 void setupMasterKeys() {
788 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
789 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
790 setState(STATE_NO_ERROR);
791 }
792
793 void clearMasterKeys() {
794 memset(mMasterKey, 0, sizeof(mMasterKey));
795 memset(mSalt, 0, sizeof(mSalt));
796 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
797 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
798 }
799
Kenny Root07438c82012-11-02 15:41:02 -0700800 static void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
801 uint8_t* salt) {
Kenny Roota91203b2012-02-15 15:00:46 -0800802 size_t saltSize;
803 if (salt != NULL) {
804 saltSize = SALT_SIZE;
805 } else {
806 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
807 salt = (uint8_t*) "keystore";
808 // sizeof = 9, not strlen = 8
809 saltSize = sizeof("keystore");
810 }
Kenny Root07438c82012-11-02 15:41:02 -0700811
812 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
813 saltSize, 8192, keySize, key);
Kenny Roota91203b2012-02-15 15:00:46 -0800814 }
815
816 static bool isKeyFile(const char* filename) {
817 return ((strcmp(filename, MASTER_KEY_FILE) != 0)
818 && (strcmp(filename, ".") != 0)
819 && (strcmp(filename, "..") != 0));
820 }
Kenny Root70e3a862012-02-15 17:20:23 -0800821
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700822 grant_t* getGrant(const char* filename, uid_t uid) const {
Kenny Root70e3a862012-02-15 17:20:23 -0800823 struct listnode *node;
824 grant_t *grant;
825
826 list_for_each(node, &mGrants) {
827 grant = node_to_item(node, grant_t, plist);
828 if (grant->uid == uid
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700829 && !strcmp(reinterpret_cast<const char*>(grant->filename),
830 filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -0800831 return grant;
832 }
833 }
834
835 return NULL;
836 }
837
Kenny Root822c3a92012-03-23 16:34:39 -0700838 /**
839 * Upgrade code. This will upgrade the key from the current version
840 * to whatever is newest.
841 */
842 void upgrade(const char* filename, Blob* blob, const uint8_t oldVersion, const BlobType type) {
843 bool updated = false;
844 uint8_t version = oldVersion;
845
846 /* From V0 -> V1: All old types were unknown */
847 if (version == 0) {
848 ALOGV("upgrading to version 1 and setting type %d", type);
849
850 blob->setType(type);
851 if (type == TYPE_KEY_PAIR) {
852 importBlobAsKey(blob, filename);
853 }
854 version = 1;
855 updated = true;
856 }
857
858 /*
859 * If we've updated, set the key blob to the right version
860 * and write it.
861 * */
862 if (updated) {
863 ALOGV("updated and writing file %s", filename);
864 blob->setVersion(version);
865 this->put(filename, blob);
866 }
867 }
868
869 /**
870 * Takes a blob that is an PEM-encoded RSA key as a byte array and
871 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
872 * Then it overwrites the original blob with the new blob
873 * format that is returned from the keymaster.
874 */
875 ResponseCode importBlobAsKey(Blob* blob, const char* filename) {
876 // We won't even write to the blob directly with this BIO, so const_cast is okay.
877 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
878 if (b.get() == NULL) {
879 ALOGE("Problem instantiating BIO");
880 return SYSTEM_ERROR;
881 }
882
883 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
884 if (pkey.get() == NULL) {
885 ALOGE("Couldn't read old PEM file");
886 return SYSTEM_ERROR;
887 }
888
889 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
890 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
891 if (len < 0) {
892 ALOGE("Couldn't measure PKCS#8 length");
893 return SYSTEM_ERROR;
894 }
895
Kenny Root70c98892013-02-07 09:10:36 -0800896 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
897 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -0700898 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
899 ALOGE("Couldn't convert to PKCS#8");
900 return SYSTEM_ERROR;
901 }
902
Kenny Root70c98892013-02-07 09:10:36 -0800903 ResponseCode rc = importKey(pkcs8key.get(), len, filename);
Kenny Root822c3a92012-03-23 16:34:39 -0700904 if (rc != NO_ERROR) {
905 return rc;
906 }
907
908 return get(filename, blob, TYPE_KEY_PAIR);
909 }
Kenny Roota91203b2012-02-15 15:00:46 -0800910};
911
912const char* KeyStore::MASTER_KEY_FILE = ".masterkey";
913
Kenny Root07438c82012-11-02 15:41:02 -0700914static ResponseCode get_key_for_name(KeyStore* keyStore, Blob* keyBlob,
915 const android::String8& keyName, const uid_t uid, const BlobType type) {
Kenny Root70e3a862012-02-15 17:20:23 -0800916 char filename[NAME_MAX];
917
918 encode_key_for_uid(filename, uid, keyName);
Kenny Root822c3a92012-03-23 16:34:39 -0700919 ResponseCode responseCode = keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800920 if (responseCode == NO_ERROR) {
921 return responseCode;
922 }
923
Kenny Root49468902013-03-19 13:41:33 -0700924 // If this is one of the legacy UID->UID mappings, use it.
925 uid_t euid = get_keystore_euid(uid);
926 if (euid != uid) {
927 encode_key_for_uid(filename, euid, keyName);
Kenny Root822c3a92012-03-23 16:34:39 -0700928 responseCode = keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800929 if (responseCode == NO_ERROR) {
930 return responseCode;
931 }
932 }
933
934 // They might be using a granted key.
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700935 encode_key(filename, keyName);
936 if (!keyStore->hasGrant(filename, uid)) {
Kenny Root70e3a862012-02-15 17:20:23 -0800937 return responseCode;
938 }
939
940 // It is a granted key. Try to load it.
Kenny Root822c3a92012-03-23 16:34:39 -0700941 return keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800942}
943
Kenny Root07438c82012-11-02 15:41:02 -0700944namespace android {
945class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
946public:
947 KeyStoreProxy(KeyStore* keyStore)
948 : mKeyStore(keyStore)
949 {
Kenny Roota91203b2012-02-15 15:00:46 -0800950 }
Kenny Roota91203b2012-02-15 15:00:46 -0800951
Kenny Root07438c82012-11-02 15:41:02 -0700952 void binderDied(const wp<IBinder>&) {
953 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -0700954 }
Kenny Roota91203b2012-02-15 15:00:46 -0800955
Kenny Root07438c82012-11-02 15:41:02 -0700956 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -0800957 uid_t callingUid = IPCThreadState::self()->getCallingUid();
958 if (!has_permission(callingUid, P_TEST)) {
959 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -0700960 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -0800961 }
Kenny Roota91203b2012-02-15 15:00:46 -0800962
Kenny Root07438c82012-11-02 15:41:02 -0700963 return mKeyStore->getState();
Kenny Root298e7b12012-03-26 13:54:44 -0700964 }
965
Kenny Root07438c82012-11-02 15:41:02 -0700966 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -0800967 uid_t callingUid = IPCThreadState::self()->getCallingUid();
968 if (!has_permission(callingUid, P_GET)) {
969 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -0700970 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -0800971 }
Kenny Root07438c82012-11-02 15:41:02 -0700972
Kenny Root9d45d1c2013-02-14 10:32:30 -0800973 State state = mKeyStore->getState();
974 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -0700975 ALOGD("calling get in state: %d", state);
976 return state;
Kenny Roota91203b2012-02-15 15:00:46 -0800977 }
Kenny Root07438c82012-11-02 15:41:02 -0700978
979 String8 name8(name);
980 char filename[NAME_MAX];
Kenny Root07438c82012-11-02 15:41:02 -0700981 Blob keyBlob;
Kenny Root49468902013-03-19 13:41:33 -0700982
983 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
984 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -0700985 if (responseCode != ::NO_ERROR) {
Kenny Root150ca932012-11-14 14:29:02 -0800986 ALOGW("Could not read %s", filename);
Kenny Root07438c82012-11-02 15:41:02 -0700987 *item = NULL;
988 *itemLength = 0;
989 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -0800990 }
Kenny Roota91203b2012-02-15 15:00:46 -0800991
Kenny Root07438c82012-11-02 15:41:02 -0700992 *item = (uint8_t*) malloc(keyBlob.getLength());
993 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
994 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -0800995
Kenny Root07438c82012-11-02 15:41:02 -0700996 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -0800997 }
998
Kenny Root49468902013-03-19 13:41:33 -0700999 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001000 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1001 if (!has_permission(callingUid, P_INSERT)) {
1002 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001003 return ::PERMISSION_DENIED;
1004 }
Kenny Root07438c82012-11-02 15:41:02 -07001005
Kenny Root49468902013-03-19 13:41:33 -07001006 if (targetUid == -1) {
1007 targetUid = callingUid;
1008 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001009 return ::PERMISSION_DENIED;
1010 }
1011
Kenny Root9d45d1c2013-02-14 10:32:30 -08001012 State state = mKeyStore->getState();
1013 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001014 ALOGD("calling insert in state: %d", state);
1015 return state;
1016 }
1017
1018 String8 name8(name);
1019 char filename[NAME_MAX];
1020
Kenny Root49468902013-03-19 13:41:33 -07001021 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001022
1023 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
1024 return mKeyStore->put(filename, &keyBlob);
Kenny Root70e3a862012-02-15 17:20:23 -08001025 }
1026
Kenny Root49468902013-03-19 13:41:33 -07001027 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001028 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1029 if (!has_permission(callingUid, P_DELETE)) {
1030 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001031 return ::PERMISSION_DENIED;
1032 }
Kenny Root70e3a862012-02-15 17:20:23 -08001033
Kenny Root49468902013-03-19 13:41:33 -07001034 if (targetUid == -1) {
1035 targetUid = callingUid;
1036 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001037 return ::PERMISSION_DENIED;
1038 }
1039
Kenny Root07438c82012-11-02 15:41:02 -07001040 String8 name8(name);
1041 char filename[NAME_MAX];
1042
Kenny Root49468902013-03-19 13:41:33 -07001043 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001044
1045 Blob keyBlob;
1046 ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, TYPE_GENERIC);
1047 if (responseCode != ::NO_ERROR) {
1048 return responseCode;
1049 }
1050 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001051 }
1052
Kenny Root49468902013-03-19 13:41:33 -07001053 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001054 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1055 if (!has_permission(callingUid, P_EXIST)) {
1056 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001057 return ::PERMISSION_DENIED;
1058 }
Kenny Root70e3a862012-02-15 17:20:23 -08001059
Kenny Root49468902013-03-19 13:41:33 -07001060 if (targetUid == -1) {
1061 targetUid = callingUid;
1062 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001063 return ::PERMISSION_DENIED;
1064 }
1065
Kenny Root07438c82012-11-02 15:41:02 -07001066 String8 name8(name);
1067 char filename[NAME_MAX];
Kenny Root70e3a862012-02-15 17:20:23 -08001068
Kenny Root49468902013-03-19 13:41:33 -07001069 encode_key_for_uid(filename, targetUid, name8);
Kenny Root70e3a862012-02-15 17:20:23 -08001070
Kenny Root07438c82012-11-02 15:41:02 -07001071 if (access(filename, R_OK) == -1) {
1072 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1073 }
1074 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001075 }
1076
Kenny Root49468902013-03-19 13:41:33 -07001077 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001078 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1079 if (!has_permission(callingUid, P_SAW)) {
1080 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001081 return ::PERMISSION_DENIED;
1082 }
Kenny Root70e3a862012-02-15 17:20:23 -08001083
Kenny Root49468902013-03-19 13:41:33 -07001084 if (targetUid == -1) {
1085 targetUid = callingUid;
1086 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001087 return ::PERMISSION_DENIED;
1088 }
1089
Kenny Root07438c82012-11-02 15:41:02 -07001090 DIR* dir = opendir(".");
1091 if (!dir) {
1092 return ::SYSTEM_ERROR;
1093 }
Kenny Root70e3a862012-02-15 17:20:23 -08001094
Kenny Root07438c82012-11-02 15:41:02 -07001095 const String8 prefix8(prefix);
1096 char filename[NAME_MAX];
Kenny Root70e3a862012-02-15 17:20:23 -08001097
Kenny Root49468902013-03-19 13:41:33 -07001098 int n = encode_key_for_uid(filename, targetUid, prefix8);
Kenny Root70e3a862012-02-15 17:20:23 -08001099
Kenny Root07438c82012-11-02 15:41:02 -07001100 struct dirent* file;
1101 while ((file = readdir(dir)) != NULL) {
1102 if (!strncmp(filename, file->d_name, n)) {
1103 const char* p = &file->d_name[n];
1104 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001105
Kenny Root07438c82012-11-02 15:41:02 -07001106 size_t extra = decode_key_length(p, plen);
1107 char *match = (char*) malloc(extra + 1);
1108 if (match != NULL) {
1109 decode_key(match, p, plen);
1110 matches->push(String16(match, extra));
1111 free(match);
1112 } else {
1113 ALOGW("could not allocate match of size %zd", extra);
1114 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001115 }
1116 }
Kenny Root07438c82012-11-02 15:41:02 -07001117 closedir(dir);
1118
1119 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001120 }
1121
Kenny Root07438c82012-11-02 15:41:02 -07001122 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001123 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1124 if (!has_permission(callingUid, P_RESET)) {
1125 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001126 return ::PERMISSION_DENIED;
1127 }
1128
1129 ResponseCode rc = mKeyStore->reset() ? ::NO_ERROR : ::SYSTEM_ERROR;
1130
1131 const keymaster_device_t* device = mKeyStore->getDevice();
1132 if (device == NULL) {
1133 ALOGE("No keymaster device!");
1134 return ::SYSTEM_ERROR;
1135 }
1136
1137 if (device->delete_all == NULL) {
1138 ALOGV("keymaster device doesn't implement delete_all");
1139 return rc;
1140 }
1141
1142 if (device->delete_all(device)) {
1143 ALOGE("Problem calling keymaster's delete_all");
1144 return ::SYSTEM_ERROR;
1145 }
1146
Kenny Root9a53d3e2012-08-14 10:47:54 -07001147 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001148 }
1149
Kenny Root07438c82012-11-02 15:41:02 -07001150 /*
1151 * Here is the history. To improve the security, the parameters to generate the
1152 * master key has been changed. To make a seamless transition, we update the
1153 * file using the same password when the user unlock it for the first time. If
1154 * any thing goes wrong during the transition, the new file will not overwrite
1155 * the old one. This avoids permanent damages of the existing data.
1156 */
1157 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001158 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1159 if (!has_permission(callingUid, P_PASSWORD)) {
1160 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001161 return ::PERMISSION_DENIED;
1162 }
Kenny Root70e3a862012-02-15 17:20:23 -08001163
Kenny Root07438c82012-11-02 15:41:02 -07001164 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001165
Kenny Root07438c82012-11-02 15:41:02 -07001166 switch (mKeyStore->getState()) {
1167 case ::STATE_UNINITIALIZED: {
1168 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
1169 return mKeyStore->initialize(password8);
1170 }
1171 case ::STATE_NO_ERROR: {
1172 // rewrite master key with new password.
1173 return mKeyStore->writeMasterKey(password8);
1174 }
1175 case ::STATE_LOCKED: {
1176 // read master key, decrypt with password, initialize mMasterKey*.
1177 return mKeyStore->readMasterKey(password8);
1178 }
1179 }
1180 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001181 }
1182
Kenny Root07438c82012-11-02 15:41:02 -07001183 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001184 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1185 if (!has_permission(callingUid, P_LOCK)) {
1186 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001187 return ::PERMISSION_DENIED;
1188 }
Kenny Root70e3a862012-02-15 17:20:23 -08001189
Kenny Root9d45d1c2013-02-14 10:32:30 -08001190 State state = mKeyStore->getState();
1191 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001192 ALOGD("calling lock in state: %d", state);
1193 return state;
1194 }
1195
1196 mKeyStore->lock();
1197 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001198 }
1199
Kenny Root07438c82012-11-02 15:41:02 -07001200 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001201 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1202 if (!has_permission(callingUid, P_UNLOCK)) {
1203 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001204 return ::PERMISSION_DENIED;
1205 }
1206
Kenny Root9d45d1c2013-02-14 10:32:30 -08001207 State state = mKeyStore->getState();
1208 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001209 ALOGD("calling unlock when not locked");
1210 return state;
1211 }
1212
1213 const String8 password8(pw);
1214 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001215 }
1216
Kenny Root07438c82012-11-02 15:41:02 -07001217 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001218 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1219 if (!has_permission(callingUid, P_ZERO)) {
1220 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001221 return -1;
1222 }
Kenny Root70e3a862012-02-15 17:20:23 -08001223
Kenny Root07438c82012-11-02 15:41:02 -07001224 return mKeyStore->isEmpty() ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001225 }
1226
Kenny Root49468902013-03-19 13:41:33 -07001227 int32_t generate(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001228 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1229 if (!has_permission(callingUid, P_INSERT)) {
1230 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001231 return ::PERMISSION_DENIED;
1232 }
Kenny Root70e3a862012-02-15 17:20:23 -08001233
Kenny Root49468902013-03-19 13:41:33 -07001234 if (targetUid == -1) {
1235 targetUid = callingUid;
1236 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001237 return ::PERMISSION_DENIED;
1238 }
1239
Kenny Root9d45d1c2013-02-14 10:32:30 -08001240 State state = mKeyStore->getState();
1241 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001242 ALOGD("calling generate in state: %d", state);
1243 return state;
1244 }
Kenny Root70e3a862012-02-15 17:20:23 -08001245
Kenny Root07438c82012-11-02 15:41:02 -07001246 String8 name8(name);
1247 char filename[NAME_MAX];
1248
1249 uint8_t* data;
1250 size_t dataLength;
1251 int rc;
1252
1253 const keymaster_device_t* device = mKeyStore->getDevice();
1254 if (device == NULL) {
1255 return ::SYSTEM_ERROR;
1256 }
1257
1258 if (device->generate_keypair == NULL) {
1259 return ::SYSTEM_ERROR;
1260 }
1261
1262 keymaster_rsa_keygen_params_t rsa_params;
1263 rsa_params.modulus_size = 2048;
1264 rsa_params.public_exponent = 0x10001;
1265
1266 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1267 if (rc) {
1268 return ::SYSTEM_ERROR;
1269 }
1270
Kenny Root49468902013-03-19 13:41:33 -07001271 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001272
1273 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1274 free(data);
1275
1276 return mKeyStore->put(filename, &keyBlob);
Kenny Root70e3a862012-02-15 17:20:23 -08001277 }
1278
Kenny Root49468902013-03-19 13:41:33 -07001279 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001280 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1281 if (!has_permission(callingUid, P_INSERT)) {
1282 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001283 return ::PERMISSION_DENIED;
1284 }
Kenny Root07438c82012-11-02 15:41:02 -07001285
Kenny Root49468902013-03-19 13:41:33 -07001286 if (targetUid == -1) {
1287 targetUid = callingUid;
1288 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001289 return ::PERMISSION_DENIED;
1290 }
1291
Kenny Root9d45d1c2013-02-14 10:32:30 -08001292 State state = mKeyStore->getState();
1293 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001294 ALOGD("calling import in state: %d", state);
1295 return state;
1296 }
1297
1298 String8 name8(name);
1299 char filename[NAME_MAX];
1300
Kenny Root49468902013-03-19 13:41:33 -07001301 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001302
1303 return mKeyStore->importKey(data, length, filename);
Kenny Root70e3a862012-02-15 17:20:23 -08001304 }
1305
Kenny Root07438c82012-11-02 15:41:02 -07001306 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1307 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001308 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1309 if (!has_permission(callingUid, P_SIGN)) {
1310 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001311 return ::PERMISSION_DENIED;
1312 }
Kenny Root07438c82012-11-02 15:41:02 -07001313
Kenny Root9d45d1c2013-02-14 10:32:30 -08001314 State state = mKeyStore->getState();
1315 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001316 ALOGD("calling sign in state: %d", state);
1317 return state;
1318 }
1319
1320 Blob keyBlob;
1321 String8 name8(name);
1322
Kenny Rootd38a0b02013-02-13 12:59:14 -08001323 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001324 int rc;
1325
Kenny Rootd38a0b02013-02-13 12:59:14 -08001326 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1327 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001328 if (responseCode != ::NO_ERROR) {
1329 return responseCode;
1330 }
1331
1332 const keymaster_device_t* device = mKeyStore->getDevice();
1333 if (device == NULL) {
1334 ALOGE("no keymaster device; cannot sign");
1335 return ::SYSTEM_ERROR;
1336 }
1337
1338 if (device->sign_data == NULL) {
1339 ALOGE("device doesn't implement signing");
1340 return ::SYSTEM_ERROR;
1341 }
1342
1343 keymaster_rsa_sign_params_t params;
1344 params.digest_type = DIGEST_NONE;
1345 params.padding_type = PADDING_NONE;
1346
1347 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1348 data, length, out, outLength);
1349 if (rc) {
1350 ALOGW("device couldn't sign data");
1351 return ::SYSTEM_ERROR;
1352 }
1353
1354 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001355 }
1356
Kenny Root07438c82012-11-02 15:41:02 -07001357 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1358 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001359 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1360 if (!has_permission(callingUid, P_VERIFY)) {
1361 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001362 return ::PERMISSION_DENIED;
1363 }
Kenny Root70e3a862012-02-15 17:20:23 -08001364
Kenny Root9d45d1c2013-02-14 10:32:30 -08001365 State state = mKeyStore->getState();
1366 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001367 ALOGD("calling verify in state: %d", state);
1368 return state;
1369 }
Kenny Root70e3a862012-02-15 17:20:23 -08001370
Kenny Root07438c82012-11-02 15:41:02 -07001371 Blob keyBlob;
1372 String8 name8(name);
1373 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001374
Kenny Root49468902013-03-19 13:41:33 -07001375 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1376 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001377 if (responseCode != ::NO_ERROR) {
1378 return responseCode;
1379 }
Kenny Root70e3a862012-02-15 17:20:23 -08001380
Kenny Root07438c82012-11-02 15:41:02 -07001381 const keymaster_device_t* device = mKeyStore->getDevice();
1382 if (device == NULL) {
1383 return ::SYSTEM_ERROR;
1384 }
Kenny Root70e3a862012-02-15 17:20:23 -08001385
Kenny Root07438c82012-11-02 15:41:02 -07001386 if (device->verify_data == NULL) {
1387 return ::SYSTEM_ERROR;
1388 }
Kenny Root70e3a862012-02-15 17:20:23 -08001389
Kenny Root07438c82012-11-02 15:41:02 -07001390 keymaster_rsa_sign_params_t params;
1391 params.digest_type = DIGEST_NONE;
1392 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001393
Kenny Root07438c82012-11-02 15:41:02 -07001394 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1395 data, dataLength, signature, signatureLength);
1396 if (rc) {
1397 return ::SYSTEM_ERROR;
1398 } else {
1399 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001400 }
1401 }
Kenny Root07438c82012-11-02 15:41:02 -07001402
1403 /*
1404 * TODO: The abstraction between things stored in hardware and regular blobs
1405 * of data stored on the filesystem should be moved down to keystore itself.
1406 * Unfortunately the Java code that calls this has naming conventions that it
1407 * knows about. Ideally keystore shouldn't be used to store random blobs of
1408 * data.
1409 *
1410 * Until that happens, it's necessary to have a separate "get_pubkey" and
1411 * "del_key" since the Java code doesn't really communicate what it's
1412 * intentions are.
1413 */
1414 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001415 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1416 if (!has_permission(callingUid, P_GET)) {
1417 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001418 return ::PERMISSION_DENIED;
1419 }
Kenny Root07438c82012-11-02 15:41:02 -07001420
Kenny Root9d45d1c2013-02-14 10:32:30 -08001421 State state = mKeyStore->getState();
1422 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001423 ALOGD("calling get_pubkey in state: %d", state);
1424 return state;
1425 }
1426
1427 Blob keyBlob;
1428 String8 name8(name);
1429
Kenny Rootd38a0b02013-02-13 12:59:14 -08001430 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001431
Kenny Rootd38a0b02013-02-13 12:59:14 -08001432 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07001433 TYPE_KEY_PAIR);
1434 if (responseCode != ::NO_ERROR) {
1435 return responseCode;
1436 }
1437
1438 const keymaster_device_t* device = mKeyStore->getDevice();
1439 if (device == NULL) {
1440 return ::SYSTEM_ERROR;
1441 }
1442
1443 if (device->get_keypair_public == NULL) {
1444 ALOGE("device has no get_keypair_public implementation!");
1445 return ::SYSTEM_ERROR;
1446 }
1447
1448 int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
1449 pubkeyLength);
1450 if (rc) {
1451 return ::SYSTEM_ERROR;
1452 }
1453
1454 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001455 }
Kenny Root07438c82012-11-02 15:41:02 -07001456
Kenny Root49468902013-03-19 13:41:33 -07001457 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001458 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1459 if (!has_permission(callingUid, P_DELETE)) {
1460 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001461 return ::PERMISSION_DENIED;
1462 }
Kenny Root07438c82012-11-02 15:41:02 -07001463
Kenny Root49468902013-03-19 13:41:33 -07001464 if (targetUid == -1) {
1465 targetUid = callingUid;
1466 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001467 return ::PERMISSION_DENIED;
1468 }
1469
Kenny Root07438c82012-11-02 15:41:02 -07001470 String8 name8(name);
1471 char filename[NAME_MAX];
1472
Kenny Root49468902013-03-19 13:41:33 -07001473 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001474
1475 Blob keyBlob;
1476 ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, ::TYPE_KEY_PAIR);
1477 if (responseCode != ::NO_ERROR) {
1478 return responseCode;
1479 }
1480
1481 ResponseCode rc = ::NO_ERROR;
1482
1483 const keymaster_device_t* device = mKeyStore->getDevice();
1484 if (device == NULL) {
1485 rc = ::SYSTEM_ERROR;
1486 } else {
1487 // A device doesn't have to implement delete_keypair.
1488 if (device->delete_keypair != NULL) {
1489 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1490 rc = ::SYSTEM_ERROR;
1491 }
1492 }
1493 }
1494
1495 if (rc != ::NO_ERROR) {
1496 return rc;
1497 }
1498
1499 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1500 }
1501
1502 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001503 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1504 if (!has_permission(callingUid, P_GRANT)) {
1505 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001506 return ::PERMISSION_DENIED;
1507 }
Kenny Root07438c82012-11-02 15:41:02 -07001508
Kenny Root9d45d1c2013-02-14 10:32:30 -08001509 State state = mKeyStore->getState();
1510 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001511 ALOGD("calling grant in state: %d", state);
1512 return state;
1513 }
1514
1515 String8 name8(name);
1516 char filename[NAME_MAX];
1517
Kenny Rootd38a0b02013-02-13 12:59:14 -08001518 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001519
1520 if (access(filename, R_OK) == -1) {
1521 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1522 }
1523
1524 mKeyStore->addGrant(filename, granteeUid);
1525 return ::NO_ERROR;
1526 }
1527
1528 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001529 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1530 if (!has_permission(callingUid, P_GRANT)) {
1531 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001532 return ::PERMISSION_DENIED;
1533 }
Kenny Root07438c82012-11-02 15:41:02 -07001534
Kenny Root9d45d1c2013-02-14 10:32:30 -08001535 State state = mKeyStore->getState();
1536 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001537 ALOGD("calling ungrant in state: %d", state);
1538 return state;
1539 }
1540
1541 String8 name8(name);
1542 char filename[NAME_MAX];
1543
Kenny Rootd38a0b02013-02-13 12:59:14 -08001544 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001545
1546 if (access(filename, R_OK) == -1) {
1547 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1548 }
1549
1550 return mKeyStore->removeGrant(filename, granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
1551 }
1552
1553 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001554 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1555 if (!has_permission(callingUid, P_GET)) {
1556 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08001557 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001558 }
Kenny Root07438c82012-11-02 15:41:02 -07001559
1560 String8 name8(name);
1561 char filename[NAME_MAX];
1562
Kenny Rootd38a0b02013-02-13 12:59:14 -08001563 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001564
1565 if (access(filename, R_OK) == -1) {
Kenny Root36a9e232013-02-04 14:24:15 -08001566 ALOGW("could not access %s for getmtime", filename);
1567 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001568 }
1569
Kenny Root150ca932012-11-14 14:29:02 -08001570 int fd = TEMP_FAILURE_RETRY(open(filename, O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07001571 if (fd < 0) {
Kenny Root36a9e232013-02-04 14:24:15 -08001572 ALOGW("could not open %s for getmtime", filename);
1573 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001574 }
1575
1576 struct stat s;
1577 int ret = fstat(fd, &s);
1578 close(fd);
1579 if (ret == -1) {
Kenny Root36a9e232013-02-04 14:24:15 -08001580 ALOGW("could not stat %s for getmtime", filename);
1581 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001582 }
1583
Kenny Root36a9e232013-02-04 14:24:15 -08001584 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07001585 }
1586
1587private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08001588 inline bool isKeystoreUnlocked(State state) {
1589 switch (state) {
1590 case ::STATE_NO_ERROR:
1591 return true;
1592 case ::STATE_UNINITIALIZED:
1593 case ::STATE_LOCKED:
1594 return false;
1595 }
1596 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001597 }
1598
1599 ::KeyStore* mKeyStore;
1600};
1601
1602}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08001603
1604int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08001605 if (argc < 2) {
1606 ALOGE("A directory must be specified!");
1607 return 1;
1608 }
1609 if (chdir(argv[1]) == -1) {
1610 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
1611 return 1;
1612 }
1613
1614 Entropy entropy;
1615 if (!entropy.open()) {
1616 return 1;
1617 }
Kenny Root70e3a862012-02-15 17:20:23 -08001618
1619 keymaster_device_t* dev;
1620 if (keymaster_device_initialize(&dev)) {
1621 ALOGE("keystore keymaster could not be initialized; exiting");
1622 return 1;
1623 }
1624
Kenny Root70e3a862012-02-15 17:20:23 -08001625 KeyStore keyStore(&entropy, dev);
Kenny Root07438c82012-11-02 15:41:02 -07001626 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
1627 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
1628 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
1629 if (ret != android::OK) {
1630 ALOGE("Couldn't register binder service!");
1631 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08001632 }
Kenny Root07438c82012-11-02 15:41:02 -07001633
1634 /*
1635 * We're the only thread in existence, so we're just going to process
1636 * Binder transaction as a single-threaded program.
1637 */
1638 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08001639
1640 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08001641 return 1;
1642}