blob: 760ec4d2e34a00bc18db1ed38f8b2cbeaacb2b14 [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 Roota9bb5492013-04-01 16:29:11 -0700140 P_CLEAR_UID = 1 << 15,
Kenny Root07438c82012-11-02 15:41:02 -0700141} perm_t;
142
143static struct user_euid {
144 uid_t uid;
145 uid_t euid;
146} user_euids[] = {
147 {AID_VPN, AID_SYSTEM},
148 {AID_WIFI, AID_SYSTEM},
149 {AID_ROOT, AID_SYSTEM},
150};
151
152static struct user_perm {
153 uid_t uid;
154 perm_t perms;
155} user_perms[] = {
156 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
157 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
158 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
159 {AID_ROOT, static_cast<perm_t>(P_GET) },
160};
161
162static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
163 | P_VERIFY);
164
165static bool has_permission(uid_t uid, perm_t perm) {
166 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
167 struct user_perm user = user_perms[i];
168 if (user.uid == uid) {
169 return user.perms & perm;
170 }
171 }
172
173 return DEFAULT_PERMS & perm;
174}
175
Kenny Root49468902013-03-19 13:41:33 -0700176/**
177 * Returns the UID that the callingUid should act as. This is here for
178 * legacy support of the WiFi and VPN systems and should be removed
179 * when WiFi can operate in its own namespace.
180 */
Kenny Root07438c82012-11-02 15:41:02 -0700181static uid_t get_keystore_euid(uid_t uid) {
182 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
183 struct user_euid user = user_euids[i];
184 if (user.uid == uid) {
185 return user.euid;
186 }
187 }
188
189 return uid;
190}
191
Kenny Root49468902013-03-19 13:41:33 -0700192/**
193 * Returns true if the callingUid is allowed to interact in the targetUid's
194 * namespace.
195 */
196static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
197 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
198 struct user_euid user = user_euids[i];
199 if (user.euid == callingUid && user.uid == targetUid) {
200 return true;
201 }
202 }
203
204 return false;
205}
206
Kenny Roota91203b2012-02-15 15:00:46 -0800207/* Here is the encoding of keys. This is necessary in order to allow arbitrary
208 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
209 * into two bytes. The first byte is one of [+-.] which represents the first
210 * two bits of the character. The second byte encodes the rest of the bits into
211 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
212 * that Base64 cannot be used here due to the need of prefix match on keys. */
213
Kenny Root07438c82012-11-02 15:41:02 -0700214static int encode_key(char* out, const android::String8& keyName) {
215 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
216 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800217 for (int i = length; i > 0; --i, ++in, ++out) {
218 if (*in >= '0' && *in <= '~') {
219 *out = *in;
220 } else {
221 *out = '+' + (*in >> 6);
222 *++out = '0' + (*in & 0x3F);
223 ++length;
224 }
225 }
226 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800227 return length;
228}
229
Kenny Root07438c82012-11-02 15:41:02 -0700230static int encode_key_for_uid(char* out, uid_t uid, const android::String8& keyName) {
Kenny Root70e3a862012-02-15 17:20:23 -0800231 int n = snprintf(out, NAME_MAX, "%u_", uid);
232 out += n;
233
Kenny Root07438c82012-11-02 15:41:02 -0700234 return n + encode_key(out, keyName);
Kenny Roota91203b2012-02-15 15:00:46 -0800235}
236
Kenny Root07438c82012-11-02 15:41:02 -0700237/*
238 * Converts from the "escaped" format on disk to actual name.
239 * This will be smaller than the input string.
240 *
241 * Characters that should combine with the next at the end will be truncated.
242 */
243static size_t decode_key_length(const char* in, size_t length) {
244 size_t outLength = 0;
245
246 for (const char* end = in + length; in < end; in++) {
247 /* This combines with the next character. */
248 if (*in < '0' || *in > '~') {
249 continue;
250 }
251
252 outLength++;
253 }
254 return outLength;
255}
256
257static void decode_key(char* out, const char* in, size_t length) {
258 for (const char* end = in + length; in < end; in++) {
259 if (*in < '0' || *in > '~') {
260 /* Truncate combining characters at the end. */
261 if (in + 1 >= end) {
262 break;
263 }
264
265 *out = (*in++ - '+') << 6;
266 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800267 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700268 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800269 }
270 }
271 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800272}
273
274static size_t readFully(int fd, uint8_t* data, size_t size) {
275 size_t remaining = size;
276 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800277 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800278 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800279 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800280 }
281 data += n;
282 remaining -= n;
283 }
284 return size;
285}
286
287static size_t writeFully(int fd, uint8_t* data, size_t size) {
288 size_t remaining = size;
289 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800290 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
291 if (n < 0) {
292 ALOGW("write failed: %s", strerror(errno));
293 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800294 }
295 data += n;
296 remaining -= n;
297 }
298 return size;
299}
300
301class Entropy {
302public:
303 Entropy() : mRandom(-1) {}
304 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800305 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800306 close(mRandom);
307 }
308 }
309
310 bool open() {
311 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800312 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
313 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800314 ALOGE("open: %s: %s", randomDevice, strerror(errno));
315 return false;
316 }
317 return true;
318 }
319
Kenny Root51878182012-03-13 12:53:19 -0700320 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800321 return (readFully(mRandom, data, size) == size);
322 }
323
324private:
325 int mRandom;
326};
327
328/* Here is the file format. There are two parts in blob.value, the secret and
329 * the description. The secret is stored in ciphertext, and its original size
330 * can be found in blob.length. The description is stored after the secret in
331 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700332 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
333 * the second is the blob's type, and the third byte is reserved. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800334 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
335 * and decryptBlob(). Thus they should not be accessed from outside. */
336
Kenny Root822c3a92012-03-23 16:34:39 -0700337/* ** Note to future implementors of encryption: **
338 * Currently this is the construction:
339 * metadata || Enc(MD5(data) || data)
340 *
341 * This should be the construction used for encrypting if re-implementing:
342 *
343 * Derive independent keys for encryption and MAC:
344 * Kenc = AES_encrypt(masterKey, "Encrypt")
345 * Kmac = AES_encrypt(masterKey, "MAC")
346 *
347 * Store this:
348 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
349 * HMAC(Kmac, metadata || Enc(data))
350 */
Kenny Roota91203b2012-02-15 15:00:46 -0800351struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700352 uint8_t version;
353 uint8_t type;
354 uint8_t reserved;
Kenny Roota91203b2012-02-15 15:00:46 -0800355 uint8_t info;
356 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700357 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800358 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700359 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800360 int32_t length; // in network byte order when encrypted
361 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
362};
363
Kenny Root822c3a92012-03-23 16:34:39 -0700364typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700365 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700366 TYPE_GENERIC = 1,
367 TYPE_MASTER_KEY = 2,
368 TYPE_KEY_PAIR = 3,
369} BlobType;
370
Kenny Root07438c82012-11-02 15:41:02 -0700371static const uint8_t CURRENT_BLOB_VERSION = 1;
Kenny Root822c3a92012-03-23 16:34:39 -0700372
Kenny Roota91203b2012-02-15 15:00:46 -0800373class Blob {
374public:
Kenny Root07438c82012-11-02 15:41:02 -0700375 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
376 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800377 mBlob.length = valueLength;
378 memcpy(mBlob.value, value, valueLength);
379
380 mBlob.info = infoLength;
381 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700382
Kenny Root07438c82012-11-02 15:41:02 -0700383 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700384 mBlob.type = uint8_t(type);
Kenny Roota91203b2012-02-15 15:00:46 -0800385 }
386
387 Blob(blob b) {
388 mBlob = b;
389 }
390
391 Blob() {}
392
Kenny Root51878182012-03-13 12:53:19 -0700393 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800394 return mBlob.value;
395 }
396
Kenny Root51878182012-03-13 12:53:19 -0700397 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800398 return mBlob.length;
399 }
400
Kenny Root51878182012-03-13 12:53:19 -0700401 const uint8_t* getInfo() const {
402 return mBlob.value + mBlob.length;
403 }
404
405 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800406 return mBlob.info;
407 }
408
Kenny Root822c3a92012-03-23 16:34:39 -0700409 uint8_t getVersion() const {
410 return mBlob.version;
411 }
412
413 void setVersion(uint8_t version) {
414 mBlob.version = version;
415 }
416
417 BlobType getType() const {
418 return BlobType(mBlob.type);
419 }
420
421 void setType(BlobType type) {
422 mBlob.type = uint8_t(type);
423 }
424
Kenny Roota91203b2012-02-15 15:00:46 -0800425 ResponseCode encryptBlob(const char* filename, AES_KEY *aes_key, Entropy* entropy) {
426 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
Kenny Root150ca932012-11-14 14:29:02 -0800427 ALOGW("Could not read random data for: %s", filename);
Kenny Roota91203b2012-02-15 15:00:46 -0800428 return SYSTEM_ERROR;
429 }
430
431 // data includes the value and the value's length
432 size_t dataLength = mBlob.length + sizeof(mBlob.length);
433 // pad data to the AES_BLOCK_SIZE
434 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
435 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
436 // encrypted data includes the digest value
437 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
438 // move info after space for padding
439 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
440 // zero padding area
441 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
442
443 mBlob.length = htonl(mBlob.length);
444 MD5(mBlob.digested, digestedLength, mBlob.digest);
445
446 uint8_t vector[AES_BLOCK_SIZE];
447 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
448 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
449 aes_key, vector, AES_ENCRYPT);
450
Kenny Root822c3a92012-03-23 16:34:39 -0700451 mBlob.reserved = 0;
Kenny Roota91203b2012-02-15 15:00:46 -0800452 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
453 size_t fileLength = encryptedLength + headerLength + mBlob.info;
454
455 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800456 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
457 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
458 if (out < 0) {
459 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800460 return SYSTEM_ERROR;
461 }
462 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
463 if (close(out) != 0) {
464 return SYSTEM_ERROR;
465 }
466 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800467 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800468 unlink(tmpFileName);
469 return SYSTEM_ERROR;
470 }
Kenny Root150ca932012-11-14 14:29:02 -0800471 if (rename(tmpFileName, filename) == -1) {
472 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
473 return SYSTEM_ERROR;
474 }
475 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800476 }
477
478 ResponseCode decryptBlob(const char* filename, AES_KEY *aes_key) {
Kenny Root150ca932012-11-14 14:29:02 -0800479 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
480 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800481 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
482 }
483 // fileLength may be less than sizeof(mBlob) since the in
484 // memory version has extra padding to tolerate rounding up to
485 // the AES_BLOCK_SIZE
486 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
487 if (close(in) != 0) {
488 return SYSTEM_ERROR;
489 }
490 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
491 if (fileLength < headerLength) {
492 return VALUE_CORRUPTED;
493 }
494
495 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
496 if (encryptedLength < 0 || encryptedLength % AES_BLOCK_SIZE != 0) {
497 return VALUE_CORRUPTED;
498 }
499 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
500 mBlob.vector, AES_DECRYPT);
501 size_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
502 uint8_t computedDigest[MD5_DIGEST_LENGTH];
503 MD5(mBlob.digested, digestedLength, computedDigest);
504 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
505 return VALUE_CORRUPTED;
506 }
507
508 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
509 mBlob.length = ntohl(mBlob.length);
510 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
511 return VALUE_CORRUPTED;
512 }
513 if (mBlob.info != 0) {
514 // move info from after padding to after data
515 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
516 }
Kenny Root07438c82012-11-02 15:41:02 -0700517 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800518 }
519
520private:
521 struct blob mBlob;
522};
523
Kenny Root70e3a862012-02-15 17:20:23 -0800524typedef struct {
525 uint32_t uid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700526 const uint8_t* filename;
Kenny Root70e3a862012-02-15 17:20:23 -0800527
528 struct listnode plist;
529} grant_t;
530
Kenny Roota91203b2012-02-15 15:00:46 -0800531class KeyStore {
532public:
Kenny Root70e3a862012-02-15 17:20:23 -0800533 KeyStore(Entropy* entropy, keymaster_device_t* device)
Kenny Root51878182012-03-13 12:53:19 -0700534 : mEntropy(entropy)
Kenny Root70e3a862012-02-15 17:20:23 -0800535 , mDevice(device)
Kenny Root51878182012-03-13 12:53:19 -0700536 , mRetry(MAX_RETRY)
537 {
Kenny Roota91203b2012-02-15 15:00:46 -0800538 if (access(MASTER_KEY_FILE, R_OK) == 0) {
539 setState(STATE_LOCKED);
540 } else {
541 setState(STATE_UNINITIALIZED);
542 }
Kenny Root70e3a862012-02-15 17:20:23 -0800543
544 list_init(&mGrants);
Kenny Roota91203b2012-02-15 15:00:46 -0800545 }
546
Kenny Root51878182012-03-13 12:53:19 -0700547 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800548 return mState;
549 }
550
Kenny Root51878182012-03-13 12:53:19 -0700551 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800552 return mRetry;
553 }
554
Kenny Root70e3a862012-02-15 17:20:23 -0800555 keymaster_device_t* getDevice() const {
556 return mDevice;
557 }
558
Kenny Root07438c82012-11-02 15:41:02 -0700559 ResponseCode initialize(const android::String8& pw) {
Kenny Roota91203b2012-02-15 15:00:46 -0800560 if (!generateMasterKey()) {
561 return SYSTEM_ERROR;
562 }
563 ResponseCode response = writeMasterKey(pw);
564 if (response != NO_ERROR) {
565 return response;
566 }
567 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700568 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800569 }
570
Kenny Root07438c82012-11-02 15:41:02 -0700571 ResponseCode writeMasterKey(const android::String8& pw) {
Kenny Roota91203b2012-02-15 15:00:46 -0800572 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
573 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
574 AES_KEY passwordAesKey;
575 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700576 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Roota91203b2012-02-15 15:00:46 -0800577 return masterKeyBlob.encryptBlob(MASTER_KEY_FILE, &passwordAesKey, mEntropy);
578 }
579
Kenny Root07438c82012-11-02 15:41:02 -0700580 ResponseCode readMasterKey(const android::String8& pw) {
Kenny Root150ca932012-11-14 14:29:02 -0800581 int in = TEMP_FAILURE_RETRY(open(MASTER_KEY_FILE, O_RDONLY));
582 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800583 return SYSTEM_ERROR;
584 }
585
586 // we read the raw blob to just to get the salt to generate
587 // the AES key, then we create the Blob to use with decryptBlob
588 blob rawBlob;
589 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
590 if (close(in) != 0) {
591 return SYSTEM_ERROR;
592 }
593 // find salt at EOF if present, otherwise we have an old file
594 uint8_t* salt;
595 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
596 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
597 } else {
598 salt = NULL;
599 }
600 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
601 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
602 AES_KEY passwordAesKey;
603 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
604 Blob masterKeyBlob(rawBlob);
605 ResponseCode response = masterKeyBlob.decryptBlob(MASTER_KEY_FILE, &passwordAesKey);
606 if (response == SYSTEM_ERROR) {
607 return SYSTEM_ERROR;
608 }
609 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
610 // if salt was missing, generate one and write a new master key file with the salt.
611 if (salt == NULL) {
612 if (!generateSalt()) {
613 return SYSTEM_ERROR;
614 }
615 response = writeMasterKey(pw);
616 }
617 if (response == NO_ERROR) {
618 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
619 setupMasterKeys();
620 }
621 return response;
622 }
623 if (mRetry <= 0) {
624 reset();
625 return UNINITIALIZED;
626 }
627 --mRetry;
628 switch (mRetry) {
629 case 0: return WRONG_PASSWORD_0;
630 case 1: return WRONG_PASSWORD_1;
631 case 2: return WRONG_PASSWORD_2;
632 case 3: return WRONG_PASSWORD_3;
633 default: return WRONG_PASSWORD_3;
634 }
635 }
636
637 bool reset() {
638 clearMasterKeys();
639 setState(STATE_UNINITIALIZED);
640
641 DIR* dir = opendir(".");
642 struct dirent* file;
643
644 if (!dir) {
645 return false;
646 }
647 while ((file = readdir(dir)) != NULL) {
648 unlink(file->d_name);
649 }
650 closedir(dir);
651 return true;
652 }
653
Kenny Root51878182012-03-13 12:53:19 -0700654 bool isEmpty() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800655 DIR* dir = opendir(".");
656 struct dirent* file;
657 if (!dir) {
658 return true;
659 }
660 bool result = true;
661 while ((file = readdir(dir)) != NULL) {
662 if (isKeyFile(file->d_name)) {
663 result = false;
664 break;
665 }
666 }
667 closedir(dir);
668 return result;
669 }
670
671 void lock() {
672 clearMasterKeys();
673 setState(STATE_LOCKED);
674 }
675
Kenny Root822c3a92012-03-23 16:34:39 -0700676 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type) {
677 ResponseCode rc = keyBlob->decryptBlob(filename, &mMasterKeyDecryption);
678 if (rc != NO_ERROR) {
679 return rc;
680 }
681
682 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -0700683 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -0700684 /* If we upgrade the key, we need to write it to disk again. Then
685 * it must be read it again since the blob is encrypted each time
686 * it's written.
687 */
688 if (upgrade(filename, keyBlob, version, type)) {
689 if ((rc = this->put(filename, keyBlob)) != NO_ERROR
Kenny Rootff620c22013-04-04 10:01:44 -0700690 || (rc = keyBlob->decryptBlob(filename, &mMasterKeyDecryption)) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -0700691 return rc;
692 }
693 }
Kenny Root822c3a92012-03-23 16:34:39 -0700694 }
695
Kenny Rootd53bc922013-03-21 14:10:15 -0700696 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -0700697 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
698 return KEY_NOT_FOUND;
699 }
700
701 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -0800702 }
703
704 ResponseCode put(const char* filename, Blob* keyBlob) {
705 return keyBlob->encryptBlob(filename, &mMasterKeyEncryption, mEntropy);
706 }
707
Kenny Root07438c82012-11-02 15:41:02 -0700708 void addGrant(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 grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -0700712 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700713 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root70e3a862012-02-15 17:20:23 -0800714 list_add_tail(&mGrants, &grant->plist);
715 }
716 }
717
Kenny Root07438c82012-11-02 15:41:02 -0700718 bool removeGrant(const char* filename, uid_t granteeUid) {
719 grant_t *grant = getGrant(filename, granteeUid);
Kenny Root70e3a862012-02-15 17:20:23 -0800720 if (grant != NULL) {
721 list_remove(&grant->plist);
722 delete grant;
723 return true;
724 }
725
726 return false;
727 }
728
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700729 bool hasGrant(const char* filename, const uid_t uid) const {
730 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -0800731 }
732
Kenny Root07438c82012-11-02 15:41:02 -0700733 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename) {
Kenny Root822c3a92012-03-23 16:34:39 -0700734 uint8_t* data;
735 size_t dataLength;
736 int rc;
737
738 if (mDevice->import_keypair == NULL) {
739 ALOGE("Keymaster doesn't support import!");
740 return SYSTEM_ERROR;
741 }
742
Kenny Root07438c82012-11-02 15:41:02 -0700743 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700744 if (rc) {
745 ALOGE("Error while importing keypair: %d", rc);
746 return SYSTEM_ERROR;
747 }
748
749 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
750 free(data);
751
752 return put(filename, &keyBlob);
753 }
754
Kenny Root8ddf35a2013-03-29 11:15:50 -0700755 bool isHardwareBacked() const {
Kenny Root483407e2013-04-04 17:12:25 -0700756 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -0700757 }
758
Kenny Roota91203b2012-02-15 15:00:46 -0800759private:
760 static const char* MASTER_KEY_FILE;
761 static const int MASTER_KEY_SIZE_BYTES = 16;
762 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
763
764 static const int MAX_RETRY = 4;
765 static const size_t SALT_SIZE = 16;
766
767 Entropy* mEntropy;
768
Kenny Root70e3a862012-02-15 17:20:23 -0800769 keymaster_device_t* mDevice;
770
Kenny Roota91203b2012-02-15 15:00:46 -0800771 State mState;
772 int8_t mRetry;
773
774 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
775 uint8_t mSalt[SALT_SIZE];
776
777 AES_KEY mMasterKeyEncryption;
778 AES_KEY mMasterKeyDecryption;
779
Kenny Root70e3a862012-02-15 17:20:23 -0800780 struct listnode mGrants;
781
Kenny Roota91203b2012-02-15 15:00:46 -0800782 void setState(State state) {
783 mState = state;
784 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
785 mRetry = MAX_RETRY;
786 }
787 }
788
789 bool generateSalt() {
790 return mEntropy->generate_random_data(mSalt, sizeof(mSalt));
791 }
792
793 bool generateMasterKey() {
794 if (!mEntropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
795 return false;
796 }
797 if (!generateSalt()) {
798 return false;
799 }
800 return true;
801 }
802
803 void setupMasterKeys() {
804 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
805 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
806 setState(STATE_NO_ERROR);
807 }
808
809 void clearMasterKeys() {
810 memset(mMasterKey, 0, sizeof(mMasterKey));
811 memset(mSalt, 0, sizeof(mSalt));
812 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
813 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
814 }
815
Kenny Root07438c82012-11-02 15:41:02 -0700816 static void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
817 uint8_t* salt) {
Kenny Roota91203b2012-02-15 15:00:46 -0800818 size_t saltSize;
819 if (salt != NULL) {
820 saltSize = SALT_SIZE;
821 } else {
822 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
823 salt = (uint8_t*) "keystore";
824 // sizeof = 9, not strlen = 8
825 saltSize = sizeof("keystore");
826 }
Kenny Root07438c82012-11-02 15:41:02 -0700827
828 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
829 saltSize, 8192, keySize, key);
Kenny Roota91203b2012-02-15 15:00:46 -0800830 }
831
832 static bool isKeyFile(const char* filename) {
833 return ((strcmp(filename, MASTER_KEY_FILE) != 0)
834 && (strcmp(filename, ".") != 0)
835 && (strcmp(filename, "..") != 0));
836 }
Kenny Root70e3a862012-02-15 17:20:23 -0800837
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700838 grant_t* getGrant(const char* filename, uid_t uid) const {
Kenny Root70e3a862012-02-15 17:20:23 -0800839 struct listnode *node;
840 grant_t *grant;
841
842 list_for_each(node, &mGrants) {
843 grant = node_to_item(node, grant_t, plist);
844 if (grant->uid == uid
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700845 && !strcmp(reinterpret_cast<const char*>(grant->filename),
846 filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -0800847 return grant;
848 }
849 }
850
851 return NULL;
852 }
853
Kenny Root822c3a92012-03-23 16:34:39 -0700854 /**
855 * Upgrade code. This will upgrade the key from the current version
856 * to whatever is newest.
857 */
Kenny Rootcfeae072013-04-04 08:39:57 -0700858 bool upgrade(const char* filename, Blob* blob, const uint8_t oldVersion, const BlobType type) {
Kenny Root822c3a92012-03-23 16:34:39 -0700859 bool updated = false;
860 uint8_t version = oldVersion;
861
862 /* From V0 -> V1: All old types were unknown */
863 if (version == 0) {
864 ALOGV("upgrading to version 1 and setting type %d", type);
865
866 blob->setType(type);
867 if (type == TYPE_KEY_PAIR) {
868 importBlobAsKey(blob, filename);
869 }
870 version = 1;
871 updated = true;
872 }
873
874 /*
875 * If we've updated, set the key blob to the right version
876 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -0700877 */
Kenny Root822c3a92012-03-23 16:34:39 -0700878 if (updated) {
879 ALOGV("updated and writing file %s", filename);
880 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -0700881 }
Kenny Rootcfeae072013-04-04 08:39:57 -0700882
883 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -0700884 }
885
886 /**
887 * Takes a blob that is an PEM-encoded RSA key as a byte array and
888 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
889 * Then it overwrites the original blob with the new blob
890 * format that is returned from the keymaster.
891 */
892 ResponseCode importBlobAsKey(Blob* blob, const char* filename) {
893 // We won't even write to the blob directly with this BIO, so const_cast is okay.
894 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
895 if (b.get() == NULL) {
896 ALOGE("Problem instantiating BIO");
897 return SYSTEM_ERROR;
898 }
899
900 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
901 if (pkey.get() == NULL) {
902 ALOGE("Couldn't read old PEM file");
903 return SYSTEM_ERROR;
904 }
905
906 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
907 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
908 if (len < 0) {
909 ALOGE("Couldn't measure PKCS#8 length");
910 return SYSTEM_ERROR;
911 }
912
Kenny Root70c98892013-02-07 09:10:36 -0800913 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
914 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -0700915 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
916 ALOGE("Couldn't convert to PKCS#8");
917 return SYSTEM_ERROR;
918 }
919
Kenny Root70c98892013-02-07 09:10:36 -0800920 ResponseCode rc = importKey(pkcs8key.get(), len, filename);
Kenny Root822c3a92012-03-23 16:34:39 -0700921 if (rc != NO_ERROR) {
922 return rc;
923 }
924
925 return get(filename, blob, TYPE_KEY_PAIR);
926 }
Kenny Roota91203b2012-02-15 15:00:46 -0800927};
928
929const char* KeyStore::MASTER_KEY_FILE = ".masterkey";
930
Kenny Root07438c82012-11-02 15:41:02 -0700931static ResponseCode get_key_for_name(KeyStore* keyStore, Blob* keyBlob,
932 const android::String8& keyName, const uid_t uid, const BlobType type) {
Kenny Root70e3a862012-02-15 17:20:23 -0800933 char filename[NAME_MAX];
934
935 encode_key_for_uid(filename, uid, keyName);
Kenny Root822c3a92012-03-23 16:34:39 -0700936 ResponseCode responseCode = keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800937 if (responseCode == NO_ERROR) {
938 return responseCode;
939 }
940
Kenny Root49468902013-03-19 13:41:33 -0700941 // If this is one of the legacy UID->UID mappings, use it.
942 uid_t euid = get_keystore_euid(uid);
943 if (euid != uid) {
944 encode_key_for_uid(filename, euid, keyName);
Kenny Root822c3a92012-03-23 16:34:39 -0700945 responseCode = keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800946 if (responseCode == NO_ERROR) {
947 return responseCode;
948 }
949 }
950
951 // They might be using a granted key.
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700952 encode_key(filename, keyName);
953 if (!keyStore->hasGrant(filename, uid)) {
Kenny Root70e3a862012-02-15 17:20:23 -0800954 return responseCode;
955 }
956
957 // It is a granted key. Try to load it.
Kenny Root822c3a92012-03-23 16:34:39 -0700958 return keyStore->get(filename, keyBlob, type);
Kenny Root70e3a862012-02-15 17:20:23 -0800959}
960
Kenny Root07438c82012-11-02 15:41:02 -0700961namespace android {
962class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
963public:
964 KeyStoreProxy(KeyStore* keyStore)
965 : mKeyStore(keyStore)
966 {
Kenny Roota91203b2012-02-15 15:00:46 -0800967 }
Kenny Roota91203b2012-02-15 15:00:46 -0800968
Kenny Root07438c82012-11-02 15:41:02 -0700969 void binderDied(const wp<IBinder>&) {
970 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -0700971 }
Kenny Roota91203b2012-02-15 15:00:46 -0800972
Kenny Root07438c82012-11-02 15:41:02 -0700973 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -0800974 uid_t callingUid = IPCThreadState::self()->getCallingUid();
975 if (!has_permission(callingUid, P_TEST)) {
976 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -0700977 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -0800978 }
Kenny Roota91203b2012-02-15 15:00:46 -0800979
Kenny Root07438c82012-11-02 15:41:02 -0700980 return mKeyStore->getState();
Kenny Root298e7b12012-03-26 13:54:44 -0700981 }
982
Kenny Root07438c82012-11-02 15:41:02 -0700983 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -0800984 uid_t callingUid = IPCThreadState::self()->getCallingUid();
985 if (!has_permission(callingUid, P_GET)) {
986 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -0700987 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -0800988 }
Kenny Root07438c82012-11-02 15:41:02 -0700989
Kenny Root9d45d1c2013-02-14 10:32:30 -0800990 State state = mKeyStore->getState();
991 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -0700992 ALOGD("calling get in state: %d", state);
993 return state;
Kenny Roota91203b2012-02-15 15:00:46 -0800994 }
Kenny Root07438c82012-11-02 15:41:02 -0700995
996 String8 name8(name);
997 char filename[NAME_MAX];
Kenny Root07438c82012-11-02 15:41:02 -0700998 Blob keyBlob;
Kenny Root49468902013-03-19 13:41:33 -0700999
1000 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1001 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001002 if (responseCode != ::NO_ERROR) {
Kenny Root150ca932012-11-14 14:29:02 -08001003 ALOGW("Could not read %s", filename);
Kenny Root07438c82012-11-02 15:41:02 -07001004 *item = NULL;
1005 *itemLength = 0;
1006 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001007 }
Kenny Roota91203b2012-02-15 15:00:46 -08001008
Kenny Root07438c82012-11-02 15:41:02 -07001009 *item = (uint8_t*) malloc(keyBlob.getLength());
1010 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1011 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001012
Kenny Root07438c82012-11-02 15:41:02 -07001013 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001014 }
1015
Kenny Root49468902013-03-19 13:41:33 -07001016 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001017 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1018 if (!has_permission(callingUid, P_INSERT)) {
1019 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001020 return ::PERMISSION_DENIED;
1021 }
Kenny Root07438c82012-11-02 15:41:02 -07001022
Kenny Root49468902013-03-19 13:41:33 -07001023 if (targetUid == -1) {
1024 targetUid = callingUid;
1025 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001026 return ::PERMISSION_DENIED;
1027 }
1028
Kenny Root9d45d1c2013-02-14 10:32:30 -08001029 State state = mKeyStore->getState();
1030 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001031 ALOGD("calling insert in state: %d", state);
1032 return state;
1033 }
1034
1035 String8 name8(name);
1036 char filename[NAME_MAX];
1037
Kenny Root49468902013-03-19 13:41:33 -07001038 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001039
1040 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
1041 return mKeyStore->put(filename, &keyBlob);
Kenny Root70e3a862012-02-15 17:20:23 -08001042 }
1043
Kenny Root49468902013-03-19 13:41:33 -07001044 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001045 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1046 if (!has_permission(callingUid, P_DELETE)) {
1047 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001048 return ::PERMISSION_DENIED;
1049 }
Kenny Root70e3a862012-02-15 17:20:23 -08001050
Kenny Root49468902013-03-19 13:41:33 -07001051 if (targetUid == -1) {
1052 targetUid = callingUid;
1053 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001054 return ::PERMISSION_DENIED;
1055 }
1056
Kenny Root07438c82012-11-02 15:41:02 -07001057 String8 name8(name);
1058 char filename[NAME_MAX];
1059
Kenny Root49468902013-03-19 13:41:33 -07001060 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001061
1062 Blob keyBlob;
1063 ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, TYPE_GENERIC);
1064 if (responseCode != ::NO_ERROR) {
1065 return responseCode;
1066 }
1067 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001068 }
1069
Kenny Root49468902013-03-19 13:41:33 -07001070 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001071 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1072 if (!has_permission(callingUid, P_EXIST)) {
1073 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001074 return ::PERMISSION_DENIED;
1075 }
Kenny Root70e3a862012-02-15 17:20:23 -08001076
Kenny Root49468902013-03-19 13:41:33 -07001077 if (targetUid == -1) {
1078 targetUid = callingUid;
1079 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001080 return ::PERMISSION_DENIED;
1081 }
1082
Kenny Root07438c82012-11-02 15:41:02 -07001083 String8 name8(name);
1084 char filename[NAME_MAX];
Kenny Root70e3a862012-02-15 17:20:23 -08001085
Kenny Root49468902013-03-19 13:41:33 -07001086 encode_key_for_uid(filename, targetUid, name8);
Kenny Root70e3a862012-02-15 17:20:23 -08001087
Kenny Root07438c82012-11-02 15:41:02 -07001088 if (access(filename, R_OK) == -1) {
1089 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1090 }
1091 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001092 }
1093
Kenny Root49468902013-03-19 13:41:33 -07001094 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001095 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1096 if (!has_permission(callingUid, P_SAW)) {
1097 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001098 return ::PERMISSION_DENIED;
1099 }
Kenny Root70e3a862012-02-15 17:20:23 -08001100
Kenny Root49468902013-03-19 13:41:33 -07001101 if (targetUid == -1) {
1102 targetUid = callingUid;
1103 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001104 return ::PERMISSION_DENIED;
1105 }
1106
Kenny Root07438c82012-11-02 15:41:02 -07001107 DIR* dir = opendir(".");
1108 if (!dir) {
1109 return ::SYSTEM_ERROR;
1110 }
Kenny Root70e3a862012-02-15 17:20:23 -08001111
Kenny Root07438c82012-11-02 15:41:02 -07001112 const String8 prefix8(prefix);
1113 char filename[NAME_MAX];
Kenny Root70e3a862012-02-15 17:20:23 -08001114
Kenny Root49468902013-03-19 13:41:33 -07001115 int n = encode_key_for_uid(filename, targetUid, prefix8);
Kenny Root70e3a862012-02-15 17:20:23 -08001116
Kenny Root07438c82012-11-02 15:41:02 -07001117 struct dirent* file;
1118 while ((file = readdir(dir)) != NULL) {
1119 if (!strncmp(filename, file->d_name, n)) {
1120 const char* p = &file->d_name[n];
1121 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001122
Kenny Root07438c82012-11-02 15:41:02 -07001123 size_t extra = decode_key_length(p, plen);
1124 char *match = (char*) malloc(extra + 1);
1125 if (match != NULL) {
1126 decode_key(match, p, plen);
1127 matches->push(String16(match, extra));
1128 free(match);
1129 } else {
1130 ALOGW("could not allocate match of size %zd", extra);
1131 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001132 }
1133 }
Kenny Root07438c82012-11-02 15:41:02 -07001134 closedir(dir);
1135
1136 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001137 }
1138
Kenny Root07438c82012-11-02 15:41:02 -07001139 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001140 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1141 if (!has_permission(callingUid, P_RESET)) {
1142 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001143 return ::PERMISSION_DENIED;
1144 }
1145
1146 ResponseCode rc = mKeyStore->reset() ? ::NO_ERROR : ::SYSTEM_ERROR;
1147
1148 const keymaster_device_t* device = mKeyStore->getDevice();
1149 if (device == NULL) {
1150 ALOGE("No keymaster device!");
1151 return ::SYSTEM_ERROR;
1152 }
1153
1154 if (device->delete_all == NULL) {
1155 ALOGV("keymaster device doesn't implement delete_all");
1156 return rc;
1157 }
1158
1159 if (device->delete_all(device)) {
1160 ALOGE("Problem calling keymaster's delete_all");
1161 return ::SYSTEM_ERROR;
1162 }
1163
Kenny Root9a53d3e2012-08-14 10:47:54 -07001164 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001165 }
1166
Kenny Root07438c82012-11-02 15:41:02 -07001167 /*
1168 * Here is the history. To improve the security, the parameters to generate the
1169 * master key has been changed. To make a seamless transition, we update the
1170 * file using the same password when the user unlock it for the first time. If
1171 * any thing goes wrong during the transition, the new file will not overwrite
1172 * the old one. This avoids permanent damages of the existing data.
1173 */
1174 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001175 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1176 if (!has_permission(callingUid, P_PASSWORD)) {
1177 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001178 return ::PERMISSION_DENIED;
1179 }
Kenny Root70e3a862012-02-15 17:20:23 -08001180
Kenny Root07438c82012-11-02 15:41:02 -07001181 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001182
Kenny Root07438c82012-11-02 15:41:02 -07001183 switch (mKeyStore->getState()) {
1184 case ::STATE_UNINITIALIZED: {
1185 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
1186 return mKeyStore->initialize(password8);
1187 }
1188 case ::STATE_NO_ERROR: {
1189 // rewrite master key with new password.
1190 return mKeyStore->writeMasterKey(password8);
1191 }
1192 case ::STATE_LOCKED: {
1193 // read master key, decrypt with password, initialize mMasterKey*.
1194 return mKeyStore->readMasterKey(password8);
1195 }
1196 }
1197 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001198 }
1199
Kenny Root07438c82012-11-02 15:41:02 -07001200 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001201 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1202 if (!has_permission(callingUid, P_LOCK)) {
1203 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001204 return ::PERMISSION_DENIED;
1205 }
Kenny Root70e3a862012-02-15 17:20:23 -08001206
Kenny Root9d45d1c2013-02-14 10:32:30 -08001207 State state = mKeyStore->getState();
1208 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001209 ALOGD("calling lock in state: %d", state);
1210 return state;
1211 }
1212
1213 mKeyStore->lock();
1214 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001215 }
1216
Kenny Root07438c82012-11-02 15:41:02 -07001217 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001218 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1219 if (!has_permission(callingUid, P_UNLOCK)) {
1220 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001221 return ::PERMISSION_DENIED;
1222 }
1223
Kenny Root9d45d1c2013-02-14 10:32:30 -08001224 State state = mKeyStore->getState();
1225 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001226 ALOGD("calling unlock when not locked");
1227 return state;
1228 }
1229
1230 const String8 password8(pw);
1231 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001232 }
1233
Kenny Root07438c82012-11-02 15:41:02 -07001234 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001235 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1236 if (!has_permission(callingUid, P_ZERO)) {
1237 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001238 return -1;
1239 }
Kenny Root70e3a862012-02-15 17:20:23 -08001240
Kenny Root07438c82012-11-02 15:41:02 -07001241 return mKeyStore->isEmpty() ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001242 }
1243
Kenny Root49468902013-03-19 13:41:33 -07001244 int32_t generate(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001245 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1246 if (!has_permission(callingUid, P_INSERT)) {
1247 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001248 return ::PERMISSION_DENIED;
1249 }
Kenny Root70e3a862012-02-15 17:20:23 -08001250
Kenny Root49468902013-03-19 13:41:33 -07001251 if (targetUid == -1) {
1252 targetUid = callingUid;
1253 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001254 return ::PERMISSION_DENIED;
1255 }
1256
Kenny Root9d45d1c2013-02-14 10:32:30 -08001257 State state = mKeyStore->getState();
1258 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001259 ALOGD("calling generate in state: %d", state);
1260 return state;
1261 }
Kenny Root70e3a862012-02-15 17:20:23 -08001262
Kenny Root07438c82012-11-02 15:41:02 -07001263 String8 name8(name);
1264 char filename[NAME_MAX];
1265
1266 uint8_t* data;
1267 size_t dataLength;
1268 int rc;
1269
1270 const keymaster_device_t* device = mKeyStore->getDevice();
1271 if (device == NULL) {
1272 return ::SYSTEM_ERROR;
1273 }
1274
1275 if (device->generate_keypair == NULL) {
1276 return ::SYSTEM_ERROR;
1277 }
1278
1279 keymaster_rsa_keygen_params_t rsa_params;
1280 rsa_params.modulus_size = 2048;
1281 rsa_params.public_exponent = 0x10001;
1282
1283 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1284 if (rc) {
1285 return ::SYSTEM_ERROR;
1286 }
1287
Kenny Root49468902013-03-19 13:41:33 -07001288 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001289
1290 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1291 free(data);
1292
1293 return mKeyStore->put(filename, &keyBlob);
Kenny Root70e3a862012-02-15 17:20:23 -08001294 }
1295
Kenny Root49468902013-03-19 13:41:33 -07001296 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001297 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1298 if (!has_permission(callingUid, P_INSERT)) {
1299 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001300 return ::PERMISSION_DENIED;
1301 }
Kenny Root07438c82012-11-02 15:41:02 -07001302
Kenny Root49468902013-03-19 13:41:33 -07001303 if (targetUid == -1) {
1304 targetUid = callingUid;
1305 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001306 return ::PERMISSION_DENIED;
1307 }
1308
Kenny Root9d45d1c2013-02-14 10:32:30 -08001309 State state = mKeyStore->getState();
1310 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001311 ALOGD("calling import in state: %d", state);
1312 return state;
1313 }
1314
1315 String8 name8(name);
1316 char filename[NAME_MAX];
1317
Kenny Root49468902013-03-19 13:41:33 -07001318 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001319
1320 return mKeyStore->importKey(data, length, filename);
Kenny Root70e3a862012-02-15 17:20:23 -08001321 }
1322
Kenny Root07438c82012-11-02 15:41:02 -07001323 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1324 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001325 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1326 if (!has_permission(callingUid, P_SIGN)) {
1327 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001328 return ::PERMISSION_DENIED;
1329 }
Kenny Root07438c82012-11-02 15:41:02 -07001330
Kenny Root9d45d1c2013-02-14 10:32:30 -08001331 State state = mKeyStore->getState();
1332 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001333 ALOGD("calling sign in state: %d", state);
1334 return state;
1335 }
1336
1337 Blob keyBlob;
1338 String8 name8(name);
1339
Kenny Rootd38a0b02013-02-13 12:59:14 -08001340 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001341 int rc;
1342
Kenny Rootd38a0b02013-02-13 12:59:14 -08001343 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1344 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001345 if (responseCode != ::NO_ERROR) {
1346 return responseCode;
1347 }
1348
1349 const keymaster_device_t* device = mKeyStore->getDevice();
1350 if (device == NULL) {
1351 ALOGE("no keymaster device; cannot sign");
1352 return ::SYSTEM_ERROR;
1353 }
1354
1355 if (device->sign_data == NULL) {
1356 ALOGE("device doesn't implement signing");
1357 return ::SYSTEM_ERROR;
1358 }
1359
1360 keymaster_rsa_sign_params_t params;
1361 params.digest_type = DIGEST_NONE;
1362 params.padding_type = PADDING_NONE;
1363
1364 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1365 data, length, out, outLength);
1366 if (rc) {
1367 ALOGW("device couldn't sign data");
1368 return ::SYSTEM_ERROR;
1369 }
1370
1371 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001372 }
1373
Kenny Root07438c82012-11-02 15:41:02 -07001374 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
1375 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001376 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1377 if (!has_permission(callingUid, P_VERIFY)) {
1378 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001379 return ::PERMISSION_DENIED;
1380 }
Kenny Root70e3a862012-02-15 17:20:23 -08001381
Kenny Root9d45d1c2013-02-14 10:32:30 -08001382 State state = mKeyStore->getState();
1383 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001384 ALOGD("calling verify in state: %d", state);
1385 return state;
1386 }
Kenny Root70e3a862012-02-15 17:20:23 -08001387
Kenny Root07438c82012-11-02 15:41:02 -07001388 Blob keyBlob;
1389 String8 name8(name);
1390 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001391
Kenny Root49468902013-03-19 13:41:33 -07001392 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
1393 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001394 if (responseCode != ::NO_ERROR) {
1395 return responseCode;
1396 }
Kenny Root70e3a862012-02-15 17:20:23 -08001397
Kenny Root07438c82012-11-02 15:41:02 -07001398 const keymaster_device_t* device = mKeyStore->getDevice();
1399 if (device == NULL) {
1400 return ::SYSTEM_ERROR;
1401 }
Kenny Root70e3a862012-02-15 17:20:23 -08001402
Kenny Root07438c82012-11-02 15:41:02 -07001403 if (device->verify_data == NULL) {
1404 return ::SYSTEM_ERROR;
1405 }
Kenny Root70e3a862012-02-15 17:20:23 -08001406
Kenny Root07438c82012-11-02 15:41:02 -07001407 keymaster_rsa_sign_params_t params;
1408 params.digest_type = DIGEST_NONE;
1409 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07001410
Kenny Root07438c82012-11-02 15:41:02 -07001411 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(),
1412 data, dataLength, signature, signatureLength);
1413 if (rc) {
1414 return ::SYSTEM_ERROR;
1415 } else {
1416 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001417 }
1418 }
Kenny Root07438c82012-11-02 15:41:02 -07001419
1420 /*
1421 * TODO: The abstraction between things stored in hardware and regular blobs
1422 * of data stored on the filesystem should be moved down to keystore itself.
1423 * Unfortunately the Java code that calls this has naming conventions that it
1424 * knows about. Ideally keystore shouldn't be used to store random blobs of
1425 * data.
1426 *
1427 * Until that happens, it's necessary to have a separate "get_pubkey" and
1428 * "del_key" since the Java code doesn't really communicate what it's
1429 * intentions are.
1430 */
1431 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001432 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1433 if (!has_permission(callingUid, P_GET)) {
1434 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001435 return ::PERMISSION_DENIED;
1436 }
Kenny Root07438c82012-11-02 15:41:02 -07001437
Kenny Root9d45d1c2013-02-14 10:32:30 -08001438 State state = mKeyStore->getState();
1439 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001440 ALOGD("calling get_pubkey in state: %d", state);
1441 return state;
1442 }
1443
1444 Blob keyBlob;
1445 String8 name8(name);
1446
Kenny Rootd38a0b02013-02-13 12:59:14 -08001447 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001448
Kenny Rootd38a0b02013-02-13 12:59:14 -08001449 ResponseCode responseCode = get_key_for_name(mKeyStore, &keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07001450 TYPE_KEY_PAIR);
1451 if (responseCode != ::NO_ERROR) {
1452 return responseCode;
1453 }
1454
1455 const keymaster_device_t* device = mKeyStore->getDevice();
1456 if (device == NULL) {
1457 return ::SYSTEM_ERROR;
1458 }
1459
1460 if (device->get_keypair_public == NULL) {
1461 ALOGE("device has no get_keypair_public implementation!");
1462 return ::SYSTEM_ERROR;
1463 }
1464
1465 int rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
1466 pubkeyLength);
1467 if (rc) {
1468 return ::SYSTEM_ERROR;
1469 }
1470
1471 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08001472 }
Kenny Root07438c82012-11-02 15:41:02 -07001473
Kenny Root49468902013-03-19 13:41:33 -07001474 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001475 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1476 if (!has_permission(callingUid, P_DELETE)) {
1477 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001478 return ::PERMISSION_DENIED;
1479 }
Kenny Root07438c82012-11-02 15:41:02 -07001480
Kenny Root49468902013-03-19 13:41:33 -07001481 if (targetUid == -1) {
1482 targetUid = callingUid;
1483 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001484 return ::PERMISSION_DENIED;
1485 }
1486
Kenny Root07438c82012-11-02 15:41:02 -07001487 String8 name8(name);
1488 char filename[NAME_MAX];
1489
Kenny Root49468902013-03-19 13:41:33 -07001490 encode_key_for_uid(filename, targetUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001491
1492 Blob keyBlob;
1493 ResponseCode responseCode = mKeyStore->get(filename, &keyBlob, ::TYPE_KEY_PAIR);
1494 if (responseCode != ::NO_ERROR) {
1495 return responseCode;
1496 }
1497
1498 ResponseCode rc = ::NO_ERROR;
1499
1500 const keymaster_device_t* device = mKeyStore->getDevice();
1501 if (device == NULL) {
1502 rc = ::SYSTEM_ERROR;
1503 } else {
1504 // A device doesn't have to implement delete_keypair.
1505 if (device->delete_keypair != NULL) {
1506 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1507 rc = ::SYSTEM_ERROR;
1508 }
1509 }
1510 }
1511
1512 if (rc != ::NO_ERROR) {
1513 return rc;
1514 }
1515
1516 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1517 }
1518
1519 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001520 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1521 if (!has_permission(callingUid, P_GRANT)) {
1522 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001523 return ::PERMISSION_DENIED;
1524 }
Kenny Root07438c82012-11-02 15:41:02 -07001525
Kenny Root9d45d1c2013-02-14 10:32:30 -08001526 State state = mKeyStore->getState();
1527 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001528 ALOGD("calling grant in state: %d", state);
1529 return state;
1530 }
1531
1532 String8 name8(name);
1533 char filename[NAME_MAX];
1534
Kenny Rootd38a0b02013-02-13 12:59:14 -08001535 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001536
1537 if (access(filename, R_OK) == -1) {
1538 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1539 }
1540
1541 mKeyStore->addGrant(filename, granteeUid);
1542 return ::NO_ERROR;
1543 }
1544
1545 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001546 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1547 if (!has_permission(callingUid, P_GRANT)) {
1548 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001549 return ::PERMISSION_DENIED;
1550 }
Kenny Root07438c82012-11-02 15:41:02 -07001551
Kenny Root9d45d1c2013-02-14 10:32:30 -08001552 State state = mKeyStore->getState();
1553 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001554 ALOGD("calling ungrant in state: %d", state);
1555 return state;
1556 }
1557
1558 String8 name8(name);
1559 char filename[NAME_MAX];
1560
Kenny Rootd38a0b02013-02-13 12:59:14 -08001561 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001562
1563 if (access(filename, R_OK) == -1) {
1564 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1565 }
1566
1567 return mKeyStore->removeGrant(filename, granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
1568 }
1569
1570 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001571 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1572 if (!has_permission(callingUid, P_GET)) {
1573 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08001574 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001575 }
Kenny Root07438c82012-11-02 15:41:02 -07001576
1577 String8 name8(name);
1578 char filename[NAME_MAX];
1579
Kenny Rootd38a0b02013-02-13 12:59:14 -08001580 encode_key_for_uid(filename, callingUid, name8);
Kenny Root07438c82012-11-02 15:41:02 -07001581
1582 if (access(filename, R_OK) == -1) {
Kenny Root36a9e232013-02-04 14:24:15 -08001583 ALOGW("could not access %s for getmtime", filename);
1584 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001585 }
1586
Kenny Root150ca932012-11-14 14:29:02 -08001587 int fd = TEMP_FAILURE_RETRY(open(filename, O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07001588 if (fd < 0) {
Kenny Root36a9e232013-02-04 14:24:15 -08001589 ALOGW("could not open %s for getmtime", filename);
1590 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001591 }
1592
1593 struct stat s;
1594 int ret = fstat(fd, &s);
1595 close(fd);
1596 if (ret == -1) {
Kenny Root36a9e232013-02-04 14:24:15 -08001597 ALOGW("could not stat %s for getmtime", filename);
1598 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07001599 }
1600
Kenny Root36a9e232013-02-04 14:24:15 -08001601 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07001602 }
1603
Kenny Rootd53bc922013-03-21 14:10:15 -07001604 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
1605 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07001606 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Rootd53bc922013-03-21 14:10:15 -07001607 if (!has_permission(callingUid, P_DUPLICATE)) {
1608 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07001609 return -1L;
1610 }
1611
1612 State state = mKeyStore->getState();
1613 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07001614 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07001615 return state;
1616 }
1617
Kenny Rootd53bc922013-03-21 14:10:15 -07001618 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
1619 srcUid = callingUid;
1620 } else if (!is_granted_to(callingUid, srcUid)) {
1621 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07001622 return ::PERMISSION_DENIED;
1623 }
1624
Kenny Rootd53bc922013-03-21 14:10:15 -07001625 if (destUid == -1) {
1626 destUid = callingUid;
1627 }
1628
1629 if (srcUid != destUid) {
1630 if (static_cast<uid_t>(srcUid) != callingUid) {
1631 ALOGD("can only duplicate from caller to other or to same uid: "
1632 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
1633 return ::PERMISSION_DENIED;
1634 }
1635
1636 if (!is_granted_to(callingUid, destUid)) {
1637 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
1638 return ::PERMISSION_DENIED;
1639 }
1640 }
1641
1642 String8 source8(srcKey);
Kenny Root02254072013-03-20 11:48:19 -07001643 char source[NAME_MAX];
1644
Kenny Rootd53bc922013-03-21 14:10:15 -07001645 encode_key_for_uid(source, srcUid, source8);
Kenny Root02254072013-03-20 11:48:19 -07001646
Kenny Rootd53bc922013-03-21 14:10:15 -07001647 String8 target8(destKey);
Kenny Root02254072013-03-20 11:48:19 -07001648 char target[NAME_MAX];
1649
Kenny Rootd53bc922013-03-21 14:10:15 -07001650 encode_key_for_uid(target, destUid, target8);
Kenny Root02254072013-03-20 11:48:19 -07001651
Kenny Rootd53bc922013-03-21 14:10:15 -07001652 if (access(target, W_OK) != -1 || errno != ENOENT) {
1653 ALOGD("destination already exists: %s", target);
Kenny Root02254072013-03-20 11:48:19 -07001654 return ::SYSTEM_ERROR;
1655 }
1656
Kenny Rootd53bc922013-03-21 14:10:15 -07001657 Blob keyBlob;
1658 ResponseCode responseCode = mKeyStore->get(source, &keyBlob, TYPE_ANY);
1659 if (responseCode != ::NO_ERROR) {
1660 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07001661 }
Kenny Rootd53bc922013-03-21 14:10:15 -07001662
1663 return mKeyStore->put(target, &keyBlob);
Kenny Root02254072013-03-20 11:48:19 -07001664 }
1665
Kenny Root8ddf35a2013-03-29 11:15:50 -07001666 int32_t is_hardware_backed() {
1667 return mKeyStore->isHardwareBacked() ? 1 : 0;
1668 }
1669
Kenny Roota9bb5492013-04-01 16:29:11 -07001670 int32_t clear_uid(int64_t targetUid) {
1671 uid_t callingUid = IPCThreadState::self()->getCallingUid();
1672 if (!has_permission(callingUid, P_CLEAR_UID)) {
1673 ALOGW("permission denied for %d: clear_uid", callingUid);
1674 return ::PERMISSION_DENIED;
1675 }
1676
1677 State state = mKeyStore->getState();
1678 if (!isKeystoreUnlocked(state)) {
1679 ALOGD("calling clear_uid in state: %d", state);
1680 return state;
1681 }
1682
1683 const keymaster_device_t* device = mKeyStore->getDevice();
1684 if (device == NULL) {
1685 return ::SYSTEM_ERROR;
1686 }
1687
1688 DIR* dir = opendir(".");
1689 if (!dir) {
1690 return ::SYSTEM_ERROR;
1691 }
1692
1693 char filename[NAME_MAX];
1694 int n = snprintf(filename, NAME_MAX, "%u_", static_cast<uid_t>(targetUid));
1695 char *end = &filename[n];
1696
1697 ResponseCode rc = ::NO_ERROR;
1698
1699 struct dirent* file;
1700 while ((file = readdir(dir)) != NULL) {
1701 if (strncmp(filename, file->d_name, n)) {
1702 continue;
1703 }
1704
1705 String8 file8(&file->d_name[n]);
1706 encode_key(end, file8);
1707
1708 Blob keyBlob;
1709 if (mKeyStore->get(filename, &keyBlob, ::TYPE_ANY) != ::NO_ERROR) {
1710 ALOGW("couldn't open %s", filename);
1711 continue;
1712 }
1713
1714 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1715 // A device doesn't have to implement delete_keypair.
1716 if (device->delete_keypair != NULL) {
1717 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
1718 rc = ::SYSTEM_ERROR;
1719 ALOGW("device couldn't remove %s", filename);
1720 }
1721 }
1722 }
1723
1724 if (unlink(filename) && errno != ENOENT) {
1725 rc = ::SYSTEM_ERROR;
1726 ALOGW("couldn't unlink %s", filename);
1727 }
1728 }
1729 closedir(dir);
1730
1731 return rc;
1732 }
1733
Kenny Root07438c82012-11-02 15:41:02 -07001734private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08001735 inline bool isKeystoreUnlocked(State state) {
1736 switch (state) {
1737 case ::STATE_NO_ERROR:
1738 return true;
1739 case ::STATE_UNINITIALIZED:
1740 case ::STATE_LOCKED:
1741 return false;
1742 }
1743 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001744 }
1745
1746 ::KeyStore* mKeyStore;
1747};
1748
1749}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08001750
1751int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08001752 if (argc < 2) {
1753 ALOGE("A directory must be specified!");
1754 return 1;
1755 }
1756 if (chdir(argv[1]) == -1) {
1757 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
1758 return 1;
1759 }
1760
1761 Entropy entropy;
1762 if (!entropy.open()) {
1763 return 1;
1764 }
Kenny Root70e3a862012-02-15 17:20:23 -08001765
1766 keymaster_device_t* dev;
1767 if (keymaster_device_initialize(&dev)) {
1768 ALOGE("keystore keymaster could not be initialized; exiting");
1769 return 1;
1770 }
1771
Kenny Root70e3a862012-02-15 17:20:23 -08001772 KeyStore keyStore(&entropy, dev);
Kenny Root07438c82012-11-02 15:41:02 -07001773 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
1774 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
1775 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
1776 if (ret != android::OK) {
1777 ALOGE("Couldn't register binder service!");
1778 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08001779 }
Kenny Root07438c82012-11-02 15:41:02 -07001780
1781 /*
1782 * We're the only thread in existence, so we're just going to process
1783 * Binder transaction as a single-threaded program.
1784 */
1785 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08001786
1787 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08001788 return 1;
1789}