blob: 0b26bc88e378aab77f6dbb9072e278033087313d [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,
Kenny Root02254072013-03-20 11:48:19 -0700139 P_MIGRATE = 1 << 14,
Kenny Root07438c82012-11-02 15:41:02 -0700140} perm_t;
141
142static struct user_euid {
143 uid_t uid;
144 uid_t euid;
145} user_euids[] = {
146 {AID_VPN, AID_SYSTEM},
147 {AID_WIFI, AID_SYSTEM},
148 {AID_ROOT, AID_SYSTEM},
149};
150
151static struct user_perm {
152 uid_t uid;
153 perm_t perms;
154} user_perms[] = {
155 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
156 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
157 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
158 {AID_ROOT, static_cast<perm_t>(P_GET) },
159};
160
161static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
162 | P_VERIFY);
163
164static bool has_permission(uid_t uid, perm_t perm) {
165 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
166 struct user_perm user = user_perms[i];
167 if (user.uid == uid) {
168 return user.perms & perm;
169 }
170 }
171
172 return DEFAULT_PERMS & perm;
173}
174
Kenny Root49468902013-03-19 13:41:33 -0700175/**
176 * Returns the UID that the callingUid should act as. This is here for
177 * legacy support of the WiFi and VPN systems and should be removed
178 * when WiFi can operate in its own namespace.
179 */
Kenny Root07438c82012-11-02 15:41:02 -0700180static uid_t get_keystore_euid(uid_t uid) {
181 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
182 struct user_euid user = user_euids[i];
183 if (user.uid == uid) {
184 return user.euid;
185 }
186 }
187
188 return uid;
189}
190
Kenny Root49468902013-03-19 13:41:33 -0700191/**
192 * Returns true if the callingUid is allowed to interact in the targetUid's
193 * namespace.
194 */
195static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
196 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
197 struct user_euid user = user_euids[i];
198 if (user.euid == callingUid && user.uid == targetUid) {
199 return true;
200 }
201 }
202
203 return false;
204}
205
Kenny Roota91203b2012-02-15 15:00:46 -0800206/* Here is the encoding of keys. This is necessary in order to allow arbitrary
207 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
208 * into two bytes. The first byte is one of [+-.] which represents the first
209 * two bits of the character. The second byte encodes the rest of the bits into
210 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
211 * that Base64 cannot be used here due to the need of prefix match on keys. */
212
Kenny Root07438c82012-11-02 15:41:02 -0700213static int encode_key(char* out, const android::String8& keyName) {
214 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
215 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800216 for (int i = length; i > 0; --i, ++in, ++out) {
217 if (*in >= '0' && *in <= '~') {
218 *out = *in;
219 } else {
220 *out = '+' + (*in >> 6);
221 *++out = '0' + (*in & 0x3F);
222 ++length;
223 }
224 }
225 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800226 return length;
227}
228
Kenny Root07438c82012-11-02 15:41:02 -0700229static int encode_key_for_uid(char* out, uid_t uid, const android::String8& keyName) {
Kenny Root70e3a862012-02-15 17:20:23 -0800230 int n = snprintf(out, NAME_MAX, "%u_", uid);
231 out += n;
232
Kenny Root07438c82012-11-02 15:41:02 -0700233 return n + encode_key(out, keyName);
Kenny Roota91203b2012-02-15 15:00:46 -0800234}
235
Kenny Root07438c82012-11-02 15:41:02 -0700236/*
237 * Converts from the "escaped" format on disk to actual name.
238 * This will be smaller than the input string.
239 *
240 * Characters that should combine with the next at the end will be truncated.
241 */
242static size_t decode_key_length(const char* in, size_t length) {
243 size_t outLength = 0;
244
245 for (const char* end = in + length; in < end; in++) {
246 /* This combines with the next character. */
247 if (*in < '0' || *in > '~') {
248 continue;
249 }
250
251 outLength++;
252 }
253 return outLength;
254}
255
256static void decode_key(char* out, const char* in, size_t length) {
257 for (const char* end = in + length; in < end; in++) {
258 if (*in < '0' || *in > '~') {
259 /* Truncate combining characters at the end. */
260 if (in + 1 >= end) {
261 break;
262 }
263
264 *out = (*in++ - '+') << 6;
265 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800266 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700267 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800268 }
269 }
270 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800271}
272
273static size_t readFully(int fd, uint8_t* data, size_t size) {
274 size_t remaining = size;
275 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800276 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800277 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800278 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800279 }
280 data += n;
281 remaining -= n;
282 }
283 return size;
284}
285
286static size_t writeFully(int fd, uint8_t* data, size_t size) {
287 size_t remaining = size;
288 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800289 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
290 if (n < 0) {
291 ALOGW("write failed: %s", strerror(errno));
292 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800293 }
294 data += n;
295 remaining -= n;
296 }
297 return size;
298}
299
300class Entropy {
301public:
302 Entropy() : mRandom(-1) {}
303 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800304 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800305 close(mRandom);
306 }
307 }
308
309 bool open() {
310 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800311 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
312 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800313 ALOGE("open: %s: %s", randomDevice, strerror(errno));
314 return false;
315 }
316 return true;
317 }
318
Kenny Root51878182012-03-13 12:53:19 -0700319 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800320 return (readFully(mRandom, data, size) == size);
321 }
322
323private:
324 int mRandom;
325};
326
327/* Here is the file format. There are two parts in blob.value, the secret and
328 * the description. The secret is stored in ciphertext, and its original size
329 * can be found in blob.length. The description is stored after the secret in
330 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700331 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
332 * the second is the blob's type, and the third byte is reserved. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800333 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
334 * and decryptBlob(). Thus they should not be accessed from outside. */
335
Kenny Root822c3a92012-03-23 16:34:39 -0700336/* ** Note to future implementors of encryption: **
337 * Currently this is the construction:
338 * metadata || Enc(MD5(data) || data)
339 *
340 * This should be the construction used for encrypting if re-implementing:
341 *
342 * Derive independent keys for encryption and MAC:
343 * Kenc = AES_encrypt(masterKey, "Encrypt")
344 * Kmac = AES_encrypt(masterKey, "MAC")
345 *
346 * Store this:
347 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
348 * HMAC(Kmac, metadata || Enc(data))
349 */
Kenny Roota91203b2012-02-15 15:00:46 -0800350struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700351 uint8_t version;
352 uint8_t type;
353 uint8_t reserved;
Kenny Roota91203b2012-02-15 15:00:46 -0800354 uint8_t info;
355 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700356 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800357 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700358 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800359 int32_t length; // in network byte order when encrypted
360 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
361};
362
Kenny Root822c3a92012-03-23 16:34:39 -0700363typedef enum {
364 TYPE_GENERIC = 1,
365 TYPE_MASTER_KEY = 2,
366 TYPE_KEY_PAIR = 3,
367} BlobType;
368
Kenny Root07438c82012-11-02 15:41:02 -0700369static const uint8_t CURRENT_BLOB_VERSION = 1;
Kenny Root822c3a92012-03-23 16:34:39 -0700370
Kenny Roota91203b2012-02-15 15:00:46 -0800371class Blob {
372public:
Kenny Root07438c82012-11-02 15:41:02 -0700373 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
374 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800375 mBlob.length = valueLength;
376 memcpy(mBlob.value, value, valueLength);
377
378 mBlob.info = infoLength;
379 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700380
Kenny Root07438c82012-11-02 15:41:02 -0700381 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700382 mBlob.type = uint8_t(type);
Kenny Roota91203b2012-02-15 15:00:46 -0800383 }
384
385 Blob(blob b) {
386 mBlob = b;
387 }
388
389 Blob() {}
390
Kenny Root51878182012-03-13 12:53:19 -0700391 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800392 return mBlob.value;
393 }
394
Kenny Root51878182012-03-13 12:53:19 -0700395 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800396 return mBlob.length;
397 }
398
Kenny Root51878182012-03-13 12:53:19 -0700399 const uint8_t* getInfo() const {
400 return mBlob.value + mBlob.length;
401 }
402
403 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800404 return mBlob.info;
405 }
406
Kenny Root822c3a92012-03-23 16:34:39 -0700407 uint8_t getVersion() const {
408 return mBlob.version;
409 }
410
411 void setVersion(uint8_t version) {
412 mBlob.version = version;
413 }
414
415 BlobType getType() const {
416 return BlobType(mBlob.type);
417 }
418
419 void setType(BlobType type) {
420 mBlob.type = uint8_t(type);
421 }
422
Kenny Roota91203b2012-02-15 15:00:46 -0800423 ResponseCode encryptBlob(const char* filename, AES_KEY *aes_key, Entropy* entropy) {
424 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
Kenny Root150ca932012-11-14 14:29:02 -0800425 ALOGW("Could not read random data for: %s", filename);
Kenny Roota91203b2012-02-15 15:00:46 -0800426 return SYSTEM_ERROR;
427 }
428
429 // data includes the value and the value's length
430 size_t dataLength = mBlob.length + sizeof(mBlob.length);
431 // pad data to the AES_BLOCK_SIZE
432 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
433 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
434 // encrypted data includes the digest value
435 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
436 // move info after space for padding
437 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
438 // zero padding area
439 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
440
441 mBlob.length = htonl(mBlob.length);
442 MD5(mBlob.digested, digestedLength, mBlob.digest);
443
444 uint8_t vector[AES_BLOCK_SIZE];
445 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
446 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
447 aes_key, vector, AES_ENCRYPT);
448
Kenny Root822c3a92012-03-23 16:34:39 -0700449 mBlob.reserved = 0;
Kenny Roota91203b2012-02-15 15:00:46 -0800450 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
451 size_t fileLength = encryptedLength + headerLength + mBlob.info;
452
453 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800454 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
455 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
456 if (out < 0) {
457 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800458 return SYSTEM_ERROR;
459 }
460 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
461 if (close(out) != 0) {
462 return SYSTEM_ERROR;
463 }
464 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800465 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800466 unlink(tmpFileName);
467 return SYSTEM_ERROR;
468 }
Kenny Root150ca932012-11-14 14:29:02 -0800469 if (rename(tmpFileName, filename) == -1) {
470 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
471 return SYSTEM_ERROR;
472 }
473 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800474 }
475
476 ResponseCode decryptBlob(const char* filename, AES_KEY *aes_key) {
Kenny Root150ca932012-11-14 14:29:02 -0800477 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
478 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800479 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
480 }
481 // fileLength may be less than sizeof(mBlob) since the in
482 // memory version has extra padding to tolerate rounding up to
483 // the AES_BLOCK_SIZE
484 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
485 if (close(in) != 0) {
486 return SYSTEM_ERROR;
487 }
488 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
489 if (fileLength < headerLength) {
490 return VALUE_CORRUPTED;
491 }
492
493 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
494 if (encryptedLength < 0 || encryptedLength % AES_BLOCK_SIZE != 0) {
495 return VALUE_CORRUPTED;
496 }
497 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
498 mBlob.vector, AES_DECRYPT);
499 size_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
500 uint8_t computedDigest[MD5_DIGEST_LENGTH];
501 MD5(mBlob.digested, digestedLength, computedDigest);
502 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
503 return VALUE_CORRUPTED;
504 }
505
506 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
507 mBlob.length = ntohl(mBlob.length);
508 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
509 return VALUE_CORRUPTED;
510 }
511 if (mBlob.info != 0) {
512 // move info from after padding to after data
513 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
514 }
Kenny Root07438c82012-11-02 15:41:02 -0700515 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800516 }
517
518private:
519 struct blob mBlob;
520};
521
Kenny Root70e3a862012-02-15 17:20:23 -0800522typedef struct {
523 uint32_t uid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700524 const uint8_t* filename;
Kenny Root70e3a862012-02-15 17:20:23 -0800525
526 struct listnode plist;
527} grant_t;
528
Kenny Roota91203b2012-02-15 15:00:46 -0800529class KeyStore {
530public:
Kenny Root70e3a862012-02-15 17:20:23 -0800531 KeyStore(Entropy* entropy, keymaster_device_t* device)
Kenny Root51878182012-03-13 12:53:19 -0700532 : mEntropy(entropy)
Kenny Root70e3a862012-02-15 17:20:23 -0800533 , mDevice(device)
Kenny Root51878182012-03-13 12:53:19 -0700534 , mRetry(MAX_RETRY)
535 {
Kenny Roota91203b2012-02-15 15:00:46 -0800536 if (access(MASTER_KEY_FILE, R_OK) == 0) {
537 setState(STATE_LOCKED);
538 } else {
539 setState(STATE_UNINITIALIZED);
540 }
Kenny Root70e3a862012-02-15 17:20:23 -0800541
542 list_init(&mGrants);
Kenny Roota91203b2012-02-15 15:00:46 -0800543 }
544
Kenny Root51878182012-03-13 12:53:19 -0700545 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800546 return mState;
547 }
548
Kenny Root51878182012-03-13 12:53:19 -0700549 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800550 return mRetry;
551 }
552
Kenny Root70e3a862012-02-15 17:20:23 -0800553 keymaster_device_t* getDevice() const {
554 return mDevice;
555 }
556
Kenny Root07438c82012-11-02 15:41:02 -0700557 ResponseCode initialize(const android::String8& pw) {
Kenny Roota91203b2012-02-15 15:00:46 -0800558 if (!generateMasterKey()) {
559 return SYSTEM_ERROR;
560 }
561 ResponseCode response = writeMasterKey(pw);
562 if (response != NO_ERROR) {
563 return response;
564 }
565 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700566 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800567 }
568
Kenny Root07438c82012-11-02 15:41:02 -0700569 ResponseCode writeMasterKey(const android::String8& pw) {
Kenny Roota91203b2012-02-15 15:00:46 -0800570 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
571 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
572 AES_KEY passwordAesKey;
573 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700574 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Roota91203b2012-02-15 15:00:46 -0800575 return masterKeyBlob.encryptBlob(MASTER_KEY_FILE, &passwordAesKey, mEntropy);
576 }
577
Kenny Root07438c82012-11-02 15:41:02 -0700578 ResponseCode readMasterKey(const android::String8& pw) {
Kenny Root150ca932012-11-14 14:29:02 -0800579 int in = TEMP_FAILURE_RETRY(open(MASTER_KEY_FILE, O_RDONLY));
580 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800581 return SYSTEM_ERROR;
582 }
583
584 // we read the raw blob to just to get the salt to generate
585 // the AES key, then we create the Blob to use with decryptBlob
586 blob rawBlob;
587 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
588 if (close(in) != 0) {
589 return SYSTEM_ERROR;
590 }
591 // find salt at EOF if present, otherwise we have an old file
592 uint8_t* salt;
593 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
594 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
595 } else {
596 salt = NULL;
597 }
598 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
599 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
600 AES_KEY passwordAesKey;
601 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
602 Blob masterKeyBlob(rawBlob);
603 ResponseCode response = masterKeyBlob.decryptBlob(MASTER_KEY_FILE, &passwordAesKey);
604 if (response == SYSTEM_ERROR) {
605 return SYSTEM_ERROR;
606 }
607 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
608 // if salt was missing, generate one and write a new master key file with the salt.
609 if (salt == NULL) {
610 if (!generateSalt()) {
611 return SYSTEM_ERROR;
612 }
613 response = writeMasterKey(pw);
614 }
615 if (response == NO_ERROR) {
616 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
617 setupMasterKeys();
618 }
619 return response;
620 }
621 if (mRetry <= 0) {
622 reset();
623 return UNINITIALIZED;
624 }
625 --mRetry;
626 switch (mRetry) {
627 case 0: return WRONG_PASSWORD_0;
628 case 1: return WRONG_PASSWORD_1;
629 case 2: return WRONG_PASSWORD_2;
630 case 3: return WRONG_PASSWORD_3;
631 default: return WRONG_PASSWORD_3;
632 }
633 }
634
635 bool reset() {
636 clearMasterKeys();
637 setState(STATE_UNINITIALIZED);
638
639 DIR* dir = opendir(".");
640 struct dirent* file;
641
642 if (!dir) {
643 return false;
644 }
645 while ((file = readdir(dir)) != NULL) {
646 unlink(file->d_name);
647 }
648 closedir(dir);
649 return true;
650 }
651
Kenny Root51878182012-03-13 12:53:19 -0700652 bool isEmpty() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800653 DIR* dir = opendir(".");
654 struct dirent* file;
655 if (!dir) {
656 return true;
657 }
658 bool result = true;
659 while ((file = readdir(dir)) != NULL) {
660 if (isKeyFile(file->d_name)) {
661 result = false;
662 break;
663 }
664 }
665 closedir(dir);
666 return result;
667 }
668
669 void lock() {
670 clearMasterKeys();
671 setState(STATE_LOCKED);
672 }
673
Kenny Root822c3a92012-03-23 16:34:39 -0700674 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type) {
675 ResponseCode rc = keyBlob->decryptBlob(filename, &mMasterKeyDecryption);
676 if (rc != NO_ERROR) {
677 return rc;
678 }
679
680 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -0700681 if (version < CURRENT_BLOB_VERSION) {
Kenny Root822c3a92012-03-23 16:34:39 -0700682 upgrade(filename, keyBlob, version, type);
683 }
684
685 if (keyBlob->getType() != type) {
686 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
687 return KEY_NOT_FOUND;
688 }
689
690 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -0800691 }
692
693 ResponseCode put(const char* filename, Blob* keyBlob) {
694 return keyBlob->encryptBlob(filename, &mMasterKeyEncryption, mEntropy);
695 }
696
Kenny Root07438c82012-11-02 15:41:02 -0700697 void addGrant(const char* filename, uid_t granteeUid) {
698 grant_t *grant = getGrant(filename, granteeUid);
Kenny Root70e3a862012-02-15 17:20:23 -0800699 if (grant == NULL) {
700 grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -0700701 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700702 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root70e3a862012-02-15 17:20:23 -0800703 list_add_tail(&mGrants, &grant->plist);
704 }
705 }
706
Kenny Root07438c82012-11-02 15:41:02 -0700707 bool removeGrant(const char* filename, uid_t granteeUid) {
708 grant_t *grant = getGrant(filename, granteeUid);
Kenny Root70e3a862012-02-15 17:20:23 -0800709 if (grant != NULL) {
710 list_remove(&grant->plist);
711 delete grant;
712 return true;
713 }
714
715 return false;
716 }
717
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700718 bool hasGrant(const char* filename, const uid_t uid) const {
719 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -0800720 }
721
Kenny Root07438c82012-11-02 15:41:02 -0700722 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename) {
Kenny Root822c3a92012-03-23 16:34:39 -0700723 uint8_t* data;
724 size_t dataLength;
725 int rc;
726
727 if (mDevice->import_keypair == NULL) {
728 ALOGE("Keymaster doesn't support import!");
729 return SYSTEM_ERROR;
730 }
731
Kenny Root07438c82012-11-02 15:41:02 -0700732 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700733 if (rc) {
734 ALOGE("Error while importing keypair: %d", rc);
735 return SYSTEM_ERROR;
736 }
737
738 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
739 free(data);
740
741 return put(filename, &keyBlob);
742 }
743
Kenny Roota91203b2012-02-15 15:00:46 -0800744private:
745 static const char* MASTER_KEY_FILE;
746 static const int MASTER_KEY_SIZE_BYTES = 16;
747 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
748
749 static const int MAX_RETRY = 4;
750 static const size_t SALT_SIZE = 16;
751
752 Entropy* mEntropy;
753
Kenny Root70e3a862012-02-15 17:20:23 -0800754 keymaster_device_t* mDevice;
755
Kenny Roota91203b2012-02-15 15:00:46 -0800756 State mState;
757 int8_t mRetry;
758
759 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
760 uint8_t mSalt[SALT_SIZE];
761
762 AES_KEY mMasterKeyEncryption;
763 AES_KEY mMasterKeyDecryption;
764
Kenny Root70e3a862012-02-15 17:20:23 -0800765 struct listnode mGrants;
766
Kenny Roota91203b2012-02-15 15:00:46 -0800767 void setState(State state) {
768 mState = state;
769 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
770 mRetry = MAX_RETRY;
771 }
772 }
773
774 bool generateSalt() {
775 return mEntropy->generate_random_data(mSalt, sizeof(mSalt));
776 }
777
778 bool generateMasterKey() {
779 if (!mEntropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
780 return false;
781 }
782 if (!generateSalt()) {
783 return false;
784 }
785 return true;
786 }
787
788 void setupMasterKeys() {
789 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
790 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
791 setState(STATE_NO_ERROR);
792 }
793
794 void clearMasterKeys() {
795 memset(mMasterKey, 0, sizeof(mMasterKey));
796 memset(mSalt, 0, sizeof(mSalt));
797 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
798 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
799 }
800
Kenny Root07438c82012-11-02 15:41:02 -0700801 static void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
802 uint8_t* salt) {
Kenny Roota91203b2012-02-15 15:00:46 -0800803 size_t saltSize;
804 if (salt != NULL) {
805 saltSize = SALT_SIZE;
806 } else {
807 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
808 salt = (uint8_t*) "keystore";
809 // sizeof = 9, not strlen = 8
810 saltSize = sizeof("keystore");
811 }
Kenny Root07438c82012-11-02 15:41:02 -0700812
813 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
814 saltSize, 8192, keySize, key);
Kenny Roota91203b2012-02-15 15:00:46 -0800815 }
816
817 static bool isKeyFile(const char* filename) {
818 return ((strcmp(filename, MASTER_KEY_FILE) != 0)
819 && (strcmp(filename, ".") != 0)
820 && (strcmp(filename, "..") != 0));
821 }
Kenny Root70e3a862012-02-15 17:20:23 -0800822
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700823 grant_t* getGrant(const char* filename, uid_t uid) const {
Kenny Root70e3a862012-02-15 17:20:23 -0800824 struct listnode *node;
825 grant_t *grant;
826
827 list_for_each(node, &mGrants) {
828 grant = node_to_item(node, grant_t, plist);
829 if (grant->uid == uid
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700830 && !strcmp(reinterpret_cast<const char*>(grant->filename),
831 filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -0800832 return grant;
833 }
834 }
835
836 return NULL;
837 }
838
Kenny Root822c3a92012-03-23 16:34:39 -0700839 /**
840 * Upgrade code. This will upgrade the key from the current version
841 * to whatever is newest.
842 */
843 void upgrade(const char* filename, Blob* blob, const uint8_t oldVersion, const BlobType type) {
844 bool updated = false;
845 uint8_t version = oldVersion;
846
847 /* From V0 -> V1: All old types were unknown */
848 if (version == 0) {
849 ALOGV("upgrading to version 1 and setting type %d", type);
850
851 blob->setType(type);
852 if (type == TYPE_KEY_PAIR) {
853 importBlobAsKey(blob, filename);
854 }
855 version = 1;
856 updated = true;
857 }
858
859 /*
860 * If we've updated, set the key blob to the right version
861 * and write it.
862 * */
863 if (updated) {
864 ALOGV("updated and writing file %s", filename);
865 blob->setVersion(version);
866 this->put(filename, blob);
867 }
868 }
869
870 /**
871 * Takes a blob that is an PEM-encoded RSA key as a byte array and
872 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
873 * Then it overwrites the original blob with the new blob
874 * format that is returned from the keymaster.
875 */
876 ResponseCode importBlobAsKey(Blob* blob, const char* filename) {
877 // We won't even write to the blob directly with this BIO, so const_cast is okay.
878 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
879 if (b.get() == NULL) {
880 ALOGE("Problem instantiating BIO");
881 return SYSTEM_ERROR;
882 }
883
884 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
885 if (pkey.get() == NULL) {
886 ALOGE("Couldn't read old PEM file");
887 return SYSTEM_ERROR;
888 }
889
890 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
891 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
892 if (len < 0) {
893 ALOGE("Couldn't measure PKCS#8 length");
894 return SYSTEM_ERROR;
895 }
896
Kenny Root70c98892013-02-07 09:10:36 -0800897 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
898 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -0700899 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
900 ALOGE("Couldn't convert to PKCS#8");
901 return SYSTEM_ERROR;
902 }
903
Kenny Root70c98892013-02-07 09:10:36 -0800904 ResponseCode rc = importKey(pkcs8key.get(), len, filename);
Kenny Root822c3a92012-03-23 16:34:39 -0700905 if (rc != NO_ERROR) {
906 return rc;
907 }
908
909 return get(filename, blob, TYPE_KEY_PAIR);
910 }
Kenny Roota91203b2012-02-15 15:00:46 -0800911};
912
913const char* KeyStore::MASTER_KEY_FILE = ".masterkey";
914
Kenny Root07438c82012-11-02 15:41:02 -0700915static ResponseCode get_key_for_name(KeyStore* keyStore, Blob* keyBlob,
916 const android::String8& keyName, const uid_t uid, const BlobType type) {
Kenny Root70e3a862012-02-15 17:20:23 -0800917 char filename[NAME_MAX];
918
919 encode_key_for_uid(filename, uid, keyName);
Kenny Root822c3a92012-03-23 16:34:39 -0700920 ResponseCode responseCode = keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800921 if (responseCode == NO_ERROR) {
922 return responseCode;
923 }
924
Kenny Root49468902013-03-19 13:41:33 -0700925 // If this is one of the legacy UID->UID mappings, use it.
926 uid_t euid = get_keystore_euid(uid);
927 if (euid != uid) {
928 encode_key_for_uid(filename, euid, keyName);
Kenny Root822c3a92012-03-23 16:34:39 -0700929 responseCode = keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800930 if (responseCode == NO_ERROR) {
931 return responseCode;
932 }
933 }
934
935 // They might be using a granted key.
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700936 encode_key(filename, keyName);
937 if (!keyStore->hasGrant(filename, uid)) {
Kenny Root70e3a862012-02-15 17:20:23 -0800938 return responseCode;
939 }
940
941 // It is a granted key. Try to load it.
Kenny Root822c3a92012-03-23 16:34:39 -0700942 return keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800943}
944
Kenny Root07438c82012-11-02 15:41:02 -0700945namespace android {
946class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
947public:
948 KeyStoreProxy(KeyStore* keyStore)
949 : mKeyStore(keyStore)
950 {
Kenny Roota91203b2012-02-15 15:00:46 -0800951 }
Kenny Roota91203b2012-02-15 15:00:46 -0800952
Kenny Root07438c82012-11-02 15:41:02 -0700953 void binderDied(const wp<IBinder>&) {
954 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -0700955 }
Kenny Roota91203b2012-02-15 15:00:46 -0800956
Kenny Root07438c82012-11-02 15:41:02 -0700957 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -0800958 uid_t callingUid = IPCThreadState::self()->getCallingUid();
959 if (!has_permission(callingUid, P_TEST)) {
960 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -0700961 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -0800962 }
Kenny Roota91203b2012-02-15 15:00:46 -0800963
Kenny Root07438c82012-11-02 15:41:02 -0700964 return mKeyStore->getState();
Kenny Root298e7b12012-03-26 13:54:44 -0700965 }
966
Kenny Root07438c82012-11-02 15:41:02 -0700967 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -0800968 uid_t callingUid = IPCThreadState::self()->getCallingUid();
969 if (!has_permission(callingUid, P_GET)) {
970 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -0700971 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -0800972 }
Kenny Root07438c82012-11-02 15:41:02 -0700973
Kenny Root9d45d1c2013-02-14 10:32:30 -0800974 State state = mKeyStore->getState();
975 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -0700976 ALOGD("calling get in state: %d", state);
977 return state;
Kenny Roota91203b2012-02-15 15:00:46 -0800978 }
Kenny Root07438c82012-11-02 15:41:02 -0700979
980 String8 name8(name);
981 char filename[NAME_MAX];
Kenny Root07438c82012-11-02 15:41:02 -0700982 Blob keyBlob;
Kenny Root49468902013-03-19 13:41:33 -0700983
984 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
985 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -0700986 if (responseCode != ::NO_ERROR) {
Kenny Root150ca932012-11-14 14:29:02 -0800987 ALOGW("Could not read %s", filename);
Kenny Root07438c82012-11-02 15:41:02 -0700988 *item = NULL;
989 *itemLength = 0;
990 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -0800991 }
Kenny Roota91203b2012-02-15 15:00:46 -0800992
Kenny Root07438c82012-11-02 15:41:02 -0700993 *item = (uint8_t*) malloc(keyBlob.getLength());
994 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
995 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -0800996
Kenny Root07438c82012-11-02 15:41:02 -0700997 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -0800998 }
999
Kenny Root49468902013-03-19 13:41:33 -07001000 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001001 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1002 if (!has_permission(callingUid, P_INSERT)) {
1003 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001004 return ::PERMISSION_DENIED;
1005 }
Kenny Root07438c82012-11-02 15:41:02 -07001006
Kenny Root49468902013-03-19 13:41:33 -07001007 if (targetUid == -1) {
1008 targetUid = callingUid;
1009 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001010 return ::PERMISSION_DENIED;
1011 }
1012
Kenny Root9d45d1c2013-02-14 10:32:30 -08001013 State state = mKeyStore->getState();
1014 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001015 ALOGD("calling insert in state: %d", state);
1016 return state;
1017 }
1018
1019 String8 name8(name);
1020 char filename[NAME_MAX];
1021
Kenny Root49468902013-03-19 13:41:33 -07001022 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001023
1024 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
1025 return mKeyStore->put(filename, &keyBlob);
Kenny Root70e3a862012-02-15 17:20:23 -08001026 }
1027
Kenny Root49468902013-03-19 13:41:33 -07001028 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001029 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1030 if (!has_permission(callingUid, P_DELETE)) {
1031 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001032 return ::PERMISSION_DENIED;
1033 }
Kenny Root70e3a862012-02-15 17:20:23 -08001034
Kenny Root49468902013-03-19 13:41:33 -07001035 if (targetUid == -1) {
1036 targetUid = callingUid;
1037 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001038 return ::PERMISSION_DENIED;
1039 }
1040
Kenny Root07438c82012-11-02 15:41:02 -07001041 String8 name8(name);
1042 char filename[NAME_MAX];
1043
Kenny Root49468902013-03-19 13:41:33 -07001044 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001045
1046 Blob keyBlob;
1047 ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, TYPE_GENERIC);
1048 if (responseCode != ::NO_ERROR) {
1049 return responseCode;
1050 }
1051 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001052 }
1053
Kenny Root49468902013-03-19 13:41:33 -07001054 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001055 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1056 if (!has_permission(callingUid, P_EXIST)) {
1057 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001058 return ::PERMISSION_DENIED;
1059 }
Kenny Root70e3a862012-02-15 17:20:23 -08001060
Kenny Root49468902013-03-19 13:41:33 -07001061 if (targetUid == -1) {
1062 targetUid = callingUid;
1063 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001064 return ::PERMISSION_DENIED;
1065 }
1066
Kenny Root07438c82012-11-02 15:41:02 -07001067 String8 name8(name);
1068 char filename[NAME_MAX];
Kenny Root70e3a862012-02-15 17:20:23 -08001069
Kenny Root49468902013-03-19 13:41:33 -07001070 encode_key_for_uid(filename, targetUid, name8);
Kenny Root70e3a862012-02-15 17:20:23 -08001071
Kenny Root07438c82012-11-02 15:41:02 -07001072 if (access(filename, R_OK) == -1) {
1073 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1074 }
1075 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001076 }
1077
Kenny Root49468902013-03-19 13:41:33 -07001078 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001079 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1080 if (!has_permission(callingUid, P_SAW)) {
1081 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001082 return ::PERMISSION_DENIED;
1083 }
Kenny Root70e3a862012-02-15 17:20:23 -08001084
Kenny Root49468902013-03-19 13:41:33 -07001085 if (targetUid == -1) {
1086 targetUid = callingUid;
1087 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001088 return ::PERMISSION_DENIED;
1089 }
1090
Kenny Root07438c82012-11-02 15:41:02 -07001091 DIR* dir = opendir(".");
1092 if (!dir) {
1093 return ::SYSTEM_ERROR;
1094 }
Kenny Root70e3a862012-02-15 17:20:23 -08001095
Kenny Root07438c82012-11-02 15:41:02 -07001096 const String8 prefix8(prefix);
1097 char filename[NAME_MAX];
Kenny Root70e3a862012-02-15 17:20:23 -08001098
Kenny Root49468902013-03-19 13:41:33 -07001099 int n = encode_key_for_uid(filename, targetUid, prefix8);
Kenny Root70e3a862012-02-15 17:20:23 -08001100
Kenny Root07438c82012-11-02 15:41:02 -07001101 struct dirent* file;
1102 while ((file = readdir(dir)) != NULL) {
1103 if (!strncmp(filename, file->d_name, n)) {
1104 const char* p = &file->d_name[n];
1105 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001106
Kenny Root07438c82012-11-02 15:41:02 -07001107 size_t extra = decode_key_length(p, plen);
1108 char *match = (char*) malloc(extra + 1);
1109 if (match != NULL) {
1110 decode_key(match, p, plen);
1111 matches->push(String16(match, extra));
1112 free(match);
1113 } else {
1114 ALOGW("could not allocate match of size %zd", extra);
1115 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001116 }
1117 }
Kenny Root07438c82012-11-02 15:41:02 -07001118 closedir(dir);
1119
1120 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001121 }
1122
Kenny Root07438c82012-11-02 15:41:02 -07001123 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001124 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1125 if (!has_permission(callingUid, P_RESET)) {
1126 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001127 return ::PERMISSION_DENIED;
1128 }
1129
1130 ResponseCode rc = mKeyStore->reset() ? ::NO_ERROR : ::SYSTEM_ERROR;
1131
1132 const keymaster_device_t* device = mKeyStore->getDevice();
1133 if (device == NULL) {
1134 ALOGE("No keymaster device!");
1135 return ::SYSTEM_ERROR;
1136 }
1137
1138 if (device->delete_all == NULL) {
1139 ALOGV("keymaster device doesn't implement delete_all");
1140 return rc;
1141 }
1142
1143 if (device->delete_all(device)) {
1144 ALOGE("Problem calling keymaster's delete_all");
1145 return ::SYSTEM_ERROR;
1146 }
1147
Kenny Root9a53d3e2012-08-14 10:47:54 -07001148 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001149 }
1150
Kenny Root07438c82012-11-02 15:41:02 -07001151 /*
1152 * Here is the history. To improve the security, the parameters to generate the
1153 * master key has been changed. To make a seamless transition, we update the
1154 * file using the same password when the user unlock it for the first time. If
1155 * any thing goes wrong during the transition, the new file will not overwrite
1156 * the old one. This avoids permanent damages of the existing data.
1157 */
1158 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001159 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1160 if (!has_permission(callingUid, P_PASSWORD)) {
1161 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001162 return ::PERMISSION_DENIED;
1163 }
Kenny Root70e3a862012-02-15 17:20:23 -08001164
Kenny Root07438c82012-11-02 15:41:02 -07001165 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001166
Kenny Root07438c82012-11-02 15:41:02 -07001167 switch (mKeyStore->getState()) {
1168 case ::STATE_UNINITIALIZED: {
1169 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
1170 return mKeyStore->initialize(password8);
1171 }
1172 case ::STATE_NO_ERROR: {
1173 // rewrite master key with new password.
1174 return mKeyStore->writeMasterKey(password8);
1175 }
1176 case ::STATE_LOCKED: {
1177 // read master key, decrypt with password, initialize mMasterKey*.
1178 return mKeyStore->readMasterKey(password8);
1179 }
1180 }
1181 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001182 }
1183
Kenny Root07438c82012-11-02 15:41:02 -07001184 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001185 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1186 if (!has_permission(callingUid, P_LOCK)) {
1187 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001188 return ::PERMISSION_DENIED;
1189 }
Kenny Root70e3a862012-02-15 17:20:23 -08001190
Kenny Root9d45d1c2013-02-14 10:32:30 -08001191 State state = mKeyStore->getState();
1192 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001193 ALOGD("calling lock in state: %d", state);
1194 return state;
1195 }
1196
1197 mKeyStore->lock();
1198 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001199 }
1200
Kenny Root07438c82012-11-02 15:41:02 -07001201 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001202 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1203 if (!has_permission(callingUid, P_UNLOCK)) {
1204 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001205 return ::PERMISSION_DENIED;
1206 }
1207
Kenny Root9d45d1c2013-02-14 10:32:30 -08001208 State state = mKeyStore->getState();
1209 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001210 ALOGD("calling unlock when not locked");
1211 return state;
1212 }
1213
1214 const String8 password8(pw);
1215 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001216 }
1217
Kenny Root07438c82012-11-02 15:41:02 -07001218 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001219 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1220 if (!has_permission(callingUid, P_ZERO)) {
1221 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001222 return -1;
1223 }
Kenny Root70e3a862012-02-15 17:20:23 -08001224
Kenny Root07438c82012-11-02 15:41:02 -07001225 return mKeyStore->isEmpty() ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001226 }
1227
Kenny Root49468902013-03-19 13:41:33 -07001228 int32_t generate(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001229 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1230 if (!has_permission(callingUid, P_INSERT)) {
1231 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001232 return ::PERMISSION_DENIED;
1233 }
Kenny Root70e3a862012-02-15 17:20:23 -08001234
Kenny Root49468902013-03-19 13:41:33 -07001235 if (targetUid == -1) {
1236 targetUid = callingUid;
1237 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001238 return ::PERMISSION_DENIED;
1239 }
1240
Kenny Root9d45d1c2013-02-14 10:32:30 -08001241 State state = mKeyStore->getState();
1242 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001243 ALOGD("calling generate in state: %d", state);
1244 return state;
1245 }
Kenny Root70e3a862012-02-15 17:20:23 -08001246
Kenny Root07438c82012-11-02 15:41:02 -07001247 String8 name8(name);
1248 char filename[NAME_MAX];
1249
1250 uint8_t* data;
1251 size_t dataLength;
1252 int rc;
1253
1254 const keymaster_device_t* device = mKeyStore->getDevice();
1255 if (device == NULL) {
1256 return ::SYSTEM_ERROR;
1257 }
1258
1259 if (device->generate_keypair == NULL) {
1260 return ::SYSTEM_ERROR;
1261 }
1262
1263 keymaster_rsa_keygen_params_t rsa_params;
1264 rsa_params.modulus_size = 2048;
1265 rsa_params.public_exponent = 0x10001;
1266
1267 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1268 if (rc) {
1269 return ::SYSTEM_ERROR;
1270 }
1271
Kenny Root49468902013-03-19 13:41:33 -07001272 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001273
1274 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1275 free(data);
1276
1277 return mKeyStore->put(filename, &keyBlob);
Kenny Root70e3a862012-02-15 17:20:23 -08001278 }
1279
Kenny Root49468902013-03-19 13:41:33 -07001280 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001281 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1282 if (!has_permission(callingUid, P_INSERT)) {
1283 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001284 return ::PERMISSION_DENIED;
1285 }
Kenny Root07438c82012-11-02 15:41:02 -07001286
Kenny Root49468902013-03-19 13:41:33 -07001287 if (targetUid == -1) {
1288 targetUid = callingUid;
1289 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001290 return ::PERMISSION_DENIED;
1291 }
1292
Kenny Root9d45d1c2013-02-14 10:32:30 -08001293 State state = mKeyStore->getState();
1294 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001295 ALOGD("calling import in state: %d", state);
1296 return state;
1297 }
1298
1299 String8 name8(name);
1300 char filename[NAME_MAX];
1301
Kenny Root49468902013-03-19 13:41:33 -07001302 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001303
1304 return mKeyStore->importKey(data, length, filename);
Kenny Root70e3a862012-02-15 17:20:23 -08001305 }
1306
Kenny Root07438c82012-11-02 15:41:02 -07001307 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1308 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001309 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1310 if (!has_permission(callingUid, P_SIGN)) {
1311 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001312 return ::PERMISSION_DENIED;
1313 }
Kenny Root07438c82012-11-02 15:41:02 -07001314
Kenny Root9d45d1c2013-02-14 10:32:30 -08001315 State state = mKeyStore->getState();
1316 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001317 ALOGD("calling sign in state: %d", state);
1318 return state;
1319 }
1320
1321 Blob keyBlob;
1322 String8 name8(name);
1323
Kenny Rootd38a0b02013-02-13 12:59:14 -08001324 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001325 int rc;
1326
Kenny Rootd38a0b02013-02-13 12:59:14 -08001327 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1328 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001329 if (responseCode != ::NO_ERROR) {
1330 return responseCode;
1331 }
1332
1333 const keymaster_device_t* device = mKeyStore->getDevice();
1334 if (device == NULL) {
1335 ALOGE("no keymaster device; cannot sign");
1336 return ::SYSTEM_ERROR;
1337 }
1338
1339 if (device->sign_data == NULL) {
1340 ALOGE("device doesn't implement signing");
1341 return ::SYSTEM_ERROR;
1342 }
1343
1344 keymaster_rsa_sign_params_t params;
1345 params.digest_type = DIGEST_NONE;
1346 params.padding_type = PADDING_NONE;
1347
1348 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1349 data, length, out, outLength);
1350 if (rc) {
1351 ALOGW("device couldn't sign data");
1352 return ::SYSTEM_ERROR;
1353 }
1354
1355 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001356 }
1357
Kenny Root07438c82012-11-02 15:41:02 -07001358 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1359 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001360 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1361 if (!has_permission(callingUid, P_VERIFY)) {
1362 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001363 return ::PERMISSION_DENIED;
1364 }
Kenny Root70e3a862012-02-15 17:20:23 -08001365
Kenny Root9d45d1c2013-02-14 10:32:30 -08001366 State state = mKeyStore->getState();
1367 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001368 ALOGD("calling verify in state: %d", state);
1369 return state;
1370 }
Kenny Root70e3a862012-02-15 17:20:23 -08001371
Kenny Root07438c82012-11-02 15:41:02 -07001372 Blob keyBlob;
1373 String8 name8(name);
1374 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001375
Kenny Root49468902013-03-19 13:41:33 -07001376 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1377 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001378 if (responseCode != ::NO_ERROR) {
1379 return responseCode;
1380 }
Kenny Root70e3a862012-02-15 17:20:23 -08001381
Kenny Root07438c82012-11-02 15:41:02 -07001382 const keymaster_device_t* device = mKeyStore->getDevice();
1383 if (device == NULL) {
1384 return ::SYSTEM_ERROR;
1385 }
Kenny Root70e3a862012-02-15 17:20:23 -08001386
Kenny Root07438c82012-11-02 15:41:02 -07001387 if (device->verify_data == NULL) {
1388 return ::SYSTEM_ERROR;
1389 }
Kenny Root70e3a862012-02-15 17:20:23 -08001390
Kenny Root07438c82012-11-02 15:41:02 -07001391 keymaster_rsa_sign_params_t params;
1392 params.digest_type = DIGEST_NONE;
1393 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001394
Kenny Root07438c82012-11-02 15:41:02 -07001395 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1396 data, dataLength, signature, signatureLength);
1397 if (rc) {
1398 return ::SYSTEM_ERROR;
1399 } else {
1400 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001401 }
1402 }
Kenny Root07438c82012-11-02 15:41:02 -07001403
1404 /*
1405 * TODO: The abstraction between things stored in hardware and regular blobs
1406 * of data stored on the filesystem should be moved down to keystore itself.
1407 * Unfortunately the Java code that calls this has naming conventions that it
1408 * knows about. Ideally keystore shouldn't be used to store random blobs of
1409 * data.
1410 *
1411 * Until that happens, it's necessary to have a separate "get_pubkey" and
1412 * "del_key" since the Java code doesn't really communicate what it's
1413 * intentions are.
1414 */
1415 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001416 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1417 if (!has_permission(callingUid, P_GET)) {
1418 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001419 return ::PERMISSION_DENIED;
1420 }
Kenny Root07438c82012-11-02 15:41:02 -07001421
Kenny Root9d45d1c2013-02-14 10:32:30 -08001422 State state = mKeyStore->getState();
1423 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001424 ALOGD("calling get_pubkey in state: %d", state);
1425 return state;
1426 }
1427
1428 Blob keyBlob;
1429 String8 name8(name);
1430
Kenny Rootd38a0b02013-02-13 12:59:14 -08001431 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001432
Kenny Rootd38a0b02013-02-13 12:59:14 -08001433 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07001434 TYPE_KEY_PAIR);
1435 if (responseCode != ::NO_ERROR) {
1436 return responseCode;
1437 }
1438
1439 const keymaster_device_t* device = mKeyStore->getDevice();
1440 if (device == NULL) {
1441 return ::SYSTEM_ERROR;
1442 }
1443
1444 if (device->get_keypair_public == NULL) {
1445 ALOGE("device has no get_keypair_public implementation!");
1446 return ::SYSTEM_ERROR;
1447 }
1448
1449 int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
1450 pubkeyLength);
1451 if (rc) {
1452 return ::SYSTEM_ERROR;
1453 }
1454
1455 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001456 }
Kenny Root07438c82012-11-02 15:41:02 -07001457
Kenny Root49468902013-03-19 13:41:33 -07001458 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001459 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1460 if (!has_permission(callingUid, P_DELETE)) {
1461 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001462 return ::PERMISSION_DENIED;
1463 }
Kenny Root07438c82012-11-02 15:41:02 -07001464
Kenny Root49468902013-03-19 13:41:33 -07001465 if (targetUid == -1) {
1466 targetUid = callingUid;
1467 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001468 return ::PERMISSION_DENIED;
1469 }
1470
Kenny Root07438c82012-11-02 15:41:02 -07001471 String8 name8(name);
1472 char filename[NAME_MAX];
1473
Kenny Root49468902013-03-19 13:41:33 -07001474 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001475
1476 Blob keyBlob;
1477 ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, ::TYPE_KEY_PAIR);
1478 if (responseCode != ::NO_ERROR) {
1479 return responseCode;
1480 }
1481
1482 ResponseCode rc = ::NO_ERROR;
1483
1484 const keymaster_device_t* device = mKeyStore->getDevice();
1485 if (device == NULL) {
1486 rc = ::SYSTEM_ERROR;
1487 } else {
1488 // A device doesn't have to implement delete_keypair.
1489 if (device->delete_keypair != NULL) {
1490 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1491 rc = ::SYSTEM_ERROR;
1492 }
1493 }
1494 }
1495
1496 if (rc != ::NO_ERROR) {
1497 return rc;
1498 }
1499
1500 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1501 }
1502
1503 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001504 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1505 if (!has_permission(callingUid, P_GRANT)) {
1506 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001507 return ::PERMISSION_DENIED;
1508 }
Kenny Root07438c82012-11-02 15:41:02 -07001509
Kenny Root9d45d1c2013-02-14 10:32:30 -08001510 State state = mKeyStore->getState();
1511 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001512 ALOGD("calling grant in state: %d", state);
1513 return state;
1514 }
1515
1516 String8 name8(name);
1517 char filename[NAME_MAX];
1518
Kenny Rootd38a0b02013-02-13 12:59:14 -08001519 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001520
1521 if (access(filename, R_OK) == -1) {
1522 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1523 }
1524
1525 mKeyStore->addGrant(filename, granteeUid);
1526 return ::NO_ERROR;
1527 }
1528
1529 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001530 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1531 if (!has_permission(callingUid, P_GRANT)) {
1532 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001533 return ::PERMISSION_DENIED;
1534 }
Kenny Root07438c82012-11-02 15:41:02 -07001535
Kenny Root9d45d1c2013-02-14 10:32:30 -08001536 State state = mKeyStore->getState();
1537 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001538 ALOGD("calling ungrant in state: %d", state);
1539 return state;
1540 }
1541
1542 String8 name8(name);
1543 char filename[NAME_MAX];
1544
Kenny Rootd38a0b02013-02-13 12:59:14 -08001545 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001546
1547 if (access(filename, R_OK) == -1) {
1548 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1549 }
1550
1551 return mKeyStore->removeGrant(filename, granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
1552 }
1553
1554 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001555 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1556 if (!has_permission(callingUid, P_GET)) {
1557 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08001558 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001559 }
Kenny Root07438c82012-11-02 15:41:02 -07001560
1561 String8 name8(name);
1562 char filename[NAME_MAX];
1563
Kenny Rootd38a0b02013-02-13 12:59:14 -08001564 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001565
1566 if (access(filename, R_OK) == -1) {
Kenny Root36a9e232013-02-04 14:24:15 -08001567 ALOGW("could not access %s for getmtime", filename);
1568 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001569 }
1570
Kenny Root150ca932012-11-14 14:29:02 -08001571 int fd = TEMP_FAILURE_RETRY(open(filename, O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07001572 if (fd < 0) {
Kenny Root36a9e232013-02-04 14:24:15 -08001573 ALOGW("could not open %s for getmtime", filename);
1574 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001575 }
1576
1577 struct stat s;
1578 int ret = fstat(fd, &s);
1579 close(fd);
1580 if (ret == -1) {
Kenny Root36a9e232013-02-04 14:24:15 -08001581 ALOGW("could not stat %s for getmtime", filename);
1582 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001583 }
1584
Kenny Root36a9e232013-02-04 14:24:15 -08001585 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07001586 }
1587
Kenny Root02254072013-03-20 11:48:19 -07001588 int32_t migrate(const String16& name, int32_t targetUid) {
1589 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1590 if (!has_permission(callingUid, P_MIGRATE)) {
1591 ALOGW("permission denied for %d: migrate", callingUid);
1592 return -1L;
1593 }
1594
1595 State state = mKeyStore->getState();
1596 if (!isKeystoreUnlocked(state)) {
1597 ALOGD("calling migrate in state: %d", state);
1598 return state;
1599 }
1600
1601 if (!is_granted_to(callingUid, targetUid)) {
1602 ALOGD("migrate not granted: %d -> %d", callingUid, targetUid);
1603 return ::PERMISSION_DENIED;
1604 }
1605
1606 String8 source8(name);
1607 char source[NAME_MAX];
1608
1609 encode_key_for_uid(source, callingUid, source8);
1610
1611 if (access(source, W_OK) == -1) {
1612 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1613 }
1614
1615 String8 target8(name);
1616 char target[NAME_MAX];
1617
1618 encode_key_for_uid(target, targetUid, target8);
1619
1620 // Make sure the target doesn't exist
1621 if (access(target, R_OK) == 0 || errno != ENOENT) {
1622 ALOGD("migrate target already exists: %s", strerror(errno));
1623 return ::SYSTEM_ERROR;
1624 }
1625
1626 if (rename(source, target)) {
1627 ALOGD("migrate could not rename: %s", strerror(errno));
1628 return ::SYSTEM_ERROR;
1629 }
1630 return ::NO_ERROR;
1631 }
1632
Kenny Root07438c82012-11-02 15:41:02 -07001633private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08001634 inline bool isKeystoreUnlocked(State state) {
1635 switch (state) {
1636 case ::STATE_NO_ERROR:
1637 return true;
1638 case ::STATE_UNINITIALIZED:
1639 case ::STATE_LOCKED:
1640 return false;
1641 }
1642 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001643 }
1644
1645 ::KeyStore* mKeyStore;
1646};
1647
1648}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08001649
1650int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08001651 if (argc < 2) {
1652 ALOGE("A directory must be specified!");
1653 return 1;
1654 }
1655 if (chdir(argv[1]) == -1) {
1656 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
1657 return 1;
1658 }
1659
1660 Entropy entropy;
1661 if (!entropy.open()) {
1662 return 1;
1663 }
Kenny Root70e3a862012-02-15 17:20:23 -08001664
1665 keymaster_device_t* dev;
1666 if (keymaster_device_initialize(&dev)) {
1667 ALOGE("keystore keymaster could not be initialized; exiting");
1668 return 1;
1669 }
1670
Kenny Root70e3a862012-02-15 17:20:23 -08001671 KeyStore keyStore(&entropy, dev);
Kenny Root07438c82012-11-02 15:41:02 -07001672 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
1673 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
1674 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
1675 if (ret != android::OK) {
1676 ALOGE("Couldn't register binder service!");
1677 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08001678 }
Kenny Root07438c82012-11-02 15:41:02 -07001679
1680 /*
1681 * We're the only thread in existence, so we're just going to process
1682 * Binder transaction as a single-threaded program.
1683 */
1684 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08001685
1686 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08001687 return 1;
1688}