blob: 385f005e9fb14be2348f9d0a04926eba673b3b58 [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 Roota91203b2012-02-15 15:00:46 -0800745private:
746 static const char* MASTER_KEY_FILE;
747 static const int MASTER_KEY_SIZE_BYTES = 16;
748 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
749
750 static const int MAX_RETRY = 4;
751 static const size_t SALT_SIZE = 16;
752
753 Entropy* mEntropy;
754
Kenny Root70e3a862012-02-15 17:20:23 -0800755 keymaster_device_t* mDevice;
756
Kenny Roota91203b2012-02-15 15:00:46 -0800757 State mState;
758 int8_t mRetry;
759
760 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
761 uint8_t mSalt[SALT_SIZE];
762
763 AES_KEY mMasterKeyEncryption;
764 AES_KEY mMasterKeyDecryption;
765
Kenny Root70e3a862012-02-15 17:20:23 -0800766 struct listnode mGrants;
767
Kenny Roota91203b2012-02-15 15:00:46 -0800768 void setState(State state) {
769 mState = state;
770 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
771 mRetry = MAX_RETRY;
772 }
773 }
774
775 bool generateSalt() {
776 return mEntropy->generate_random_data(mSalt, sizeof(mSalt));
777 }
778
779 bool generateMasterKey() {
780 if (!mEntropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
781 return false;
782 }
783 if (!generateSalt()) {
784 return false;
785 }
786 return true;
787 }
788
789 void setupMasterKeys() {
790 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
791 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
792 setState(STATE_NO_ERROR);
793 }
794
795 void clearMasterKeys() {
796 memset(mMasterKey, 0, sizeof(mMasterKey));
797 memset(mSalt, 0, sizeof(mSalt));
798 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
799 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
800 }
801
Kenny Root07438c82012-11-02 15:41:02 -0700802 static void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
803 uint8_t* salt) {
Kenny Roota91203b2012-02-15 15:00:46 -0800804 size_t saltSize;
805 if (salt != NULL) {
806 saltSize = SALT_SIZE;
807 } else {
808 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
809 salt = (uint8_t*) "keystore";
810 // sizeof = 9, not strlen = 8
811 saltSize = sizeof("keystore");
812 }
Kenny Root07438c82012-11-02 15:41:02 -0700813
814 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
815 saltSize, 8192, keySize, key);
Kenny Roota91203b2012-02-15 15:00:46 -0800816 }
817
818 static bool isKeyFile(const char* filename) {
819 return ((strcmp(filename, MASTER_KEY_FILE) != 0)
820 && (strcmp(filename, ".") != 0)
821 && (strcmp(filename, "..") != 0));
822 }
Kenny Root70e3a862012-02-15 17:20:23 -0800823
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700824 grant_t* getGrant(const char* filename, uid_t uid) const {
Kenny Root70e3a862012-02-15 17:20:23 -0800825 struct listnode *node;
826 grant_t *grant;
827
828 list_for_each(node, &mGrants) {
829 grant = node_to_item(node, grant_t, plist);
830 if (grant->uid == uid
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700831 && !strcmp(reinterpret_cast<const char*>(grant->filename),
832 filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -0800833 return grant;
834 }
835 }
836
837 return NULL;
838 }
839
Kenny Root822c3a92012-03-23 16:34:39 -0700840 /**
841 * Upgrade code. This will upgrade the key from the current version
842 * to whatever is newest.
843 */
844 void upgrade(const char* filename, Blob* blob, const uint8_t oldVersion, const BlobType type) {
845 bool updated = false;
846 uint8_t version = oldVersion;
847
848 /* From V0 -> V1: All old types were unknown */
849 if (version == 0) {
850 ALOGV("upgrading to version 1 and setting type %d", type);
851
852 blob->setType(type);
853 if (type == TYPE_KEY_PAIR) {
854 importBlobAsKey(blob, filename);
855 }
856 version = 1;
857 updated = true;
858 }
859
860 /*
861 * If we've updated, set the key blob to the right version
862 * and write it.
863 * */
864 if (updated) {
865 ALOGV("updated and writing file %s", filename);
866 blob->setVersion(version);
867 this->put(filename, blob);
868 }
869 }
870
871 /**
872 * Takes a blob that is an PEM-encoded RSA key as a byte array and
873 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
874 * Then it overwrites the original blob with the new blob
875 * format that is returned from the keymaster.
876 */
877 ResponseCode importBlobAsKey(Blob* blob, const char* filename) {
878 // We won't even write to the blob directly with this BIO, so const_cast is okay.
879 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
880 if (b.get() == NULL) {
881 ALOGE("Problem instantiating BIO");
882 return SYSTEM_ERROR;
883 }
884
885 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
886 if (pkey.get() == NULL) {
887 ALOGE("Couldn't read old PEM file");
888 return SYSTEM_ERROR;
889 }
890
891 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
892 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
893 if (len < 0) {
894 ALOGE("Couldn't measure PKCS#8 length");
895 return SYSTEM_ERROR;
896 }
897
Kenny Root70c98892013-02-07 09:10:36 -0800898 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
899 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -0700900 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
901 ALOGE("Couldn't convert to PKCS#8");
902 return SYSTEM_ERROR;
903 }
904
Kenny Root70c98892013-02-07 09:10:36 -0800905 ResponseCode rc = importKey(pkcs8key.get(), len, filename);
Kenny Root822c3a92012-03-23 16:34:39 -0700906 if (rc != NO_ERROR) {
907 return rc;
908 }
909
910 return get(filename, blob, TYPE_KEY_PAIR);
911 }
Kenny Roota91203b2012-02-15 15:00:46 -0800912};
913
914const char* KeyStore::MASTER_KEY_FILE = ".masterkey";
915
Kenny Root07438c82012-11-02 15:41:02 -0700916static ResponseCode get_key_for_name(KeyStore* keyStore, Blob* keyBlob,
917 const android::String8& keyName, const uid_t uid, const BlobType type) {
Kenny Root70e3a862012-02-15 17:20:23 -0800918 char filename[NAME_MAX];
919
920 encode_key_for_uid(filename, uid, keyName);
Kenny Root822c3a92012-03-23 16:34:39 -0700921 ResponseCode responseCode = keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800922 if (responseCode == NO_ERROR) {
923 return responseCode;
924 }
925
Kenny Root49468902013-03-19 13:41:33 -0700926 // If this is one of the legacy UID->UID mappings, use it.
927 uid_t euid = get_keystore_euid(uid);
928 if (euid != uid) {
929 encode_key_for_uid(filename, euid, keyName);
Kenny Root822c3a92012-03-23 16:34:39 -0700930 responseCode = keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800931 if (responseCode == NO_ERROR) {
932 return responseCode;
933 }
934 }
935
936 // They might be using a granted key.
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700937 encode_key(filename, keyName);
938 if (!keyStore->hasGrant(filename, uid)) {
Kenny Root70e3a862012-02-15 17:20:23 -0800939 return responseCode;
940 }
941
942 // It is a granted key. Try to load it.
Kenny Root822c3a92012-03-23 16:34:39 -0700943 return keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800944}
945
Kenny Root07438c82012-11-02 15:41:02 -0700946namespace android {
947class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
948public:
949 KeyStoreProxy(KeyStore* keyStore)
950 : mKeyStore(keyStore)
951 {
Kenny Roota91203b2012-02-15 15:00:46 -0800952 }
Kenny Roota91203b2012-02-15 15:00:46 -0800953
Kenny Root07438c82012-11-02 15:41:02 -0700954 void binderDied(const wp<IBinder>&) {
955 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -0700956 }
Kenny Roota91203b2012-02-15 15:00:46 -0800957
Kenny Root07438c82012-11-02 15:41:02 -0700958 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -0800959 uid_t callingUid = IPCThreadState::self()->getCallingUid();
960 if (!has_permission(callingUid, P_TEST)) {
961 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -0700962 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -0800963 }
Kenny Roota91203b2012-02-15 15:00:46 -0800964
Kenny Root07438c82012-11-02 15:41:02 -0700965 return mKeyStore->getState();
Kenny Root298e7b12012-03-26 13:54:44 -0700966 }
967
Kenny Root07438c82012-11-02 15:41:02 -0700968 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -0800969 uid_t callingUid = IPCThreadState::self()->getCallingUid();
970 if (!has_permission(callingUid, P_GET)) {
971 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -0700972 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -0800973 }
Kenny Root07438c82012-11-02 15:41:02 -0700974
Kenny Root9d45d1c2013-02-14 10:32:30 -0800975 State state = mKeyStore->getState();
976 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -0700977 ALOGD("calling get in state: %d", state);
978 return state;
Kenny Roota91203b2012-02-15 15:00:46 -0800979 }
Kenny Root07438c82012-11-02 15:41:02 -0700980
981 String8 name8(name);
982 char filename[NAME_MAX];
Kenny Root07438c82012-11-02 15:41:02 -0700983 Blob keyBlob;
Kenny Root49468902013-03-19 13:41:33 -0700984
985 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
986 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -0700987 if (responseCode != ::NO_ERROR) {
Kenny Root150ca932012-11-14 14:29:02 -0800988 ALOGW("Could not read %s", filename);
Kenny Root07438c82012-11-02 15:41:02 -0700989 *item = NULL;
990 *itemLength = 0;
991 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -0800992 }
Kenny Roota91203b2012-02-15 15:00:46 -0800993
Kenny Root07438c82012-11-02 15:41:02 -0700994 *item = (uint8_t*) malloc(keyBlob.getLength());
995 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
996 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -0800997
Kenny Root07438c82012-11-02 15:41:02 -0700998 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -0800999 }
1000
Kenny Root49468902013-03-19 13:41:33 -07001001 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001002 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1003 if (!has_permission(callingUid, P_INSERT)) {
1004 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001005 return ::PERMISSION_DENIED;
1006 }
Kenny Root07438c82012-11-02 15:41:02 -07001007
Kenny Root49468902013-03-19 13:41:33 -07001008 if (targetUid == -1) {
1009 targetUid = callingUid;
1010 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001011 return ::PERMISSION_DENIED;
1012 }
1013
Kenny Root9d45d1c2013-02-14 10:32:30 -08001014 State state = mKeyStore->getState();
1015 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001016 ALOGD("calling insert in state: %d", state);
1017 return state;
1018 }
1019
1020 String8 name8(name);
1021 char filename[NAME_MAX];
1022
Kenny Root49468902013-03-19 13:41:33 -07001023 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001024
1025 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
1026 return mKeyStore->put(filename, &keyBlob);
Kenny Root70e3a862012-02-15 17:20:23 -08001027 }
1028
Kenny Root49468902013-03-19 13:41:33 -07001029 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001030 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1031 if (!has_permission(callingUid, P_DELETE)) {
1032 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001033 return ::PERMISSION_DENIED;
1034 }
Kenny Root70e3a862012-02-15 17:20:23 -08001035
Kenny Root49468902013-03-19 13:41:33 -07001036 if (targetUid == -1) {
1037 targetUid = callingUid;
1038 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001039 return ::PERMISSION_DENIED;
1040 }
1041
Kenny Root07438c82012-11-02 15:41:02 -07001042 String8 name8(name);
1043 char filename[NAME_MAX];
1044
Kenny Root49468902013-03-19 13:41:33 -07001045 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001046
1047 Blob keyBlob;
1048 ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, TYPE_GENERIC);
1049 if (responseCode != ::NO_ERROR) {
1050 return responseCode;
1051 }
1052 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001053 }
1054
Kenny Root49468902013-03-19 13:41:33 -07001055 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001056 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1057 if (!has_permission(callingUid, P_EXIST)) {
1058 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001059 return ::PERMISSION_DENIED;
1060 }
Kenny Root70e3a862012-02-15 17:20:23 -08001061
Kenny Root49468902013-03-19 13:41:33 -07001062 if (targetUid == -1) {
1063 targetUid = callingUid;
1064 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001065 return ::PERMISSION_DENIED;
1066 }
1067
Kenny Root07438c82012-11-02 15:41:02 -07001068 String8 name8(name);
1069 char filename[NAME_MAX];
Kenny Root70e3a862012-02-15 17:20:23 -08001070
Kenny Root49468902013-03-19 13:41:33 -07001071 encode_key_for_uid(filename, targetUid, name8);
Kenny Root70e3a862012-02-15 17:20:23 -08001072
Kenny Root07438c82012-11-02 15:41:02 -07001073 if (access(filename, R_OK) == -1) {
1074 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1075 }
1076 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001077 }
1078
Kenny Root49468902013-03-19 13:41:33 -07001079 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001080 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1081 if (!has_permission(callingUid, P_SAW)) {
1082 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001083 return ::PERMISSION_DENIED;
1084 }
Kenny Root70e3a862012-02-15 17:20:23 -08001085
Kenny Root49468902013-03-19 13:41:33 -07001086 if (targetUid == -1) {
1087 targetUid = callingUid;
1088 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001089 return ::PERMISSION_DENIED;
1090 }
1091
Kenny Root07438c82012-11-02 15:41:02 -07001092 DIR* dir = opendir(".");
1093 if (!dir) {
1094 return ::SYSTEM_ERROR;
1095 }
Kenny Root70e3a862012-02-15 17:20:23 -08001096
Kenny Root07438c82012-11-02 15:41:02 -07001097 const String8 prefix8(prefix);
1098 char filename[NAME_MAX];
Kenny Root70e3a862012-02-15 17:20:23 -08001099
Kenny Root49468902013-03-19 13:41:33 -07001100 int n = encode_key_for_uid(filename, targetUid, prefix8);
Kenny Root70e3a862012-02-15 17:20:23 -08001101
Kenny Root07438c82012-11-02 15:41:02 -07001102 struct dirent* file;
1103 while ((file = readdir(dir)) != NULL) {
1104 if (!strncmp(filename, file->d_name, n)) {
1105 const char* p = &file->d_name[n];
1106 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001107
Kenny Root07438c82012-11-02 15:41:02 -07001108 size_t extra = decode_key_length(p, plen);
1109 char *match = (char*) malloc(extra + 1);
1110 if (match != NULL) {
1111 decode_key(match, p, plen);
1112 matches->push(String16(match, extra));
1113 free(match);
1114 } else {
1115 ALOGW("could not allocate match of size %zd", extra);
1116 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001117 }
1118 }
Kenny Root07438c82012-11-02 15:41:02 -07001119 closedir(dir);
1120
1121 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001122 }
1123
Kenny Root07438c82012-11-02 15:41:02 -07001124 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001125 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1126 if (!has_permission(callingUid, P_RESET)) {
1127 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001128 return ::PERMISSION_DENIED;
1129 }
1130
1131 ResponseCode rc = mKeyStore->reset() ? ::NO_ERROR : ::SYSTEM_ERROR;
1132
1133 const keymaster_device_t* device = mKeyStore->getDevice();
1134 if (device == NULL) {
1135 ALOGE("No keymaster device!");
1136 return ::SYSTEM_ERROR;
1137 }
1138
1139 if (device->delete_all == NULL) {
1140 ALOGV("keymaster device doesn't implement delete_all");
1141 return rc;
1142 }
1143
1144 if (device->delete_all(device)) {
1145 ALOGE("Problem calling keymaster's delete_all");
1146 return ::SYSTEM_ERROR;
1147 }
1148
Kenny Root9a53d3e2012-08-14 10:47:54 -07001149 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001150 }
1151
Kenny Root07438c82012-11-02 15:41:02 -07001152 /*
1153 * Here is the history. To improve the security, the parameters to generate the
1154 * master key has been changed. To make a seamless transition, we update the
1155 * file using the same password when the user unlock it for the first time. If
1156 * any thing goes wrong during the transition, the new file will not overwrite
1157 * the old one. This avoids permanent damages of the existing data.
1158 */
1159 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001160 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1161 if (!has_permission(callingUid, P_PASSWORD)) {
1162 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001163 return ::PERMISSION_DENIED;
1164 }
Kenny Root70e3a862012-02-15 17:20:23 -08001165
Kenny Root07438c82012-11-02 15:41:02 -07001166 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001167
Kenny Root07438c82012-11-02 15:41:02 -07001168 switch (mKeyStore->getState()) {
1169 case ::STATE_UNINITIALIZED: {
1170 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
1171 return mKeyStore->initialize(password8);
1172 }
1173 case ::STATE_NO_ERROR: {
1174 // rewrite master key with new password.
1175 return mKeyStore->writeMasterKey(password8);
1176 }
1177 case ::STATE_LOCKED: {
1178 // read master key, decrypt with password, initialize mMasterKey*.
1179 return mKeyStore->readMasterKey(password8);
1180 }
1181 }
1182 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001183 }
1184
Kenny Root07438c82012-11-02 15:41:02 -07001185 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001186 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1187 if (!has_permission(callingUid, P_LOCK)) {
1188 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001189 return ::PERMISSION_DENIED;
1190 }
Kenny Root70e3a862012-02-15 17:20:23 -08001191
Kenny Root9d45d1c2013-02-14 10:32:30 -08001192 State state = mKeyStore->getState();
1193 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001194 ALOGD("calling lock in state: %d", state);
1195 return state;
1196 }
1197
1198 mKeyStore->lock();
1199 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001200 }
1201
Kenny Root07438c82012-11-02 15:41:02 -07001202 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001203 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1204 if (!has_permission(callingUid, P_UNLOCK)) {
1205 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001206 return ::PERMISSION_DENIED;
1207 }
1208
Kenny Root9d45d1c2013-02-14 10:32:30 -08001209 State state = mKeyStore->getState();
1210 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001211 ALOGD("calling unlock when not locked");
1212 return state;
1213 }
1214
1215 const String8 password8(pw);
1216 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001217 }
1218
Kenny Root07438c82012-11-02 15:41:02 -07001219 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001220 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1221 if (!has_permission(callingUid, P_ZERO)) {
1222 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001223 return -1;
1224 }
Kenny Root70e3a862012-02-15 17:20:23 -08001225
Kenny Root07438c82012-11-02 15:41:02 -07001226 return mKeyStore->isEmpty() ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001227 }
1228
Kenny Root49468902013-03-19 13:41:33 -07001229 int32_t generate(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001230 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1231 if (!has_permission(callingUid, P_INSERT)) {
1232 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001233 return ::PERMISSION_DENIED;
1234 }
Kenny Root70e3a862012-02-15 17:20:23 -08001235
Kenny Root49468902013-03-19 13:41:33 -07001236 if (targetUid == -1) {
1237 targetUid = callingUid;
1238 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001239 return ::PERMISSION_DENIED;
1240 }
1241
Kenny Root9d45d1c2013-02-14 10:32:30 -08001242 State state = mKeyStore->getState();
1243 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001244 ALOGD("calling generate in state: %d", state);
1245 return state;
1246 }
Kenny Root70e3a862012-02-15 17:20:23 -08001247
Kenny Root07438c82012-11-02 15:41:02 -07001248 String8 name8(name);
1249 char filename[NAME_MAX];
1250
1251 uint8_t* data;
1252 size_t dataLength;
1253 int rc;
1254
1255 const keymaster_device_t* device = mKeyStore->getDevice();
1256 if (device == NULL) {
1257 return ::SYSTEM_ERROR;
1258 }
1259
1260 if (device->generate_keypair == NULL) {
1261 return ::SYSTEM_ERROR;
1262 }
1263
1264 keymaster_rsa_keygen_params_t rsa_params;
1265 rsa_params.modulus_size = 2048;
1266 rsa_params.public_exponent = 0x10001;
1267
1268 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1269 if (rc) {
1270 return ::SYSTEM_ERROR;
1271 }
1272
Kenny Root49468902013-03-19 13:41:33 -07001273 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001274
1275 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1276 free(data);
1277
1278 return mKeyStore->put(filename, &keyBlob);
Kenny Root70e3a862012-02-15 17:20:23 -08001279 }
1280
Kenny Root49468902013-03-19 13:41:33 -07001281 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001282 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1283 if (!has_permission(callingUid, P_INSERT)) {
1284 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001285 return ::PERMISSION_DENIED;
1286 }
Kenny Root07438c82012-11-02 15:41:02 -07001287
Kenny Root49468902013-03-19 13:41:33 -07001288 if (targetUid == -1) {
1289 targetUid = callingUid;
1290 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001291 return ::PERMISSION_DENIED;
1292 }
1293
Kenny Root9d45d1c2013-02-14 10:32:30 -08001294 State state = mKeyStore->getState();
1295 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001296 ALOGD("calling import in state: %d", state);
1297 return state;
1298 }
1299
1300 String8 name8(name);
1301 char filename[NAME_MAX];
1302
Kenny Root49468902013-03-19 13:41:33 -07001303 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001304
1305 return mKeyStore->importKey(data, length, filename);
Kenny Root70e3a862012-02-15 17:20:23 -08001306 }
1307
Kenny Root07438c82012-11-02 15:41:02 -07001308 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1309 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001310 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1311 if (!has_permission(callingUid, P_SIGN)) {
1312 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001313 return ::PERMISSION_DENIED;
1314 }
Kenny Root07438c82012-11-02 15:41:02 -07001315
Kenny Root9d45d1c2013-02-14 10:32:30 -08001316 State state = mKeyStore->getState();
1317 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001318 ALOGD("calling sign in state: %d", state);
1319 return state;
1320 }
1321
1322 Blob keyBlob;
1323 String8 name8(name);
1324
Kenny Rootd38a0b02013-02-13 12:59:14 -08001325 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001326 int rc;
1327
Kenny Rootd38a0b02013-02-13 12:59:14 -08001328 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1329 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001330 if (responseCode != ::NO_ERROR) {
1331 return responseCode;
1332 }
1333
1334 const keymaster_device_t* device = mKeyStore->getDevice();
1335 if (device == NULL) {
1336 ALOGE("no keymaster device; cannot sign");
1337 return ::SYSTEM_ERROR;
1338 }
1339
1340 if (device->sign_data == NULL) {
1341 ALOGE("device doesn't implement signing");
1342 return ::SYSTEM_ERROR;
1343 }
1344
1345 keymaster_rsa_sign_params_t params;
1346 params.digest_type = DIGEST_NONE;
1347 params.padding_type = PADDING_NONE;
1348
1349 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1350 data, length, out, outLength);
1351 if (rc) {
1352 ALOGW("device couldn't sign data");
1353 return ::SYSTEM_ERROR;
1354 }
1355
1356 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001357 }
1358
Kenny Root07438c82012-11-02 15:41:02 -07001359 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1360 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001361 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1362 if (!has_permission(callingUid, P_VERIFY)) {
1363 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001364 return ::PERMISSION_DENIED;
1365 }
Kenny Root70e3a862012-02-15 17:20:23 -08001366
Kenny Root9d45d1c2013-02-14 10:32:30 -08001367 State state = mKeyStore->getState();
1368 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001369 ALOGD("calling verify in state: %d", state);
1370 return state;
1371 }
Kenny Root70e3a862012-02-15 17:20:23 -08001372
Kenny Root07438c82012-11-02 15:41:02 -07001373 Blob keyBlob;
1374 String8 name8(name);
1375 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001376
Kenny Root49468902013-03-19 13:41:33 -07001377 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1378 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001379 if (responseCode != ::NO_ERROR) {
1380 return responseCode;
1381 }
Kenny Root70e3a862012-02-15 17:20:23 -08001382
Kenny Root07438c82012-11-02 15:41:02 -07001383 const keymaster_device_t* device = mKeyStore->getDevice();
1384 if (device == NULL) {
1385 return ::SYSTEM_ERROR;
1386 }
Kenny Root70e3a862012-02-15 17:20:23 -08001387
Kenny Root07438c82012-11-02 15:41:02 -07001388 if (device->verify_data == NULL) {
1389 return ::SYSTEM_ERROR;
1390 }
Kenny Root70e3a862012-02-15 17:20:23 -08001391
Kenny Root07438c82012-11-02 15:41:02 -07001392 keymaster_rsa_sign_params_t params;
1393 params.digest_type = DIGEST_NONE;
1394 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001395
Kenny Root07438c82012-11-02 15:41:02 -07001396 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1397 data, dataLength, signature, signatureLength);
1398 if (rc) {
1399 return ::SYSTEM_ERROR;
1400 } else {
1401 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001402 }
1403 }
Kenny Root07438c82012-11-02 15:41:02 -07001404
1405 /*
1406 * TODO: The abstraction between things stored in hardware and regular blobs
1407 * of data stored on the filesystem should be moved down to keystore itself.
1408 * Unfortunately the Java code that calls this has naming conventions that it
1409 * knows about. Ideally keystore shouldn't be used to store random blobs of
1410 * data.
1411 *
1412 * Until that happens, it's necessary to have a separate "get_pubkey" and
1413 * "del_key" since the Java code doesn't really communicate what it's
1414 * intentions are.
1415 */
1416 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001417 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1418 if (!has_permission(callingUid, P_GET)) {
1419 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001420 return ::PERMISSION_DENIED;
1421 }
Kenny Root07438c82012-11-02 15:41:02 -07001422
Kenny Root9d45d1c2013-02-14 10:32:30 -08001423 State state = mKeyStore->getState();
1424 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001425 ALOGD("calling get_pubkey in state: %d", state);
1426 return state;
1427 }
1428
1429 Blob keyBlob;
1430 String8 name8(name);
1431
Kenny Rootd38a0b02013-02-13 12:59:14 -08001432 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001433
Kenny Rootd38a0b02013-02-13 12:59:14 -08001434 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07001435 TYPE_KEY_PAIR);
1436 if (responseCode != ::NO_ERROR) {
1437 return responseCode;
1438 }
1439
1440 const keymaster_device_t* device = mKeyStore->getDevice();
1441 if (device == NULL) {
1442 return ::SYSTEM_ERROR;
1443 }
1444
1445 if (device->get_keypair_public == NULL) {
1446 ALOGE("device has no get_keypair_public implementation!");
1447 return ::SYSTEM_ERROR;
1448 }
1449
1450 int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
1451 pubkeyLength);
1452 if (rc) {
1453 return ::SYSTEM_ERROR;
1454 }
1455
1456 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001457 }
Kenny Root07438c82012-11-02 15:41:02 -07001458
Kenny Root49468902013-03-19 13:41:33 -07001459 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001460 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1461 if (!has_permission(callingUid, P_DELETE)) {
1462 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001463 return ::PERMISSION_DENIED;
1464 }
Kenny Root07438c82012-11-02 15:41:02 -07001465
Kenny Root49468902013-03-19 13:41:33 -07001466 if (targetUid == -1) {
1467 targetUid = callingUid;
1468 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001469 return ::PERMISSION_DENIED;
1470 }
1471
Kenny Root07438c82012-11-02 15:41:02 -07001472 String8 name8(name);
1473 char filename[NAME_MAX];
1474
Kenny Root49468902013-03-19 13:41:33 -07001475 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001476
1477 Blob keyBlob;
1478 ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, ::TYPE_KEY_PAIR);
1479 if (responseCode != ::NO_ERROR) {
1480 return responseCode;
1481 }
1482
1483 ResponseCode rc = ::NO_ERROR;
1484
1485 const keymaster_device_t* device = mKeyStore->getDevice();
1486 if (device == NULL) {
1487 rc = ::SYSTEM_ERROR;
1488 } else {
1489 // A device doesn't have to implement delete_keypair.
1490 if (device->delete_keypair != NULL) {
1491 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1492 rc = ::SYSTEM_ERROR;
1493 }
1494 }
1495 }
1496
1497 if (rc != ::NO_ERROR) {
1498 return rc;
1499 }
1500
1501 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1502 }
1503
1504 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001505 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1506 if (!has_permission(callingUid, P_GRANT)) {
1507 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001508 return ::PERMISSION_DENIED;
1509 }
Kenny Root07438c82012-11-02 15:41:02 -07001510
Kenny Root9d45d1c2013-02-14 10:32:30 -08001511 State state = mKeyStore->getState();
1512 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001513 ALOGD("calling grant in state: %d", state);
1514 return state;
1515 }
1516
1517 String8 name8(name);
1518 char filename[NAME_MAX];
1519
Kenny Rootd38a0b02013-02-13 12:59:14 -08001520 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001521
1522 if (access(filename, R_OK) == -1) {
1523 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1524 }
1525
1526 mKeyStore->addGrant(filename, granteeUid);
1527 return ::NO_ERROR;
1528 }
1529
1530 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001531 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1532 if (!has_permission(callingUid, P_GRANT)) {
1533 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001534 return ::PERMISSION_DENIED;
1535 }
Kenny Root07438c82012-11-02 15:41:02 -07001536
Kenny Root9d45d1c2013-02-14 10:32:30 -08001537 State state = mKeyStore->getState();
1538 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001539 ALOGD("calling ungrant in state: %d", state);
1540 return state;
1541 }
1542
1543 String8 name8(name);
1544 char filename[NAME_MAX];
1545
Kenny Rootd38a0b02013-02-13 12:59:14 -08001546 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001547
1548 if (access(filename, R_OK) == -1) {
1549 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1550 }
1551
1552 return mKeyStore->removeGrant(filename, granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
1553 }
1554
1555 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001556 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1557 if (!has_permission(callingUid, P_GET)) {
1558 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08001559 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001560 }
Kenny Root07438c82012-11-02 15:41:02 -07001561
1562 String8 name8(name);
1563 char filename[NAME_MAX];
1564
Kenny Rootd38a0b02013-02-13 12:59:14 -08001565 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001566
1567 if (access(filename, R_OK) == -1) {
Kenny Root36a9e232013-02-04 14:24:15 -08001568 ALOGW("could not access %s for getmtime", filename);
1569 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001570 }
1571
Kenny Root150ca932012-11-14 14:29:02 -08001572 int fd = TEMP_FAILURE_RETRY(open(filename, O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07001573 if (fd < 0) {
Kenny Root36a9e232013-02-04 14:24:15 -08001574 ALOGW("could not open %s for getmtime", filename);
1575 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001576 }
1577
1578 struct stat s;
1579 int ret = fstat(fd, &s);
1580 close(fd);
1581 if (ret == -1) {
Kenny Root36a9e232013-02-04 14:24:15 -08001582 ALOGW("could not stat %s for getmtime", filename);
1583 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001584 }
1585
Kenny Root36a9e232013-02-04 14:24:15 -08001586 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07001587 }
1588
Kenny Rootd53bc922013-03-21 14:10:15 -07001589 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
1590 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07001591 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Rootd53bc922013-03-21 14:10:15 -07001592 if (!has_permission(callingUid, P_DUPLICATE)) {
1593 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07001594 return -1L;
1595 }
1596
1597 State state = mKeyStore->getState();
1598 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07001599 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07001600 return state;
1601 }
1602
Kenny Rootd53bc922013-03-21 14:10:15 -07001603 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
1604 srcUid = callingUid;
1605 } else if (!is_granted_to(callingUid, srcUid)) {
1606 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07001607 return ::PERMISSION_DENIED;
1608 }
1609
Kenny Rootd53bc922013-03-21 14:10:15 -07001610 if (destUid == -1) {
1611 destUid = callingUid;
1612 }
1613
1614 if (srcUid != destUid) {
1615 if (static_cast<uid_t>(srcUid) != callingUid) {
1616 ALOGD("can only duplicate from caller to other or to same uid: "
1617 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
1618 return ::PERMISSION_DENIED;
1619 }
1620
1621 if (!is_granted_to(callingUid, destUid)) {
1622 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
1623 return ::PERMISSION_DENIED;
1624 }
1625 }
1626
1627 String8 source8(srcKey);
Kenny Root02254072013-03-20 11:48:19 -07001628 char source[NAME_MAX];
1629
Kenny Rootd53bc922013-03-21 14:10:15 -07001630 encode_key_for_uid(source, srcUid, source8);
Kenny Root02254072013-03-20 11:48:19 -07001631
Kenny Rootd53bc922013-03-21 14:10:15 -07001632 String8 target8(destKey);
Kenny Root02254072013-03-20 11:48:19 -07001633 char target[NAME_MAX];
1634
Kenny Rootd53bc922013-03-21 14:10:15 -07001635 encode_key_for_uid(target, destUid, target8);
Kenny Root02254072013-03-20 11:48:19 -07001636
Kenny Rootd53bc922013-03-21 14:10:15 -07001637 if (access(target, W_OK) != -1 || errno != ENOENT) {
1638 ALOGD("destination already exists: %s", target);
Kenny Root02254072013-03-20 11:48:19 -07001639 return ::SYSTEM_ERROR;
1640 }
1641
Kenny Rootd53bc922013-03-21 14:10:15 -07001642 Blob keyBlob;
1643 ResponseCode responseCode = mKeyStore->get(source, &keyBlob, TYPE_ANY);
1644 if (responseCode != ::NO_ERROR) {
1645 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07001646 }
Kenny Rootd53bc922013-03-21 14:10:15 -07001647
1648 return mKeyStore->put(target, &keyBlob);
Kenny Root02254072013-03-20 11:48:19 -07001649 }
1650
Kenny Root07438c82012-11-02 15:41:02 -07001651private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08001652 inline bool isKeystoreUnlocked(State state) {
1653 switch (state) {
1654 case ::STATE_NO_ERROR:
1655 return true;
1656 case ::STATE_UNINITIALIZED:
1657 case ::STATE_LOCKED:
1658 return false;
1659 }
1660 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001661 }
1662
1663 ::KeyStore* mKeyStore;
1664};
1665
1666}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08001667
1668int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08001669 if (argc < 2) {
1670 ALOGE("A directory must be specified!");
1671 return 1;
1672 }
1673 if (chdir(argv[1]) == -1) {
1674 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
1675 return 1;
1676 }
1677
1678 Entropy entropy;
1679 if (!entropy.open()) {
1680 return 1;
1681 }
Kenny Root70e3a862012-02-15 17:20:23 -08001682
1683 keymaster_device_t* dev;
1684 if (keymaster_device_initialize(&dev)) {
1685 ALOGE("keystore keymaster could not be initialized; exiting");
1686 return 1;
1687 }
1688
Kenny Root70e3a862012-02-15 17:20:23 -08001689 KeyStore keyStore(&entropy, dev);
Kenny Root07438c82012-11-02 15:41:02 -07001690 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
1691 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
1692 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
1693 if (ret != android::OK) {
1694 ALOGE("Couldn't register binder service!");
1695 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08001696 }
Kenny Root07438c82012-11-02 15:41:02 -07001697
1698 /*
1699 * We're the only thread in existence, so we're just going to process
1700 * Binder transaction as a single-threaded program.
1701 */
1702 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08001703
1704 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08001705 return 1;
1706}