blob: 438a8e46b248873aa1ff9c0a95dd47d0e7d9793e [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 {
Kenny Rootd53bc922013-03-21 14:10:15 -0700125 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 P_DUPLICATE = 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 {
Kenny Rootd53bc922013-03-21 14:10:15 -0700364 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700365 TYPE_GENERIC = 1,
366 TYPE_MASTER_KEY = 2,
367 TYPE_KEY_PAIR = 3,
368} BlobType;
369
Kenny Root07438c82012-11-02 15:41:02 -0700370static const uint8_t CURRENT_BLOB_VERSION = 1;
Kenny Root822c3a92012-03-23 16:34:39 -0700371
Kenny Roota91203b2012-02-15 15:00:46 -0800372class Blob {
373public:
Kenny Root07438c82012-11-02 15:41:02 -0700374 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
375 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800376 mBlob.length = valueLength;
377 memcpy(mBlob.value, value, valueLength);
378
379 mBlob.info = infoLength;
380 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700381
Kenny Root07438c82012-11-02 15:41:02 -0700382 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700383 mBlob.type = uint8_t(type);
Kenny Roota91203b2012-02-15 15:00:46 -0800384 }
385
386 Blob(blob b) {
387 mBlob = b;
388 }
389
390 Blob() {}
391
Kenny Root51878182012-03-13 12:53:19 -0700392 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800393 return mBlob.value;
394 }
395
Kenny Root51878182012-03-13 12:53:19 -0700396 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800397 return mBlob.length;
398 }
399
Kenny Root51878182012-03-13 12:53:19 -0700400 const uint8_t* getInfo() const {
401 return mBlob.value + mBlob.length;
402 }
403
404 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800405 return mBlob.info;
406 }
407
Kenny Root822c3a92012-03-23 16:34:39 -0700408 uint8_t getVersion() const {
409 return mBlob.version;
410 }
411
412 void setVersion(uint8_t version) {
413 mBlob.version = version;
414 }
415
416 BlobType getType() const {
417 return BlobType(mBlob.type);
418 }
419
420 void setType(BlobType type) {
421 mBlob.type = uint8_t(type);
422 }
423
Kenny Roota91203b2012-02-15 15:00:46 -0800424 ResponseCode encryptBlob(const char* filename, AES_KEY *aes_key, Entropy* entropy) {
425 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
Kenny Root150ca932012-11-14 14:29:02 -0800426 ALOGW("Could not read random data for: %s", filename);
Kenny Roota91203b2012-02-15 15:00:46 -0800427 return SYSTEM_ERROR;
428 }
429
430 // data includes the value and the value's length
431 size_t dataLength = mBlob.length + sizeof(mBlob.length);
432 // pad data to the AES_BLOCK_SIZE
433 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
434 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
435 // encrypted data includes the digest value
436 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
437 // move info after space for padding
438 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
439 // zero padding area
440 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
441
442 mBlob.length = htonl(mBlob.length);
443 MD5(mBlob.digested, digestedLength, mBlob.digest);
444
445 uint8_t vector[AES_BLOCK_SIZE];
446 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
447 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
448 aes_key, vector, AES_ENCRYPT);
449
Kenny Root822c3a92012-03-23 16:34:39 -0700450 mBlob.reserved = 0;
Kenny Roota91203b2012-02-15 15:00:46 -0800451 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
452 size_t fileLength = encryptedLength + headerLength + mBlob.info;
453
454 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800455 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
456 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
457 if (out < 0) {
458 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800459 return SYSTEM_ERROR;
460 }
461 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
462 if (close(out) != 0) {
463 return SYSTEM_ERROR;
464 }
465 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800466 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800467 unlink(tmpFileName);
468 return SYSTEM_ERROR;
469 }
Kenny Root150ca932012-11-14 14:29:02 -0800470 if (rename(tmpFileName, filename) == -1) {
471 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
472 return SYSTEM_ERROR;
473 }
474 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800475 }
476
477 ResponseCode decryptBlob(const char* filename, AES_KEY *aes_key) {
Kenny Root150ca932012-11-14 14:29:02 -0800478 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
479 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800480 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
481 }
482 // fileLength may be less than sizeof(mBlob) since the in
483 // memory version has extra padding to tolerate rounding up to
484 // the AES_BLOCK_SIZE
485 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
486 if (close(in) != 0) {
487 return SYSTEM_ERROR;
488 }
489 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
490 if (fileLength < headerLength) {
491 return VALUE_CORRUPTED;
492 }
493
494 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
495 if (encryptedLength < 0 || encryptedLength % AES_BLOCK_SIZE != 0) {
496 return VALUE_CORRUPTED;
497 }
498 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
499 mBlob.vector, AES_DECRYPT);
500 size_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
501 uint8_t computedDigest[MD5_DIGEST_LENGTH];
502 MD5(mBlob.digested, digestedLength, computedDigest);
503 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
504 return VALUE_CORRUPTED;
505 }
506
507 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
508 mBlob.length = ntohl(mBlob.length);
509 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
510 return VALUE_CORRUPTED;
511 }
512 if (mBlob.info != 0) {
513 // move info from after padding to after data
514 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
515 }
Kenny Root07438c82012-11-02 15:41:02 -0700516 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800517 }
518
519private:
520 struct blob mBlob;
521};
522
Kenny Root70e3a862012-02-15 17:20:23 -0800523typedef struct {
524 uint32_t uid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700525 const uint8_t* filename;
Kenny Root70e3a862012-02-15 17:20:23 -0800526
527 struct listnode plist;
528} grant_t;
529
Kenny Roota91203b2012-02-15 15:00:46 -0800530class KeyStore {
531public:
Kenny Root70e3a862012-02-15 17:20:23 -0800532 KeyStore(Entropy* entropy, keymaster_device_t* device)
Kenny Root51878182012-03-13 12:53:19 -0700533 : mEntropy(entropy)
Kenny Root70e3a862012-02-15 17:20:23 -0800534 , mDevice(device)
Kenny Root51878182012-03-13 12:53:19 -0700535 , mRetry(MAX_RETRY)
536 {
Kenny Roota91203b2012-02-15 15:00:46 -0800537 if (access(MASTER_KEY_FILE, R_OK) == 0) {
538 setState(STATE_LOCKED);
539 } else {
540 setState(STATE_UNINITIALIZED);
541 }
Kenny Root70e3a862012-02-15 17:20:23 -0800542
543 list_init(&mGrants);
Kenny Roota91203b2012-02-15 15:00:46 -0800544 }
545
Kenny Root51878182012-03-13 12:53:19 -0700546 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800547 return mState;
548 }
549
Kenny Root51878182012-03-13 12:53:19 -0700550 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800551 return mRetry;
552 }
553
Kenny Root70e3a862012-02-15 17:20:23 -0800554 keymaster_device_t* getDevice() const {
555 return mDevice;
556 }
557
Kenny Root07438c82012-11-02 15:41:02 -0700558 ResponseCode initialize(const android::String8& pw) {
Kenny Roota91203b2012-02-15 15:00:46 -0800559 if (!generateMasterKey()) {
560 return SYSTEM_ERROR;
561 }
562 ResponseCode response = writeMasterKey(pw);
563 if (response != NO_ERROR) {
564 return response;
565 }
566 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700567 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800568 }
569
Kenny Root07438c82012-11-02 15:41:02 -0700570 ResponseCode writeMasterKey(const android::String8& pw) {
Kenny Roota91203b2012-02-15 15:00:46 -0800571 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
572 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
573 AES_KEY passwordAesKey;
574 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700575 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Roota91203b2012-02-15 15:00:46 -0800576 return masterKeyBlob.encryptBlob(MASTER_KEY_FILE, &passwordAesKey, mEntropy);
577 }
578
Kenny Root07438c82012-11-02 15:41:02 -0700579 ResponseCode readMasterKey(const android::String8& pw) {
Kenny Root150ca932012-11-14 14:29:02 -0800580 int in = TEMP_FAILURE_RETRY(open(MASTER_KEY_FILE, O_RDONLY));
581 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800582 return SYSTEM_ERROR;
583 }
584
585 // we read the raw blob to just to get the salt to generate
586 // the AES key, then we create the Blob to use with decryptBlob
587 blob rawBlob;
588 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
589 if (close(in) != 0) {
590 return SYSTEM_ERROR;
591 }
592 // find salt at EOF if present, otherwise we have an old file
593 uint8_t* salt;
594 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
595 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
596 } else {
597 salt = NULL;
598 }
599 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
600 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
601 AES_KEY passwordAesKey;
602 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
603 Blob masterKeyBlob(rawBlob);
604 ResponseCode response = masterKeyBlob.decryptBlob(MASTER_KEY_FILE, &passwordAesKey);
605 if (response == SYSTEM_ERROR) {
606 return SYSTEM_ERROR;
607 }
608 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
609 // if salt was missing, generate one and write a new master key file with the salt.
610 if (salt == NULL) {
611 if (!generateSalt()) {
612 return SYSTEM_ERROR;
613 }
614 response = writeMasterKey(pw);
615 }
616 if (response == NO_ERROR) {
617 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
618 setupMasterKeys();
619 }
620 return response;
621 }
622 if (mRetry <= 0) {
623 reset();
624 return UNINITIALIZED;
625 }
626 --mRetry;
627 switch (mRetry) {
628 case 0: return WRONG_PASSWORD_0;
629 case 1: return WRONG_PASSWORD_1;
630 case 2: return WRONG_PASSWORD_2;
631 case 3: return WRONG_PASSWORD_3;
632 default: return WRONG_PASSWORD_3;
633 }
634 }
635
636 bool reset() {
637 clearMasterKeys();
638 setState(STATE_UNINITIALIZED);
639
640 DIR* dir = opendir(".");
641 struct dirent* file;
642
643 if (!dir) {
644 return false;
645 }
646 while ((file = readdir(dir)) != NULL) {
647 unlink(file->d_name);
648 }
649 closedir(dir);
650 return true;
651 }
652
Kenny Root51878182012-03-13 12:53:19 -0700653 bool isEmpty() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800654 DIR* dir = opendir(".");
655 struct dirent* file;
656 if (!dir) {
657 return true;
658 }
659 bool result = true;
660 while ((file = readdir(dir)) != NULL) {
661 if (isKeyFile(file->d_name)) {
662 result = false;
663 break;
664 }
665 }
666 closedir(dir);
667 return result;
668 }
669
670 void lock() {
671 clearMasterKeys();
672 setState(STATE_LOCKED);
673 }
674
Kenny Root822c3a92012-03-23 16:34:39 -0700675 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type) {
676 ResponseCode rc = keyBlob->decryptBlob(filename, &mMasterKeyDecryption);
677 if (rc != NO_ERROR) {
678 return rc;
679 }
680
681 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -0700682 if (version < CURRENT_BLOB_VERSION) {
Kenny Root822c3a92012-03-23 16:34:39 -0700683 upgrade(filename, keyBlob, version, type);
684 }
685
Kenny Rootd53bc922013-03-21 14:10:15 -0700686 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -0700687 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
688 return KEY_NOT_FOUND;
689 }
690
691 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -0800692 }
693
694 ResponseCode put(const char* filename, Blob* keyBlob) {
695 return keyBlob->encryptBlob(filename, &mMasterKeyEncryption, mEntropy);
696 }
697
Kenny Root07438c82012-11-02 15:41:02 -0700698 void addGrant(const char* filename, uid_t granteeUid) {
699 grant_t *grant = getGrant(filename, granteeUid);
Kenny Root70e3a862012-02-15 17:20:23 -0800700 if (grant == NULL) {
701 grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -0700702 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700703 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root70e3a862012-02-15 17:20:23 -0800704 list_add_tail(&mGrants, &grant->plist);
705 }
706 }
707
Kenny Root07438c82012-11-02 15:41:02 -0700708 bool removeGrant(const char* filename, uid_t granteeUid) {
709 grant_t *grant = getGrant(filename, granteeUid);
Kenny Root70e3a862012-02-15 17:20:23 -0800710 if (grant != NULL) {
711 list_remove(&grant->plist);
712 delete grant;
713 return true;
714 }
715
716 return false;
717 }
718
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700719 bool hasGrant(const char* filename, const uid_t uid) const {
720 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -0800721 }
722
Kenny Root07438c82012-11-02 15:41:02 -0700723 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename) {
Kenny Root822c3a92012-03-23 16:34:39 -0700724 uint8_t* data;
725 size_t dataLength;
726 int rc;
727
728 if (mDevice->import_keypair == NULL) {
729 ALOGE("Keymaster doesn't support import!");
730 return SYSTEM_ERROR;
731 }
732
Kenny Root07438c82012-11-02 15:41:02 -0700733 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700734 if (rc) {
735 ALOGE("Error while importing keypair: %d", rc);
736 return SYSTEM_ERROR;
737 }
738
739 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
740 free(data);
741
742 return put(filename, &keyBlob);
743 }
744
Kenny Root8ddf35a2013-03-29 11:15:50 -0700745 bool isHardwareBacked() const {
746 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) != 0;
747 }
748
Kenny Roota91203b2012-02-15 15:00:46 -0800749private:
750 static const char* MASTER_KEY_FILE;
751 static const int MASTER_KEY_SIZE_BYTES = 16;
752 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
753
754 static const int MAX_RETRY = 4;
755 static const size_t SALT_SIZE = 16;
756
757 Entropy* mEntropy;
758
Kenny Root70e3a862012-02-15 17:20:23 -0800759 keymaster_device_t* mDevice;
760
Kenny Roota91203b2012-02-15 15:00:46 -0800761 State mState;
762 int8_t mRetry;
763
764 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
765 uint8_t mSalt[SALT_SIZE];
766
767 AES_KEY mMasterKeyEncryption;
768 AES_KEY mMasterKeyDecryption;
769
Kenny Root70e3a862012-02-15 17:20:23 -0800770 struct listnode mGrants;
771
Kenny Roota91203b2012-02-15 15:00:46 -0800772 void setState(State state) {
773 mState = state;
774 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
775 mRetry = MAX_RETRY;
776 }
777 }
778
779 bool generateSalt() {
780 return mEntropy->generate_random_data(mSalt, sizeof(mSalt));
781 }
782
783 bool generateMasterKey() {
784 if (!mEntropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
785 return false;
786 }
787 if (!generateSalt()) {
788 return false;
789 }
790 return true;
791 }
792
793 void setupMasterKeys() {
794 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
795 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
796 setState(STATE_NO_ERROR);
797 }
798
799 void clearMasterKeys() {
800 memset(mMasterKey, 0, sizeof(mMasterKey));
801 memset(mSalt, 0, sizeof(mSalt));
802 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
803 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
804 }
805
Kenny Root07438c82012-11-02 15:41:02 -0700806 static void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
807 uint8_t* salt) {
Kenny Roota91203b2012-02-15 15:00:46 -0800808 size_t saltSize;
809 if (salt != NULL) {
810 saltSize = SALT_SIZE;
811 } else {
812 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
813 salt = (uint8_t*) "keystore";
814 // sizeof = 9, not strlen = 8
815 saltSize = sizeof("keystore");
816 }
Kenny Root07438c82012-11-02 15:41:02 -0700817
818 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
819 saltSize, 8192, keySize, key);
Kenny Roota91203b2012-02-15 15:00:46 -0800820 }
821
822 static bool isKeyFile(const char* filename) {
823 return ((strcmp(filename, MASTER_KEY_FILE) != 0)
824 && (strcmp(filename, ".") != 0)
825 && (strcmp(filename, "..") != 0));
826 }
Kenny Root70e3a862012-02-15 17:20:23 -0800827
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700828 grant_t* getGrant(const char* filename, uid_t uid) const {
Kenny Root70e3a862012-02-15 17:20:23 -0800829 struct listnode *node;
830 grant_t *grant;
831
832 list_for_each(node, &mGrants) {
833 grant = node_to_item(node, grant_t, plist);
834 if (grant->uid == uid
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700835 && !strcmp(reinterpret_cast<const char*>(grant->filename),
836 filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -0800837 return grant;
838 }
839 }
840
841 return NULL;
842 }
843
Kenny Root822c3a92012-03-23 16:34:39 -0700844 /**
845 * Upgrade code. This will upgrade the key from the current version
846 * to whatever is newest.
847 */
848 void upgrade(const char* filename, Blob* blob, const uint8_t oldVersion, const BlobType type) {
849 bool updated = false;
850 uint8_t version = oldVersion;
851
852 /* From V0 -> V1: All old types were unknown */
853 if (version == 0) {
854 ALOGV("upgrading to version 1 and setting type %d", type);
855
856 blob->setType(type);
857 if (type == TYPE_KEY_PAIR) {
858 importBlobAsKey(blob, filename);
859 }
860 version = 1;
861 updated = true;
862 }
863
864 /*
865 * If we've updated, set the key blob to the right version
866 * and write it.
867 * */
868 if (updated) {
869 ALOGV("updated and writing file %s", filename);
870 blob->setVersion(version);
871 this->put(filename, blob);
872 }
873 }
874
875 /**
876 * Takes a blob that is an PEM-encoded RSA key as a byte array and
877 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
878 * Then it overwrites the original blob with the new blob
879 * format that is returned from the keymaster.
880 */
881 ResponseCode importBlobAsKey(Blob* blob, const char* filename) {
882 // We won't even write to the blob directly with this BIO, so const_cast is okay.
883 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
884 if (b.get() == NULL) {
885 ALOGE("Problem instantiating BIO");
886 return SYSTEM_ERROR;
887 }
888
889 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
890 if (pkey.get() == NULL) {
891 ALOGE("Couldn't read old PEM file");
892 return SYSTEM_ERROR;
893 }
894
895 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
896 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
897 if (len < 0) {
898 ALOGE("Couldn't measure PKCS#8 length");
899 return SYSTEM_ERROR;
900 }
901
Kenny Root70c98892013-02-07 09:10:36 -0800902 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
903 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -0700904 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
905 ALOGE("Couldn't convert to PKCS#8");
906 return SYSTEM_ERROR;
907 }
908
Kenny Root70c98892013-02-07 09:10:36 -0800909 ResponseCode rc = importKey(pkcs8key.get(), len, filename);
Kenny Root822c3a92012-03-23 16:34:39 -0700910 if (rc != NO_ERROR) {
911 return rc;
912 }
913
914 return get(filename, blob, TYPE_KEY_PAIR);
915 }
Kenny Roota91203b2012-02-15 15:00:46 -0800916};
917
918const char* KeyStore::MASTER_KEY_FILE = ".masterkey";
919
Kenny Root07438c82012-11-02 15:41:02 -0700920static ResponseCode get_key_for_name(KeyStore* keyStore, Blob* keyBlob,
921 const android::String8& keyName, const uid_t uid, const BlobType type) {
Kenny Root70e3a862012-02-15 17:20:23 -0800922 char filename[NAME_MAX];
923
924 encode_key_for_uid(filename, uid, keyName);
Kenny Root822c3a92012-03-23 16:34:39 -0700925 ResponseCode responseCode = keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800926 if (responseCode == NO_ERROR) {
927 return responseCode;
928 }
929
Kenny Root49468902013-03-19 13:41:33 -0700930 // If this is one of the legacy UID->UID mappings, use it.
931 uid_t euid = get_keystore_euid(uid);
932 if (euid != uid) {
933 encode_key_for_uid(filename, euid, keyName);
Kenny Root822c3a92012-03-23 16:34:39 -0700934 responseCode = keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800935 if (responseCode == NO_ERROR) {
936 return responseCode;
937 }
938 }
939
940 // They might be using a granted key.
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700941 encode_key(filename, keyName);
942 if (!keyStore->hasGrant(filename, uid)) {
Kenny Root70e3a862012-02-15 17:20:23 -0800943 return responseCode;
944 }
945
946 // It is a granted key. Try to load it.
Kenny Root822c3a92012-03-23 16:34:39 -0700947 return keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800948}
949
Kenny Root07438c82012-11-02 15:41:02 -0700950namespace android {
951class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
952public:
953 KeyStoreProxy(KeyStore* keyStore)
954 : mKeyStore(keyStore)
955 {
Kenny Roota91203b2012-02-15 15:00:46 -0800956 }
Kenny Roota91203b2012-02-15 15:00:46 -0800957
Kenny Root07438c82012-11-02 15:41:02 -0700958 void binderDied(const wp<IBinder>&) {
959 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -0700960 }
Kenny Roota91203b2012-02-15 15:00:46 -0800961
Kenny Root07438c82012-11-02 15:41:02 -0700962 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -0800963 uid_t callingUid = IPCThreadState::self()->getCallingUid();
964 if (!has_permission(callingUid, P_TEST)) {
965 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -0700966 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -0800967 }
Kenny Roota91203b2012-02-15 15:00:46 -0800968
Kenny Root07438c82012-11-02 15:41:02 -0700969 return mKeyStore->getState();
Kenny Root298e7b12012-03-26 13:54:44 -0700970 }
971
Kenny Root07438c82012-11-02 15:41:02 -0700972 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -0800973 uid_t callingUid = IPCThreadState::self()->getCallingUid();
974 if (!has_permission(callingUid, P_GET)) {
975 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -0700976 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -0800977 }
Kenny Root07438c82012-11-02 15:41:02 -0700978
Kenny Root9d45d1c2013-02-14 10:32:30 -0800979 State state = mKeyStore->getState();
980 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -0700981 ALOGD("calling get in state: %d", state);
982 return state;
Kenny Roota91203b2012-02-15 15:00:46 -0800983 }
Kenny Root07438c82012-11-02 15:41:02 -0700984
985 String8 name8(name);
986 char filename[NAME_MAX];
Kenny Root07438c82012-11-02 15:41:02 -0700987 Blob keyBlob;
Kenny Root49468902013-03-19 13:41:33 -0700988
989 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
990 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -0700991 if (responseCode != ::NO_ERROR) {
Kenny Root150ca932012-11-14 14:29:02 -0800992 ALOGW("Could not read %s", filename);
Kenny Root07438c82012-11-02 15:41:02 -0700993 *item = NULL;
994 *itemLength = 0;
995 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -0800996 }
Kenny Roota91203b2012-02-15 15:00:46 -0800997
Kenny Root07438c82012-11-02 15:41:02 -0700998 *item = (uint8_t*) malloc(keyBlob.getLength());
999 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1000 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001001
Kenny Root07438c82012-11-02 15:41:02 -07001002 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001003 }
1004
Kenny Root49468902013-03-19 13:41:33 -07001005 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001006 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1007 if (!has_permission(callingUid, P_INSERT)) {
1008 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001009 return ::PERMISSION_DENIED;
1010 }
Kenny Root07438c82012-11-02 15:41:02 -07001011
Kenny Root49468902013-03-19 13:41:33 -07001012 if (targetUid == -1) {
1013 targetUid = callingUid;
1014 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001015 return ::PERMISSION_DENIED;
1016 }
1017
Kenny Root9d45d1c2013-02-14 10:32:30 -08001018 State state = mKeyStore->getState();
1019 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001020 ALOGD("calling insert in state: %d", state);
1021 return state;
1022 }
1023
1024 String8 name8(name);
1025 char filename[NAME_MAX];
1026
Kenny Root49468902013-03-19 13:41:33 -07001027 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001028
1029 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
1030 return mKeyStore->put(filename, &keyBlob);
Kenny Root70e3a862012-02-15 17:20:23 -08001031 }
1032
Kenny Root49468902013-03-19 13:41:33 -07001033 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001034 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1035 if (!has_permission(callingUid, P_DELETE)) {
1036 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001037 return ::PERMISSION_DENIED;
1038 }
Kenny Root70e3a862012-02-15 17:20:23 -08001039
Kenny Root49468902013-03-19 13:41:33 -07001040 if (targetUid == -1) {
1041 targetUid = callingUid;
1042 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001043 return ::PERMISSION_DENIED;
1044 }
1045
Kenny Root07438c82012-11-02 15:41:02 -07001046 String8 name8(name);
1047 char filename[NAME_MAX];
1048
Kenny Root49468902013-03-19 13:41:33 -07001049 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001050
1051 Blob keyBlob;
1052 ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, TYPE_GENERIC);
1053 if (responseCode != ::NO_ERROR) {
1054 return responseCode;
1055 }
1056 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001057 }
1058
Kenny Root49468902013-03-19 13:41:33 -07001059 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001060 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1061 if (!has_permission(callingUid, P_EXIST)) {
1062 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001063 return ::PERMISSION_DENIED;
1064 }
Kenny Root70e3a862012-02-15 17:20:23 -08001065
Kenny Root49468902013-03-19 13:41:33 -07001066 if (targetUid == -1) {
1067 targetUid = callingUid;
1068 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001069 return ::PERMISSION_DENIED;
1070 }
1071
Kenny Root07438c82012-11-02 15:41:02 -07001072 String8 name8(name);
1073 char filename[NAME_MAX];
Kenny Root70e3a862012-02-15 17:20:23 -08001074
Kenny Root49468902013-03-19 13:41:33 -07001075 encode_key_for_uid(filename, targetUid, name8);
Kenny Root70e3a862012-02-15 17:20:23 -08001076
Kenny Root07438c82012-11-02 15:41:02 -07001077 if (access(filename, R_OK) == -1) {
1078 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1079 }
1080 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001081 }
1082
Kenny Root49468902013-03-19 13:41:33 -07001083 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001084 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1085 if (!has_permission(callingUid, P_SAW)) {
1086 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001087 return ::PERMISSION_DENIED;
1088 }
Kenny Root70e3a862012-02-15 17:20:23 -08001089
Kenny Root49468902013-03-19 13:41:33 -07001090 if (targetUid == -1) {
1091 targetUid = callingUid;
1092 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001093 return ::PERMISSION_DENIED;
1094 }
1095
Kenny Root07438c82012-11-02 15:41:02 -07001096 DIR* dir = opendir(".");
1097 if (!dir) {
1098 return ::SYSTEM_ERROR;
1099 }
Kenny Root70e3a862012-02-15 17:20:23 -08001100
Kenny Root07438c82012-11-02 15:41:02 -07001101 const String8 prefix8(prefix);
1102 char filename[NAME_MAX];
Kenny Root70e3a862012-02-15 17:20:23 -08001103
Kenny Root49468902013-03-19 13:41:33 -07001104 int n = encode_key_for_uid(filename, targetUid, prefix8);
Kenny Root70e3a862012-02-15 17:20:23 -08001105
Kenny Root07438c82012-11-02 15:41:02 -07001106 struct dirent* file;
1107 while ((file = readdir(dir)) != NULL) {
1108 if (!strncmp(filename, file->d_name, n)) {
1109 const char* p = &file->d_name[n];
1110 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001111
Kenny Root07438c82012-11-02 15:41:02 -07001112 size_t extra = decode_key_length(p, plen);
1113 char *match = (char*) malloc(extra + 1);
1114 if (match != NULL) {
1115 decode_key(match, p, plen);
1116 matches->push(String16(match, extra));
1117 free(match);
1118 } else {
1119 ALOGW("could not allocate match of size %zd", extra);
1120 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001121 }
1122 }
Kenny Root07438c82012-11-02 15:41:02 -07001123 closedir(dir);
1124
1125 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001126 }
1127
Kenny Root07438c82012-11-02 15:41:02 -07001128 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001129 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1130 if (!has_permission(callingUid, P_RESET)) {
1131 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001132 return ::PERMISSION_DENIED;
1133 }
1134
1135 ResponseCode rc = mKeyStore->reset() ? ::NO_ERROR : ::SYSTEM_ERROR;
1136
1137 const keymaster_device_t* device = mKeyStore->getDevice();
1138 if (device == NULL) {
1139 ALOGE("No keymaster device!");
1140 return ::SYSTEM_ERROR;
1141 }
1142
1143 if (device->delete_all == NULL) {
1144 ALOGV("keymaster device doesn't implement delete_all");
1145 return rc;
1146 }
1147
1148 if (device->delete_all(device)) {
1149 ALOGE("Problem calling keymaster's delete_all");
1150 return ::SYSTEM_ERROR;
1151 }
1152
Kenny Root9a53d3e2012-08-14 10:47:54 -07001153 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001154 }
1155
Kenny Root07438c82012-11-02 15:41:02 -07001156 /*
1157 * Here is the history. To improve the security, the parameters to generate the
1158 * master key has been changed. To make a seamless transition, we update the
1159 * file using the same password when the user unlock it for the first time. If
1160 * any thing goes wrong during the transition, the new file will not overwrite
1161 * the old one. This avoids permanent damages of the existing data.
1162 */
1163 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001164 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1165 if (!has_permission(callingUid, P_PASSWORD)) {
1166 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001167 return ::PERMISSION_DENIED;
1168 }
Kenny Root70e3a862012-02-15 17:20:23 -08001169
Kenny Root07438c82012-11-02 15:41:02 -07001170 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001171
Kenny Root07438c82012-11-02 15:41:02 -07001172 switch (mKeyStore->getState()) {
1173 case ::STATE_UNINITIALIZED: {
1174 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
1175 return mKeyStore->initialize(password8);
1176 }
1177 case ::STATE_NO_ERROR: {
1178 // rewrite master key with new password.
1179 return mKeyStore->writeMasterKey(password8);
1180 }
1181 case ::STATE_LOCKED: {
1182 // read master key, decrypt with password, initialize mMasterKey*.
1183 return mKeyStore->readMasterKey(password8);
1184 }
1185 }
1186 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001187 }
1188
Kenny Root07438c82012-11-02 15:41:02 -07001189 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001190 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1191 if (!has_permission(callingUid, P_LOCK)) {
1192 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001193 return ::PERMISSION_DENIED;
1194 }
Kenny Root70e3a862012-02-15 17:20:23 -08001195
Kenny Root9d45d1c2013-02-14 10:32:30 -08001196 State state = mKeyStore->getState();
1197 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001198 ALOGD("calling lock in state: %d", state);
1199 return state;
1200 }
1201
1202 mKeyStore->lock();
1203 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001204 }
1205
Kenny Root07438c82012-11-02 15:41:02 -07001206 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001207 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1208 if (!has_permission(callingUid, P_UNLOCK)) {
1209 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001210 return ::PERMISSION_DENIED;
1211 }
1212
Kenny Root9d45d1c2013-02-14 10:32:30 -08001213 State state = mKeyStore->getState();
1214 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001215 ALOGD("calling unlock when not locked");
1216 return state;
1217 }
1218
1219 const String8 password8(pw);
1220 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001221 }
1222
Kenny Root07438c82012-11-02 15:41:02 -07001223 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001224 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1225 if (!has_permission(callingUid, P_ZERO)) {
1226 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001227 return -1;
1228 }
Kenny Root70e3a862012-02-15 17:20:23 -08001229
Kenny Root07438c82012-11-02 15:41:02 -07001230 return mKeyStore->isEmpty() ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001231 }
1232
Kenny Root49468902013-03-19 13:41:33 -07001233 int32_t generate(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001234 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1235 if (!has_permission(callingUid, P_INSERT)) {
1236 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001237 return ::PERMISSION_DENIED;
1238 }
Kenny Root70e3a862012-02-15 17:20:23 -08001239
Kenny Root49468902013-03-19 13:41:33 -07001240 if (targetUid == -1) {
1241 targetUid = callingUid;
1242 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001243 return ::PERMISSION_DENIED;
1244 }
1245
Kenny Root9d45d1c2013-02-14 10:32:30 -08001246 State state = mKeyStore->getState();
1247 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001248 ALOGD("calling generate in state: %d", state);
1249 return state;
1250 }
Kenny Root70e3a862012-02-15 17:20:23 -08001251
Kenny Root07438c82012-11-02 15:41:02 -07001252 String8 name8(name);
1253 char filename[NAME_MAX];
1254
1255 uint8_t* data;
1256 size_t dataLength;
1257 int rc;
1258
1259 const keymaster_device_t* device = mKeyStore->getDevice();
1260 if (device == NULL) {
1261 return ::SYSTEM_ERROR;
1262 }
1263
1264 if (device->generate_keypair == NULL) {
1265 return ::SYSTEM_ERROR;
1266 }
1267
1268 keymaster_rsa_keygen_params_t rsa_params;
1269 rsa_params.modulus_size = 2048;
1270 rsa_params.public_exponent = 0x10001;
1271
1272 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1273 if (rc) {
1274 return ::SYSTEM_ERROR;
1275 }
1276
Kenny Root49468902013-03-19 13:41:33 -07001277 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001278
1279 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1280 free(data);
1281
1282 return mKeyStore->put(filename, &keyBlob);
Kenny Root70e3a862012-02-15 17:20:23 -08001283 }
1284
Kenny Root49468902013-03-19 13:41:33 -07001285 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001286 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1287 if (!has_permission(callingUid, P_INSERT)) {
1288 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001289 return ::PERMISSION_DENIED;
1290 }
Kenny Root07438c82012-11-02 15:41:02 -07001291
Kenny Root49468902013-03-19 13:41:33 -07001292 if (targetUid == -1) {
1293 targetUid = callingUid;
1294 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001295 return ::PERMISSION_DENIED;
1296 }
1297
Kenny Root9d45d1c2013-02-14 10:32:30 -08001298 State state = mKeyStore->getState();
1299 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001300 ALOGD("calling import in state: %d", state);
1301 return state;
1302 }
1303
1304 String8 name8(name);
1305 char filename[NAME_MAX];
1306
Kenny Root49468902013-03-19 13:41:33 -07001307 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001308
1309 return mKeyStore->importKey(data, length, filename);
Kenny Root70e3a862012-02-15 17:20:23 -08001310 }
1311
Kenny Root07438c82012-11-02 15:41:02 -07001312 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1313 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001314 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1315 if (!has_permission(callingUid, P_SIGN)) {
1316 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001317 return ::PERMISSION_DENIED;
1318 }
Kenny Root07438c82012-11-02 15:41:02 -07001319
Kenny Root9d45d1c2013-02-14 10:32:30 -08001320 State state = mKeyStore->getState();
1321 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001322 ALOGD("calling sign in state: %d", state);
1323 return state;
1324 }
1325
1326 Blob keyBlob;
1327 String8 name8(name);
1328
Kenny Rootd38a0b02013-02-13 12:59:14 -08001329 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001330 int rc;
1331
Kenny Rootd38a0b02013-02-13 12:59:14 -08001332 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1333 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001334 if (responseCode != ::NO_ERROR) {
1335 return responseCode;
1336 }
1337
1338 const keymaster_device_t* device = mKeyStore->getDevice();
1339 if (device == NULL) {
1340 ALOGE("no keymaster device; cannot sign");
1341 return ::SYSTEM_ERROR;
1342 }
1343
1344 if (device->sign_data == NULL) {
1345 ALOGE("device doesn't implement signing");
1346 return ::SYSTEM_ERROR;
1347 }
1348
1349 keymaster_rsa_sign_params_t params;
1350 params.digest_type = DIGEST_NONE;
1351 params.padding_type = PADDING_NONE;
1352
1353 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1354 data, length, out, outLength);
1355 if (rc) {
1356 ALOGW("device couldn't sign data");
1357 return ::SYSTEM_ERROR;
1358 }
1359
1360 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001361 }
1362
Kenny Root07438c82012-11-02 15:41:02 -07001363 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1364 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001365 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1366 if (!has_permission(callingUid, P_VERIFY)) {
1367 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001368 return ::PERMISSION_DENIED;
1369 }
Kenny Root70e3a862012-02-15 17:20:23 -08001370
Kenny Root9d45d1c2013-02-14 10:32:30 -08001371 State state = mKeyStore->getState();
1372 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001373 ALOGD("calling verify in state: %d", state);
1374 return state;
1375 }
Kenny Root70e3a862012-02-15 17:20:23 -08001376
Kenny Root07438c82012-11-02 15:41:02 -07001377 Blob keyBlob;
1378 String8 name8(name);
1379 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001380
Kenny Root49468902013-03-19 13:41:33 -07001381 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1382 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001383 if (responseCode != ::NO_ERROR) {
1384 return responseCode;
1385 }
Kenny Root70e3a862012-02-15 17:20:23 -08001386
Kenny Root07438c82012-11-02 15:41:02 -07001387 const keymaster_device_t* device = mKeyStore->getDevice();
1388 if (device == NULL) {
1389 return ::SYSTEM_ERROR;
1390 }
Kenny Root70e3a862012-02-15 17:20:23 -08001391
Kenny Root07438c82012-11-02 15:41:02 -07001392 if (device->verify_data == NULL) {
1393 return ::SYSTEM_ERROR;
1394 }
Kenny Root70e3a862012-02-15 17:20:23 -08001395
Kenny Root07438c82012-11-02 15:41:02 -07001396 keymaster_rsa_sign_params_t params;
1397 params.digest_type = DIGEST_NONE;
1398 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001399
Kenny Root07438c82012-11-02 15:41:02 -07001400 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1401 data, dataLength, signature, signatureLength);
1402 if (rc) {
1403 return ::SYSTEM_ERROR;
1404 } else {
1405 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001406 }
1407 }
Kenny Root07438c82012-11-02 15:41:02 -07001408
1409 /*
1410 * TODO: The abstraction between things stored in hardware and regular blobs
1411 * of data stored on the filesystem should be moved down to keystore itself.
1412 * Unfortunately the Java code that calls this has naming conventions that it
1413 * knows about. Ideally keystore shouldn't be used to store random blobs of
1414 * data.
1415 *
1416 * Until that happens, it's necessary to have a separate "get_pubkey" and
1417 * "del_key" since the Java code doesn't really communicate what it's
1418 * intentions are.
1419 */
1420 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001421 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1422 if (!has_permission(callingUid, P_GET)) {
1423 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001424 return ::PERMISSION_DENIED;
1425 }
Kenny Root07438c82012-11-02 15:41:02 -07001426
Kenny Root9d45d1c2013-02-14 10:32:30 -08001427 State state = mKeyStore->getState();
1428 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001429 ALOGD("calling get_pubkey in state: %d", state);
1430 return state;
1431 }
1432
1433 Blob keyBlob;
1434 String8 name8(name);
1435
Kenny Rootd38a0b02013-02-13 12:59:14 -08001436 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001437
Kenny Rootd38a0b02013-02-13 12:59:14 -08001438 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07001439 TYPE_KEY_PAIR);
1440 if (responseCode != ::NO_ERROR) {
1441 return responseCode;
1442 }
1443
1444 const keymaster_device_t* device = mKeyStore->getDevice();
1445 if (device == NULL) {
1446 return ::SYSTEM_ERROR;
1447 }
1448
1449 if (device->get_keypair_public == NULL) {
1450 ALOGE("device has no get_keypair_public implementation!");
1451 return ::SYSTEM_ERROR;
1452 }
1453
1454 int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
1455 pubkeyLength);
1456 if (rc) {
1457 return ::SYSTEM_ERROR;
1458 }
1459
1460 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001461 }
Kenny Root07438c82012-11-02 15:41:02 -07001462
Kenny Root49468902013-03-19 13:41:33 -07001463 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001464 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1465 if (!has_permission(callingUid, P_DELETE)) {
1466 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001467 return ::PERMISSION_DENIED;
1468 }
Kenny Root07438c82012-11-02 15:41:02 -07001469
Kenny Root49468902013-03-19 13:41:33 -07001470 if (targetUid == -1) {
1471 targetUid = callingUid;
1472 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001473 return ::PERMISSION_DENIED;
1474 }
1475
Kenny Root07438c82012-11-02 15:41:02 -07001476 String8 name8(name);
1477 char filename[NAME_MAX];
1478
Kenny Root49468902013-03-19 13:41:33 -07001479 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001480
1481 Blob keyBlob;
1482 ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, ::TYPE_KEY_PAIR);
1483 if (responseCode != ::NO_ERROR) {
1484 return responseCode;
1485 }
1486
1487 ResponseCode rc = ::NO_ERROR;
1488
1489 const keymaster_device_t* device = mKeyStore->getDevice();
1490 if (device == NULL) {
1491 rc = ::SYSTEM_ERROR;
1492 } else {
1493 // A device doesn't have to implement delete_keypair.
1494 if (device->delete_keypair != NULL) {
1495 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1496 rc = ::SYSTEM_ERROR;
1497 }
1498 }
1499 }
1500
1501 if (rc != ::NO_ERROR) {
1502 return rc;
1503 }
1504
1505 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1506 }
1507
1508 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001509 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1510 if (!has_permission(callingUid, P_GRANT)) {
1511 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001512 return ::PERMISSION_DENIED;
1513 }
Kenny Root07438c82012-11-02 15:41:02 -07001514
Kenny Root9d45d1c2013-02-14 10:32:30 -08001515 State state = mKeyStore->getState();
1516 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001517 ALOGD("calling grant in state: %d", state);
1518 return state;
1519 }
1520
1521 String8 name8(name);
1522 char filename[NAME_MAX];
1523
Kenny Rootd38a0b02013-02-13 12:59:14 -08001524 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001525
1526 if (access(filename, R_OK) == -1) {
1527 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1528 }
1529
1530 mKeyStore->addGrant(filename, granteeUid);
1531 return ::NO_ERROR;
1532 }
1533
1534 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001535 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1536 if (!has_permission(callingUid, P_GRANT)) {
1537 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001538 return ::PERMISSION_DENIED;
1539 }
Kenny Root07438c82012-11-02 15:41:02 -07001540
Kenny Root9d45d1c2013-02-14 10:32:30 -08001541 State state = mKeyStore->getState();
1542 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001543 ALOGD("calling ungrant in state: %d", state);
1544 return state;
1545 }
1546
1547 String8 name8(name);
1548 char filename[NAME_MAX];
1549
Kenny Rootd38a0b02013-02-13 12:59:14 -08001550 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001551
1552 if (access(filename, R_OK) == -1) {
1553 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1554 }
1555
1556 return mKeyStore->removeGrant(filename, granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
1557 }
1558
1559 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001560 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1561 if (!has_permission(callingUid, P_GET)) {
1562 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08001563 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001564 }
Kenny Root07438c82012-11-02 15:41:02 -07001565
1566 String8 name8(name);
1567 char filename[NAME_MAX];
1568
Kenny Rootd38a0b02013-02-13 12:59:14 -08001569 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001570
1571 if (access(filename, R_OK) == -1) {
Kenny Root36a9e232013-02-04 14:24:15 -08001572 ALOGW("could not access %s for getmtime", filename);
1573 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001574 }
1575
Kenny Root150ca932012-11-14 14:29:02 -08001576 int fd = TEMP_FAILURE_RETRY(open(filename, O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07001577 if (fd < 0) {
Kenny Root36a9e232013-02-04 14:24:15 -08001578 ALOGW("could not open %s for getmtime", filename);
1579 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001580 }
1581
1582 struct stat s;
1583 int ret = fstat(fd, &s);
1584 close(fd);
1585 if (ret == -1) {
Kenny Root36a9e232013-02-04 14:24:15 -08001586 ALOGW("could not stat %s for getmtime", filename);
1587 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001588 }
1589
Kenny Root36a9e232013-02-04 14:24:15 -08001590 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07001591 }
1592
Kenny Rootd53bc922013-03-21 14:10:15 -07001593 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
1594 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07001595 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Rootd53bc922013-03-21 14:10:15 -07001596 if (!has_permission(callingUid, P_DUPLICATE)) {
1597 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07001598 return -1L;
1599 }
1600
1601 State state = mKeyStore->getState();
1602 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07001603 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07001604 return state;
1605 }
1606
Kenny Rootd53bc922013-03-21 14:10:15 -07001607 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
1608 srcUid = callingUid;
1609 } else if (!is_granted_to(callingUid, srcUid)) {
1610 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07001611 return ::PERMISSION_DENIED;
1612 }
1613
Kenny Rootd53bc922013-03-21 14:10:15 -07001614 if (destUid == -1) {
1615 destUid = callingUid;
1616 }
1617
1618 if (srcUid != destUid) {
1619 if (static_cast<uid_t>(srcUid) != callingUid) {
1620 ALOGD("can only duplicate from caller to other or to same uid: "
1621 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
1622 return ::PERMISSION_DENIED;
1623 }
1624
1625 if (!is_granted_to(callingUid, destUid)) {
1626 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
1627 return ::PERMISSION_DENIED;
1628 }
1629 }
1630
1631 String8 source8(srcKey);
Kenny Root02254072013-03-20 11:48:19 -07001632 char source[NAME_MAX];
1633
Kenny Rootd53bc922013-03-21 14:10:15 -07001634 encode_key_for_uid(source, srcUid, source8);
Kenny Root02254072013-03-20 11:48:19 -07001635
Kenny Rootd53bc922013-03-21 14:10:15 -07001636 String8 target8(destKey);
Kenny Root02254072013-03-20 11:48:19 -07001637 char target[NAME_MAX];
1638
Kenny Rootd53bc922013-03-21 14:10:15 -07001639 encode_key_for_uid(target, destUid, target8);
Kenny Root02254072013-03-20 11:48:19 -07001640
Kenny Rootd53bc922013-03-21 14:10:15 -07001641 if (access(target, W_OK) != -1 || errno != ENOENT) {
1642 ALOGD("destination already exists: %s", target);
Kenny Root02254072013-03-20 11:48:19 -07001643 return ::SYSTEM_ERROR;
1644 }
1645
Kenny Rootd53bc922013-03-21 14:10:15 -07001646 Blob keyBlob;
1647 ResponseCode responseCode = mKeyStore->get(source, &keyBlob, TYPE_ANY);
1648 if (responseCode != ::NO_ERROR) {
1649 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07001650 }
Kenny Rootd53bc922013-03-21 14:10:15 -07001651
1652 return mKeyStore->put(target, &keyBlob);
Kenny Root02254072013-03-20 11:48:19 -07001653 }
1654
Kenny Root8ddf35a2013-03-29 11:15:50 -07001655 int32_t is_hardware_backed() {
1656 return mKeyStore->isHardwareBacked() ? 1 : 0;
1657 }
1658
Kenny Root07438c82012-11-02 15:41:02 -07001659private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08001660 inline bool isKeystoreUnlocked(State state) {
1661 switch (state) {
1662 case ::STATE_NO_ERROR:
1663 return true;
1664 case ::STATE_UNINITIALIZED:
1665 case ::STATE_LOCKED:
1666 return false;
1667 }
1668 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001669 }
1670
1671 ::KeyStore* mKeyStore;
1672};
1673
1674}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08001675
1676int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08001677 if (argc < 2) {
1678 ALOGE("A directory must be specified!");
1679 return 1;
1680 }
1681 if (chdir(argv[1]) == -1) {
1682 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
1683 return 1;
1684 }
1685
1686 Entropy entropy;
1687 if (!entropy.open()) {
1688 return 1;
1689 }
Kenny Root70e3a862012-02-15 17:20:23 -08001690
1691 keymaster_device_t* dev;
1692 if (keymaster_device_initialize(&dev)) {
1693 ALOGE("keystore keymaster could not be initialized; exiting");
1694 return 1;
1695 }
1696
Kenny Root70e3a862012-02-15 17:20:23 -08001697 KeyStore keyStore(&entropy, dev);
Kenny Root07438c82012-11-02 15:41:02 -07001698 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
1699 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
1700 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
1701 if (ret != android::OK) {
1702 ALOGE("Couldn't register binder service!");
1703 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08001704 }
Kenny Root07438c82012-11-02 15:41:02 -07001705
1706 /*
1707 * We're the only thread in existence, so we're just going to process
1708 * Binder transaction as a single-threaded program.
1709 */
1710 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08001711
1712 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08001713 return 1;
1714}