blob: 5af534f629290a14288545f280a4f2d4111ff6d6 [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>
Kenny Root655b9582013-04-04 08:37:42 -070027#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080028#include <fcntl.h>
29#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070030#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080031#include <sys/types.h>
32#include <sys/socket.h>
33#include <sys/stat.h>
34#include <sys/time.h>
35#include <arpa/inet.h>
Riley Spahn0e542d02014-06-19 08:27:07 -070036#include <string.h>
Kenny Roota91203b2012-02-15 15:00:46 -080037
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Kenny Root70e3a862012-02-15 17:20:23 -080044#include <hardware/keymaster.h>
45
Kenny Root17208e02013-09-04 13:56:03 -070046#include <keymaster/softkeymaster.h>
47
Kenny Root26cfc082013-09-11 14:38:56 -070048#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070049#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070050#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080051
Kenny Root07438c82012-11-02 15:41:02 -070052#include <keystore/IKeystoreService.h>
53#include <binder/IPCThreadState.h>
54#include <binder/IServiceManager.h>
55
Kenny Roota91203b2012-02-15 15:00:46 -080056#include <cutils/log.h>
57#include <cutils/sockets.h>
58#include <private/android_filesystem_config.h>
59
Kenny Root07438c82012-11-02 15:41:02 -070060#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080061
Riley Spahn0e542d02014-06-19 08:27:07 -070062#include <selinux/android.h>
63
Kenny Root96427ba2013-08-16 14:02:41 -070064#include "defaults.h"
65
Kenny Roota91203b2012-02-15 15:00:46 -080066/* KeyStore is a secured storage for key-value pairs. In this implementation,
67 * each file stores one key-value pair. Keys are encoded in file names, and
68 * values are encrypted with checksums. The encryption key is protected by a
69 * user-defined password. To keep things simple, buffers are always larger than
70 * the maximum space we needed, so boundary checks on buffers are omitted. */
71
72#define KEY_SIZE ((NAME_MAX - 15) / 2)
73#define VALUE_SIZE 32768
74#define PASSWORD_SIZE VALUE_SIZE
75
Kenny Root822c3a92012-03-23 16:34:39 -070076
Kenny Root96427ba2013-08-16 14:02:41 -070077struct BIGNUM_Delete {
78 void operator()(BIGNUM* p) const {
79 BN_free(p);
80 }
81};
82typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
83
Kenny Root822c3a92012-03-23 16:34:39 -070084struct BIO_Delete {
85 void operator()(BIO* p) const {
86 BIO_free(p);
87 }
88};
89typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
90
91struct EVP_PKEY_Delete {
92 void operator()(EVP_PKEY* p) const {
93 EVP_PKEY_free(p);
94 }
95};
96typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
97
98struct PKCS8_PRIV_KEY_INFO_Delete {
99 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
100 PKCS8_PRIV_KEY_INFO_free(p);
101 }
102};
103typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
104
105
Kenny Root70e3a862012-02-15 17:20:23 -0800106static int keymaster_device_initialize(keymaster_device_t** dev) {
107 int rc;
108
109 const hw_module_t* mod;
110 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
111 if (rc) {
112 ALOGE("could not find any keystore module");
113 goto out;
114 }
115
116 rc = keymaster_open(mod, dev);
117 if (rc) {
118 ALOGE("could not open keymaster device in %s (%s)",
119 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
120 goto out;
121 }
122
123 return 0;
124
125out:
126 *dev = NULL;
127 return rc;
128}
129
130static void keymaster_device_release(keymaster_device_t* dev) {
131 keymaster_close(dev);
132}
133
Kenny Root07438c82012-11-02 15:41:02 -0700134/***************
135 * PERMISSIONS *
136 ***************/
137
138/* Here are the permissions, actions, users, and the main function. */
139typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700140 P_TEST = 1 << 0,
141 P_GET = 1 << 1,
142 P_INSERT = 1 << 2,
143 P_DELETE = 1 << 3,
144 P_EXIST = 1 << 4,
145 P_SAW = 1 << 5,
146 P_RESET = 1 << 6,
147 P_PASSWORD = 1 << 7,
148 P_LOCK = 1 << 8,
149 P_UNLOCK = 1 << 9,
150 P_ZERO = 1 << 10,
151 P_SIGN = 1 << 11,
152 P_VERIFY = 1 << 12,
153 P_GRANT = 1 << 13,
154 P_DUPLICATE = 1 << 14,
Kenny Roota9bb5492013-04-01 16:29:11 -0700155 P_CLEAR_UID = 1 << 15,
Kenny Root07438c82012-11-02 15:41:02 -0700156} perm_t;
157
Riley Spahn0e542d02014-06-19 08:27:07 -0700158/* perm_labels associcated with keystore_key SELinux class verbs. */
159const char *perm_labels[] = {
160 "test",
161 "get",
162 "insert",
163 "delete",
164 "exist",
165 "saw",
166 "reset",
167 "password",
168 "lock",
169 "unlock",
170 "zero",
171 "sign",
172 "verify",
173 "grant",
174 "duplicate",
175 "clear_uid"
176};
177
Kenny Root07438c82012-11-02 15:41:02 -0700178static struct user_euid {
179 uid_t uid;
180 uid_t euid;
181} user_euids[] = {
182 {AID_VPN, AID_SYSTEM},
183 {AID_WIFI, AID_SYSTEM},
184 {AID_ROOT, AID_SYSTEM},
185};
186
187static struct user_perm {
188 uid_t uid;
189 perm_t perms;
190} user_perms[] = {
191 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
192 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
193 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
194 {AID_ROOT, static_cast<perm_t>(P_GET) },
195};
196
197static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
198 | P_VERIFY);
199
Riley Spahn0e542d02014-06-19 08:27:07 -0700200static char *tctx;
201
202static const char *get_perm_label(perm_t perm) {
203 unsigned int index = ffs(perm);
204 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
205 return perm_labels[index - 1];
206 } else {
207 ALOGE("Keystore: Failed to retrieve permission label.\n");
208 abort();
209 }
210}
211
Kenny Root655b9582013-04-04 08:37:42 -0700212/**
213 * Returns the app ID (in the Android multi-user sense) for the current
214 * UNIX UID.
215 */
216static uid_t get_app_id(uid_t uid) {
217 return uid % AID_USER;
218}
219
220/**
221 * Returns the user ID (in the Android multi-user sense) for the current
222 * UNIX UID.
223 */
224static uid_t get_user_id(uid_t uid) {
225 return uid / AID_USER;
226}
227
Riley Spahn0e542d02014-06-19 08:27:07 -0700228static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700229 // All system users are equivalent for multi-user support.
230 if (get_app_id(uid) == AID_SYSTEM) {
231 uid = AID_SYSTEM;
232 }
233
Riley Spahn0e542d02014-06-19 08:27:07 -0700234 char *sctx = NULL;
235 const char *selinux_class = "keystore_key";
236 const char *str_perm = get_perm_label(perm);
237
238 if (!str_perm) {
239 return false;
240 }
241
242 if (getpidcon(spid, &sctx) != 0) {
243 ALOGE("SELinux: Failed to get source pid context.\n");
244 return false;
245 }
246
Kenny Root07438c82012-11-02 15:41:02 -0700247 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
248 struct user_perm user = user_perms[i];
249 if (user.uid == uid) {
Riley Spahn0e542d02014-06-19 08:27:07 -0700250 bool result = (user.perms & perm) && (selinux_check_access(sctx,
251 tctx, selinux_class, str_perm, NULL) == 0);
252 freecon(sctx);
253 return result;
Kenny Root07438c82012-11-02 15:41:02 -0700254 }
255 }
256
Riley Spahn0e542d02014-06-19 08:27:07 -0700257 bool result = (DEFAULT_PERMS & perm) && (selinux_check_access(sctx,
258 tctx, selinux_class, str_perm, NULL) == 0);
259 freecon(sctx);
260 return result;
Kenny Root07438c82012-11-02 15:41:02 -0700261}
262
Kenny Root49468902013-03-19 13:41:33 -0700263/**
264 * Returns the UID that the callingUid should act as. This is here for
265 * legacy support of the WiFi and VPN systems and should be removed
266 * when WiFi can operate in its own namespace.
267 */
Kenny Root07438c82012-11-02 15:41:02 -0700268static uid_t get_keystore_euid(uid_t uid) {
269 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
270 struct user_euid user = user_euids[i];
271 if (user.uid == uid) {
272 return user.euid;
273 }
274 }
275
276 return uid;
277}
278
Kenny Root49468902013-03-19 13:41:33 -0700279/**
280 * Returns true if the callingUid is allowed to interact in the targetUid's
281 * namespace.
282 */
283static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
284 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
285 struct user_euid user = user_euids[i];
286 if (user.euid == callingUid && user.uid == targetUid) {
287 return true;
288 }
289 }
290
291 return false;
292}
293
Kenny Roota91203b2012-02-15 15:00:46 -0800294/* Here is the encoding of keys. This is necessary in order to allow arbitrary
295 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
296 * into two bytes. The first byte is one of [+-.] which represents the first
297 * two bits of the character. The second byte encodes the rest of the bits into
298 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
299 * that Base64 cannot be used here due to the need of prefix match on keys. */
300
Kenny Root655b9582013-04-04 08:37:42 -0700301static size_t encode_key_length(const android::String8& keyName) {
302 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
303 size_t length = keyName.length();
304 for (int i = length; i > 0; --i, ++in) {
305 if (*in < '0' || *in > '~') {
306 ++length;
307 }
308 }
309 return length;
310}
311
Kenny Root07438c82012-11-02 15:41:02 -0700312static int encode_key(char* out, const android::String8& keyName) {
313 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
314 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800315 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700316 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800317 *out = '+' + (*in >> 6);
318 *++out = '0' + (*in & 0x3F);
319 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700320 } else {
321 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800322 }
323 }
324 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800325 return length;
326}
327
Kenny Root07438c82012-11-02 15:41:02 -0700328/*
329 * Converts from the "escaped" format on disk to actual name.
330 * This will be smaller than the input string.
331 *
332 * Characters that should combine with the next at the end will be truncated.
333 */
334static size_t decode_key_length(const char* in, size_t length) {
335 size_t outLength = 0;
336
337 for (const char* end = in + length; in < end; in++) {
338 /* This combines with the next character. */
339 if (*in < '0' || *in > '~') {
340 continue;
341 }
342
343 outLength++;
344 }
345 return outLength;
346}
347
348static void decode_key(char* out, const char* in, size_t length) {
349 for (const char* end = in + length; in < end; in++) {
350 if (*in < '0' || *in > '~') {
351 /* Truncate combining characters at the end. */
352 if (in + 1 >= end) {
353 break;
354 }
355
356 *out = (*in++ - '+') << 6;
357 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800358 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700359 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800360 }
361 }
362 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800363}
364
365static size_t readFully(int fd, uint8_t* data, size_t size) {
366 size_t remaining = size;
367 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800368 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800369 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800370 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800371 }
372 data += n;
373 remaining -= n;
374 }
375 return size;
376}
377
378static size_t writeFully(int fd, uint8_t* data, size_t size) {
379 size_t remaining = size;
380 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800381 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
382 if (n < 0) {
383 ALOGW("write failed: %s", strerror(errno));
384 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800385 }
386 data += n;
387 remaining -= n;
388 }
389 return size;
390}
391
392class Entropy {
393public:
394 Entropy() : mRandom(-1) {}
395 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800396 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800397 close(mRandom);
398 }
399 }
400
401 bool open() {
402 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800403 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
404 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800405 ALOGE("open: %s: %s", randomDevice, strerror(errno));
406 return false;
407 }
408 return true;
409 }
410
Kenny Root51878182012-03-13 12:53:19 -0700411 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800412 return (readFully(mRandom, data, size) == size);
413 }
414
415private:
416 int mRandom;
417};
418
419/* Here is the file format. There are two parts in blob.value, the secret and
420 * the description. The secret is stored in ciphertext, and its original size
421 * can be found in blob.length. The description is stored after the secret in
422 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700423 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700424 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800425 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
426 * and decryptBlob(). Thus they should not be accessed from outside. */
427
Kenny Root822c3a92012-03-23 16:34:39 -0700428/* ** Note to future implementors of encryption: **
429 * Currently this is the construction:
430 * metadata || Enc(MD5(data) || data)
431 *
432 * This should be the construction used for encrypting if re-implementing:
433 *
434 * Derive independent keys for encryption and MAC:
435 * Kenc = AES_encrypt(masterKey, "Encrypt")
436 * Kmac = AES_encrypt(masterKey, "MAC")
437 *
438 * Store this:
439 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
440 * HMAC(Kmac, metadata || Enc(data))
441 */
Kenny Roota91203b2012-02-15 15:00:46 -0800442struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700443 uint8_t version;
444 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700445 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800446 uint8_t info;
447 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700448 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800449 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700450 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800451 int32_t length; // in network byte order when encrypted
452 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
453};
454
Kenny Root822c3a92012-03-23 16:34:39 -0700455typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700456 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700457 TYPE_GENERIC = 1,
458 TYPE_MASTER_KEY = 2,
459 TYPE_KEY_PAIR = 3,
460} BlobType;
461
Kenny Rootf9119d62013-04-03 09:22:15 -0700462static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700463
Kenny Roota91203b2012-02-15 15:00:46 -0800464class Blob {
465public:
Kenny Root07438c82012-11-02 15:41:02 -0700466 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
467 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800468 mBlob.length = valueLength;
469 memcpy(mBlob.value, value, valueLength);
470
471 mBlob.info = infoLength;
472 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700473
Kenny Root07438c82012-11-02 15:41:02 -0700474 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700475 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700476
Kenny Rootee8068b2013-10-07 09:49:15 -0700477 if (type == TYPE_MASTER_KEY) {
478 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
479 } else {
480 mBlob.flags = KEYSTORE_FLAG_NONE;
481 }
Kenny Roota91203b2012-02-15 15:00:46 -0800482 }
483
484 Blob(blob b) {
485 mBlob = b;
486 }
487
488 Blob() {}
489
Kenny Root51878182012-03-13 12:53:19 -0700490 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800491 return mBlob.value;
492 }
493
Kenny Root51878182012-03-13 12:53:19 -0700494 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800495 return mBlob.length;
496 }
497
Kenny Root51878182012-03-13 12:53:19 -0700498 const uint8_t* getInfo() const {
499 return mBlob.value + mBlob.length;
500 }
501
502 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800503 return mBlob.info;
504 }
505
Kenny Root822c3a92012-03-23 16:34:39 -0700506 uint8_t getVersion() const {
507 return mBlob.version;
508 }
509
Kenny Rootf9119d62013-04-03 09:22:15 -0700510 bool isEncrypted() const {
511 if (mBlob.version < 2) {
512 return true;
513 }
514
515 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
516 }
517
518 void setEncrypted(bool encrypted) {
519 if (encrypted) {
520 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
521 } else {
522 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
523 }
524 }
525
Kenny Root17208e02013-09-04 13:56:03 -0700526 bool isFallback() const {
527 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
528 }
529
530 void setFallback(bool fallback) {
531 if (fallback) {
532 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
533 } else {
534 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
535 }
536 }
537
Kenny Root822c3a92012-03-23 16:34:39 -0700538 void setVersion(uint8_t version) {
539 mBlob.version = version;
540 }
541
542 BlobType getType() const {
543 return BlobType(mBlob.type);
544 }
545
546 void setType(BlobType type) {
547 mBlob.type = uint8_t(type);
548 }
549
Kenny Rootf9119d62013-04-03 09:22:15 -0700550 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
551 ALOGV("writing blob %s", filename);
552 if (isEncrypted()) {
553 if (state != STATE_NO_ERROR) {
554 ALOGD("couldn't insert encrypted blob while not unlocked");
555 return LOCKED;
556 }
557
558 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
559 ALOGW("Could not read random data for: %s", filename);
560 return SYSTEM_ERROR;
561 }
Kenny Roota91203b2012-02-15 15:00:46 -0800562 }
563
564 // data includes the value and the value's length
565 size_t dataLength = mBlob.length + sizeof(mBlob.length);
566 // pad data to the AES_BLOCK_SIZE
567 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
568 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
569 // encrypted data includes the digest value
570 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
571 // move info after space for padding
572 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
573 // zero padding area
574 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
575
576 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800577
Kenny Rootf9119d62013-04-03 09:22:15 -0700578 if (isEncrypted()) {
579 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800580
Kenny Rootf9119d62013-04-03 09:22:15 -0700581 uint8_t vector[AES_BLOCK_SIZE];
582 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
583 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
584 aes_key, vector, AES_ENCRYPT);
585 }
586
Kenny Roota91203b2012-02-15 15:00:46 -0800587 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
588 size_t fileLength = encryptedLength + headerLength + mBlob.info;
589
590 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800591 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
592 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
593 if (out < 0) {
594 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800595 return SYSTEM_ERROR;
596 }
597 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
598 if (close(out) != 0) {
599 return SYSTEM_ERROR;
600 }
601 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800602 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800603 unlink(tmpFileName);
604 return SYSTEM_ERROR;
605 }
Kenny Root150ca932012-11-14 14:29:02 -0800606 if (rename(tmpFileName, filename) == -1) {
607 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
608 return SYSTEM_ERROR;
609 }
610 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800611 }
612
Kenny Rootf9119d62013-04-03 09:22:15 -0700613 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
614 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800615 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
616 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800617 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
618 }
619 // fileLength may be less than sizeof(mBlob) since the in
620 // memory version has extra padding to tolerate rounding up to
621 // the AES_BLOCK_SIZE
622 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
623 if (close(in) != 0) {
624 return SYSTEM_ERROR;
625 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700626
627 if (isEncrypted() && (state != STATE_NO_ERROR)) {
628 return LOCKED;
629 }
630
Kenny Roota91203b2012-02-15 15:00:46 -0800631 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
632 if (fileLength < headerLength) {
633 return VALUE_CORRUPTED;
634 }
635
636 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700637 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800638 return VALUE_CORRUPTED;
639 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700640
641 ssize_t digestedLength;
642 if (isEncrypted()) {
643 if (encryptedLength % AES_BLOCK_SIZE != 0) {
644 return VALUE_CORRUPTED;
645 }
646
647 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
648 mBlob.vector, AES_DECRYPT);
649 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
650 uint8_t computedDigest[MD5_DIGEST_LENGTH];
651 MD5(mBlob.digested, digestedLength, computedDigest);
652 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
653 return VALUE_CORRUPTED;
654 }
655 } else {
656 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800657 }
658
659 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
660 mBlob.length = ntohl(mBlob.length);
661 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
662 return VALUE_CORRUPTED;
663 }
664 if (mBlob.info != 0) {
665 // move info from after padding to after data
666 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
667 }
Kenny Root07438c82012-11-02 15:41:02 -0700668 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800669 }
670
671private:
672 struct blob mBlob;
673};
674
Kenny Root655b9582013-04-04 08:37:42 -0700675class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800676public:
Kenny Root655b9582013-04-04 08:37:42 -0700677 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
678 asprintf(&mUserDir, "user_%u", mUserId);
679 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
680 }
681
682 ~UserState() {
683 free(mUserDir);
684 free(mMasterKeyFile);
685 }
686
687 bool initialize() {
688 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
689 ALOGE("Could not create directory '%s'", mUserDir);
690 return false;
691 }
692
693 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800694 setState(STATE_LOCKED);
695 } else {
696 setState(STATE_UNINITIALIZED);
697 }
Kenny Root70e3a862012-02-15 17:20:23 -0800698
Kenny Root655b9582013-04-04 08:37:42 -0700699 return true;
700 }
701
702 uid_t getUserId() const {
703 return mUserId;
704 }
705
706 const char* getUserDirName() const {
707 return mUserDir;
708 }
709
710 const char* getMasterKeyFileName() const {
711 return mMasterKeyFile;
712 }
713
714 void setState(State state) {
715 mState = state;
716 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
717 mRetry = MAX_RETRY;
718 }
Kenny Roota91203b2012-02-15 15:00:46 -0800719 }
720
Kenny Root51878182012-03-13 12:53:19 -0700721 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800722 return mState;
723 }
724
Kenny Root51878182012-03-13 12:53:19 -0700725 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800726 return mRetry;
727 }
728
Kenny Root655b9582013-04-04 08:37:42 -0700729 void zeroizeMasterKeysInMemory() {
730 memset(mMasterKey, 0, sizeof(mMasterKey));
731 memset(mSalt, 0, sizeof(mSalt));
732 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
733 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800734 }
735
Kenny Root655b9582013-04-04 08:37:42 -0700736 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
737 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800738 return SYSTEM_ERROR;
739 }
Kenny Root655b9582013-04-04 08:37:42 -0700740 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800741 if (response != NO_ERROR) {
742 return response;
743 }
744 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700745 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800746 }
747
Kenny Root655b9582013-04-04 08:37:42 -0700748 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800749 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
750 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
751 AES_KEY passwordAesKey;
752 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700753 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700754 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800755 }
756
Kenny Root655b9582013-04-04 08:37:42 -0700757 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
758 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800759 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800760 return SYSTEM_ERROR;
761 }
762
763 // we read the raw blob to just to get the salt to generate
764 // the AES key, then we create the Blob to use with decryptBlob
765 blob rawBlob;
766 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
767 if (close(in) != 0) {
768 return SYSTEM_ERROR;
769 }
770 // find salt at EOF if present, otherwise we have an old file
771 uint8_t* salt;
772 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
773 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
774 } else {
775 salt = NULL;
776 }
777 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
778 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
779 AES_KEY passwordAesKey;
780 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
781 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700782 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
783 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800784 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700785 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800786 }
787 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
788 // if salt was missing, generate one and write a new master key file with the salt.
789 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700790 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800791 return SYSTEM_ERROR;
792 }
Kenny Root655b9582013-04-04 08:37:42 -0700793 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800794 }
795 if (response == NO_ERROR) {
796 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
797 setupMasterKeys();
798 }
799 return response;
800 }
801 if (mRetry <= 0) {
802 reset();
803 return UNINITIALIZED;
804 }
805 --mRetry;
806 switch (mRetry) {
807 case 0: return WRONG_PASSWORD_0;
808 case 1: return WRONG_PASSWORD_1;
809 case 2: return WRONG_PASSWORD_2;
810 case 3: return WRONG_PASSWORD_3;
811 default: return WRONG_PASSWORD_3;
812 }
813 }
814
Kenny Root655b9582013-04-04 08:37:42 -0700815 AES_KEY* getEncryptionKey() {
816 return &mMasterKeyEncryption;
817 }
818
819 AES_KEY* getDecryptionKey() {
820 return &mMasterKeyDecryption;
821 }
822
Kenny Roota91203b2012-02-15 15:00:46 -0800823 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700824 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800825 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700826 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800827 return false;
828 }
Kenny Root655b9582013-04-04 08:37:42 -0700829
830 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800831 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700832 // We only care about files.
833 if (file->d_type != DT_REG) {
834 continue;
835 }
836
837 // Skip anything that starts with a "."
838 if (file->d_name[0] == '.') {
839 continue;
840 }
841
842 // Find the current file's UID.
843 char* end;
844 unsigned long thisUid = strtoul(file->d_name, &end, 10);
845 if (end[0] != '_' || end[1] == 0) {
846 continue;
847 }
848
849 // Skip if this is not our user.
850 if (get_user_id(thisUid) != mUserId) {
851 continue;
852 }
853
854 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800855 }
856 closedir(dir);
857 return true;
858 }
859
Kenny Root655b9582013-04-04 08:37:42 -0700860private:
861 static const int MASTER_KEY_SIZE_BYTES = 16;
862 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
863
864 static const int MAX_RETRY = 4;
865 static const size_t SALT_SIZE = 16;
866
867 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
868 uint8_t* salt) {
869 size_t saltSize;
870 if (salt != NULL) {
871 saltSize = SALT_SIZE;
872 } else {
873 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
874 salt = (uint8_t*) "keystore";
875 // sizeof = 9, not strlen = 8
876 saltSize = sizeof("keystore");
877 }
878
879 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
880 saltSize, 8192, keySize, key);
881 }
882
883 bool generateSalt(Entropy* entropy) {
884 return entropy->generate_random_data(mSalt, sizeof(mSalt));
885 }
886
887 bool generateMasterKey(Entropy* entropy) {
888 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
889 return false;
890 }
891 if (!generateSalt(entropy)) {
892 return false;
893 }
894 return true;
895 }
896
897 void setupMasterKeys() {
898 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
899 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
900 setState(STATE_NO_ERROR);
901 }
902
903 uid_t mUserId;
904
905 char* mUserDir;
906 char* mMasterKeyFile;
907
908 State mState;
909 int8_t mRetry;
910
911 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
912 uint8_t mSalt[SALT_SIZE];
913
914 AES_KEY mMasterKeyEncryption;
915 AES_KEY mMasterKeyDecryption;
916};
917
918typedef struct {
919 uint32_t uid;
920 const uint8_t* filename;
921} grant_t;
922
923class KeyStore {
924public:
925 KeyStore(Entropy* entropy, keymaster_device_t* device)
926 : mEntropy(entropy)
927 , mDevice(device)
928 {
929 memset(&mMetaData, '\0', sizeof(mMetaData));
930 }
931
932 ~KeyStore() {
933 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
934 it != mGrants.end(); it++) {
935 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700936 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800937 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700938
939 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
940 it != mMasterKeys.end(); it++) {
941 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700942 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800943 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700944 }
945
946 keymaster_device_t* getDevice() const {
947 return mDevice;
948 }
949
950 ResponseCode initialize() {
951 readMetaData();
952 if (upgradeKeystore()) {
953 writeMetaData();
954 }
955
956 return ::NO_ERROR;
957 }
958
959 State getState(uid_t uid) {
960 return getUserState(uid)->getState();
961 }
962
963 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
964 UserState* userState = getUserState(uid);
965 return userState->initialize(pw, mEntropy);
966 }
967
968 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
969 uid_t user_id = get_user_id(uid);
970 UserState* userState = getUserState(user_id);
971 return userState->writeMasterKey(pw, mEntropy);
972 }
973
974 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
975 uid_t user_id = get_user_id(uid);
976 UserState* userState = getUserState(user_id);
977 return userState->readMasterKey(pw, mEntropy);
978 }
979
980 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700981 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700982 encode_key(encoded, keyName);
983 return android::String8(encoded);
984 }
985
986 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700987 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700988 encode_key(encoded, keyName);
989 return android::String8::format("%u_%s", uid, encoded);
990 }
991
992 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700993 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700994 encode_key(encoded, keyName);
995 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
996 encoded);
997 }
998
999 bool reset(uid_t uid) {
1000 UserState* userState = getUserState(uid);
1001 userState->zeroizeMasterKeysInMemory();
1002 userState->setState(STATE_UNINITIALIZED);
1003 return userState->reset();
1004 }
1005
1006 bool isEmpty(uid_t uid) const {
1007 const UserState* userState = getUserState(uid);
1008 if (userState == NULL) {
1009 return true;
1010 }
1011
1012 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001013 struct dirent* file;
1014 if (!dir) {
1015 return true;
1016 }
1017 bool result = true;
Kenny Root655b9582013-04-04 08:37:42 -07001018
1019 char filename[NAME_MAX];
1020 int n = snprintf(filename, sizeof(filename), "%u_", uid);
1021
Kenny Roota91203b2012-02-15 15:00:46 -08001022 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001023 // We only care about files.
1024 if (file->d_type != DT_REG) {
1025 continue;
1026 }
1027
1028 // Skip anything that starts with a "."
1029 if (file->d_name[0] == '.') {
1030 continue;
1031 }
1032
1033 if (!strncmp(file->d_name, filename, n)) {
Kenny Roota91203b2012-02-15 15:00:46 -08001034 result = false;
1035 break;
1036 }
1037 }
1038 closedir(dir);
1039 return result;
1040 }
1041
Kenny Root655b9582013-04-04 08:37:42 -07001042 void lock(uid_t uid) {
1043 UserState* userState = getUserState(uid);
1044 userState->zeroizeMasterKeysInMemory();
1045 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001046 }
1047
Kenny Root655b9582013-04-04 08:37:42 -07001048 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1049 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001050 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1051 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001052 if (rc != NO_ERROR) {
1053 return rc;
1054 }
1055
1056 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001057 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001058 /* If we upgrade the key, we need to write it to disk again. Then
1059 * it must be read it again since the blob is encrypted each time
1060 * it's written.
1061 */
Kenny Root655b9582013-04-04 08:37:42 -07001062 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1063 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001064 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1065 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001066 return rc;
1067 }
1068 }
Kenny Root822c3a92012-03-23 16:34:39 -07001069 }
1070
Kenny Root17208e02013-09-04 13:56:03 -07001071 /*
1072 * This will upgrade software-backed keys to hardware-backed keys when
1073 * the HAL for the device supports the newer key types.
1074 */
1075 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1076 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1077 && keyBlob->isFallback()) {
1078 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1079 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1080
1081 // The HAL allowed the import, reget the key to have the "fresh"
1082 // version.
1083 if (imported == NO_ERROR) {
1084 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1085 }
1086 }
1087
Kenny Rootd53bc922013-03-21 14:10:15 -07001088 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001089 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1090 return KEY_NOT_FOUND;
1091 }
1092
1093 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001094 }
1095
Kenny Root655b9582013-04-04 08:37:42 -07001096 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1097 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001098 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1099 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001100 }
1101
Kenny Root07438c82012-11-02 15:41:02 -07001102 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001103 const grant_t* existing = getGrant(filename, granteeUid);
1104 if (existing == NULL) {
1105 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001106 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001107 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001108 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001109 }
1110 }
1111
Kenny Root07438c82012-11-02 15:41:02 -07001112 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001113 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1114 it != mGrants.end(); it++) {
1115 grant_t* grant = *it;
1116 if (grant->uid == granteeUid
1117 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1118 mGrants.erase(it);
1119 return true;
1120 }
Kenny Root70e3a862012-02-15 17:20:23 -08001121 }
Kenny Root70e3a862012-02-15 17:20:23 -08001122 return false;
1123 }
1124
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001125 bool hasGrant(const char* filename, const uid_t uid) const {
1126 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001127 }
1128
Kenny Rootf9119d62013-04-03 09:22:15 -07001129 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1130 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001131 uint8_t* data;
1132 size_t dataLength;
1133 int rc;
1134
1135 if (mDevice->import_keypair == NULL) {
1136 ALOGE("Keymaster doesn't support import!");
1137 return SYSTEM_ERROR;
1138 }
1139
Kenny Root17208e02013-09-04 13:56:03 -07001140 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001141 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001142 if (rc) {
Kenny Root17208e02013-09-04 13:56:03 -07001143 // If this is an old device HAL, try to fall back to an old version
1144 if (mDevice->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_2) {
1145 rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength);
1146 isFallback = true;
1147 }
1148
1149 if (rc) {
1150 ALOGE("Error while importing keypair: %d", rc);
1151 return SYSTEM_ERROR;
1152 }
Kenny Root822c3a92012-03-23 16:34:39 -07001153 }
1154
1155 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1156 free(data);
1157
Kenny Rootf9119d62013-04-03 09:22:15 -07001158 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001159 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001160
Kenny Root655b9582013-04-04 08:37:42 -07001161 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001162 }
1163
Kenny Root1b0e3932013-09-05 13:06:32 -07001164 bool isHardwareBacked(const android::String16& keyType) const {
1165 if (mDevice == NULL) {
1166 ALOGW("can't get keymaster device");
1167 return false;
1168 }
1169
1170 if (sRSAKeyType == keyType) {
1171 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1172 } else {
1173 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1174 && (mDevice->common.module->module_api_version
1175 >= KEYMASTER_MODULE_API_VERSION_0_2);
1176 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001177 }
1178
Kenny Root655b9582013-04-04 08:37:42 -07001179 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1180 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001181 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001182
1183 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1184 if (responseCode == NO_ERROR) {
1185 return responseCode;
1186 }
1187
1188 // If this is one of the legacy UID->UID mappings, use it.
1189 uid_t euid = get_keystore_euid(uid);
1190 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001191 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001192 responseCode = get(filepath8.string(), keyBlob, type, uid);
1193 if (responseCode == NO_ERROR) {
1194 return responseCode;
1195 }
1196 }
1197
1198 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001199 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001200 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001201 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001202 if (end[0] != '_' || end[1] == 0) {
1203 return KEY_NOT_FOUND;
1204 }
Kenny Root86b16e82013-09-09 11:15:54 -07001205 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1206 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001207 if (!hasGrant(filepath8.string(), uid)) {
1208 return responseCode;
1209 }
1210
1211 // It is a granted key. Try to load it.
1212 return get(filepath8.string(), keyBlob, type, uid);
1213 }
1214
1215 /**
1216 * Returns any existing UserState or creates it if it doesn't exist.
1217 */
1218 UserState* getUserState(uid_t uid) {
1219 uid_t userId = get_user_id(uid);
1220
1221 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1222 it != mMasterKeys.end(); it++) {
1223 UserState* state = *it;
1224 if (state->getUserId() == userId) {
1225 return state;
1226 }
1227 }
1228
1229 UserState* userState = new UserState(userId);
1230 if (!userState->initialize()) {
1231 /* There's not much we can do if initialization fails. Trying to
1232 * unlock the keystore for that user will fail as well, so any
1233 * subsequent request for this user will just return SYSTEM_ERROR.
1234 */
1235 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1236 }
1237 mMasterKeys.add(userState);
1238 return userState;
1239 }
1240
1241 /**
1242 * Returns NULL if the UserState doesn't already exist.
1243 */
1244 const UserState* getUserState(uid_t uid) const {
1245 uid_t userId = get_user_id(uid);
1246
1247 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1248 it != mMasterKeys.end(); it++) {
1249 UserState* state = *it;
1250 if (state->getUserId() == userId) {
1251 return state;
1252 }
1253 }
1254
1255 return NULL;
1256 }
1257
Kenny Roota91203b2012-02-15 15:00:46 -08001258private:
Kenny Root655b9582013-04-04 08:37:42 -07001259 static const char* sOldMasterKey;
1260 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001261 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001262 Entropy* mEntropy;
1263
Kenny Root70e3a862012-02-15 17:20:23 -08001264 keymaster_device_t* mDevice;
1265
Kenny Root655b9582013-04-04 08:37:42 -07001266 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001267
Kenny Root655b9582013-04-04 08:37:42 -07001268 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001269
Kenny Root655b9582013-04-04 08:37:42 -07001270 typedef struct {
1271 uint32_t version;
1272 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001273
Kenny Root655b9582013-04-04 08:37:42 -07001274 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001275
Kenny Root655b9582013-04-04 08:37:42 -07001276 const grant_t* getGrant(const char* filename, uid_t uid) const {
1277 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1278 it != mGrants.end(); it++) {
1279 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001280 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001281 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001282 return grant;
1283 }
1284 }
Kenny Root70e3a862012-02-15 17:20:23 -08001285 return NULL;
1286 }
1287
Kenny Root822c3a92012-03-23 16:34:39 -07001288 /**
1289 * Upgrade code. This will upgrade the key from the current version
1290 * to whatever is newest.
1291 */
Kenny Root655b9582013-04-04 08:37:42 -07001292 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1293 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001294 bool updated = false;
1295 uint8_t version = oldVersion;
1296
1297 /* From V0 -> V1: All old types were unknown */
1298 if (version == 0) {
1299 ALOGV("upgrading to version 1 and setting type %d", type);
1300
1301 blob->setType(type);
1302 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001303 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001304 }
1305 version = 1;
1306 updated = true;
1307 }
1308
Kenny Rootf9119d62013-04-03 09:22:15 -07001309 /* From V1 -> V2: All old keys were encrypted */
1310 if (version == 1) {
1311 ALOGV("upgrading to version 2");
1312
1313 blob->setEncrypted(true);
1314 version = 2;
1315 updated = true;
1316 }
1317
Kenny Root822c3a92012-03-23 16:34:39 -07001318 /*
1319 * If we've updated, set the key blob to the right version
1320 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001321 */
Kenny Root822c3a92012-03-23 16:34:39 -07001322 if (updated) {
1323 ALOGV("updated and writing file %s", filename);
1324 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001325 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001326
1327 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001328 }
1329
1330 /**
1331 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1332 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1333 * Then it overwrites the original blob with the new blob
1334 * format that is returned from the keymaster.
1335 */
Kenny Root655b9582013-04-04 08:37:42 -07001336 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001337 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1338 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1339 if (b.get() == NULL) {
1340 ALOGE("Problem instantiating BIO");
1341 return SYSTEM_ERROR;
1342 }
1343
1344 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1345 if (pkey.get() == NULL) {
1346 ALOGE("Couldn't read old PEM file");
1347 return SYSTEM_ERROR;
1348 }
1349
1350 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1351 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1352 if (len < 0) {
1353 ALOGE("Couldn't measure PKCS#8 length");
1354 return SYSTEM_ERROR;
1355 }
1356
Kenny Root70c98892013-02-07 09:10:36 -08001357 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1358 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001359 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1360 ALOGE("Couldn't convert to PKCS#8");
1361 return SYSTEM_ERROR;
1362 }
1363
Kenny Rootf9119d62013-04-03 09:22:15 -07001364 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1365 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001366 if (rc != NO_ERROR) {
1367 return rc;
1368 }
1369
Kenny Root655b9582013-04-04 08:37:42 -07001370 return get(filename, blob, TYPE_KEY_PAIR, uid);
1371 }
1372
1373 void readMetaData() {
1374 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1375 if (in < 0) {
1376 return;
1377 }
1378 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1379 if (fileLength != sizeof(mMetaData)) {
1380 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1381 sizeof(mMetaData));
1382 }
1383 close(in);
1384 }
1385
1386 void writeMetaData() {
1387 const char* tmpFileName = ".metadata.tmp";
1388 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1389 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1390 if (out < 0) {
1391 ALOGE("couldn't write metadata file: %s", strerror(errno));
1392 return;
1393 }
1394 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1395 if (fileLength != sizeof(mMetaData)) {
1396 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1397 sizeof(mMetaData));
1398 }
1399 close(out);
1400 rename(tmpFileName, sMetaDataFile);
1401 }
1402
1403 bool upgradeKeystore() {
1404 bool upgraded = false;
1405
1406 if (mMetaData.version == 0) {
1407 UserState* userState = getUserState(0);
1408
1409 // Initialize first so the directory is made.
1410 userState->initialize();
1411
1412 // Migrate the old .masterkey file to user 0.
1413 if (access(sOldMasterKey, R_OK) == 0) {
1414 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1415 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1416 return false;
1417 }
1418 }
1419
1420 // Initialize again in case we had a key.
1421 userState->initialize();
1422
1423 // Try to migrate existing keys.
1424 DIR* dir = opendir(".");
1425 if (!dir) {
1426 // Give up now; maybe we can upgrade later.
1427 ALOGE("couldn't open keystore's directory; something is wrong");
1428 return false;
1429 }
1430
1431 struct dirent* file;
1432 while ((file = readdir(dir)) != NULL) {
1433 // We only care about files.
1434 if (file->d_type != DT_REG) {
1435 continue;
1436 }
1437
1438 // Skip anything that starts with a "."
1439 if (file->d_name[0] == '.') {
1440 continue;
1441 }
1442
1443 // Find the current file's user.
1444 char* end;
1445 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1446 if (end[0] != '_' || end[1] == 0) {
1447 continue;
1448 }
1449 UserState* otherUser = getUserState(thisUid);
1450 if (otherUser->getUserId() != 0) {
1451 unlinkat(dirfd(dir), file->d_name, 0);
1452 }
1453
1454 // Rename the file into user directory.
1455 DIR* otherdir = opendir(otherUser->getUserDirName());
1456 if (otherdir == NULL) {
1457 ALOGW("couldn't open user directory for rename");
1458 continue;
1459 }
1460 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1461 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1462 }
1463 closedir(otherdir);
1464 }
1465 closedir(dir);
1466
1467 mMetaData.version = 1;
1468 upgraded = true;
1469 }
1470
1471 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001472 }
Kenny Roota91203b2012-02-15 15:00:46 -08001473};
1474
Kenny Root655b9582013-04-04 08:37:42 -07001475const char* KeyStore::sOldMasterKey = ".masterkey";
1476const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001477
Kenny Root1b0e3932013-09-05 13:06:32 -07001478const android::String16 KeyStore::sRSAKeyType("RSA");
1479
Kenny Root07438c82012-11-02 15:41:02 -07001480namespace android {
1481class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1482public:
1483 KeyStoreProxy(KeyStore* keyStore)
1484 : mKeyStore(keyStore)
1485 {
Kenny Roota91203b2012-02-15 15:00:46 -08001486 }
Kenny Roota91203b2012-02-15 15:00:46 -08001487
Kenny Root07438c82012-11-02 15:41:02 -07001488 void binderDied(const wp<IBinder>&) {
1489 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001490 }
Kenny Roota91203b2012-02-15 15:00:46 -08001491
Kenny Root07438c82012-11-02 15:41:02 -07001492 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001493 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07001494 pid_t spid = IPCThreadState::self()->getCallingPid();
1495 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001496 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001497 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001498 }
Kenny Roota91203b2012-02-15 15:00:46 -08001499
Kenny Root655b9582013-04-04 08:37:42 -07001500 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001501 }
1502
Kenny Root07438c82012-11-02 15:41:02 -07001503 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001504 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07001505 pid_t spid = IPCThreadState::self()->getCallingPid();
1506 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001507 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001508 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001509 }
Kenny Root07438c82012-11-02 15:41:02 -07001510
Kenny Root07438c82012-11-02 15:41:02 -07001511 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001512 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001513 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001514 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001515 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001516 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001517 *item = NULL;
1518 *itemLength = 0;
1519 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001520 }
Kenny Roota91203b2012-02-15 15:00:46 -08001521
Kenny Root07438c82012-11-02 15:41:02 -07001522 *item = (uint8_t*) malloc(keyBlob.getLength());
1523 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1524 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001525
Kenny Root07438c82012-11-02 15:41:02 -07001526 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001527 }
1528
Kenny Rootf9119d62013-04-03 09:22:15 -07001529 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1530 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001531 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07001532 pid_t spid = IPCThreadState::self()->getCallingPid();
1533 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001534 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001535 return ::PERMISSION_DENIED;
1536 }
Kenny Root07438c82012-11-02 15:41:02 -07001537
Kenny Rootf9119d62013-04-03 09:22:15 -07001538 State state = mKeyStore->getState(callingUid);
1539 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1540 ALOGD("calling get in state: %d", state);
1541 return state;
1542 }
1543
Kenny Root49468902013-03-19 13:41:33 -07001544 if (targetUid == -1) {
1545 targetUid = callingUid;
1546 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001547 return ::PERMISSION_DENIED;
1548 }
1549
Kenny Root07438c82012-11-02 15:41:02 -07001550 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001551 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001552
1553 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001554 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1555
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001556 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001557 }
1558
Kenny Root49468902013-03-19 13:41:33 -07001559 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001560 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07001561 pid_t spid = IPCThreadState::self()->getCallingPid();
1562 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001563 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001564 return ::PERMISSION_DENIED;
1565 }
Kenny Root70e3a862012-02-15 17:20:23 -08001566
Kenny Root49468902013-03-19 13:41:33 -07001567 if (targetUid == -1) {
1568 targetUid = callingUid;
1569 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001570 return ::PERMISSION_DENIED;
1571 }
1572
Kenny Root07438c82012-11-02 15:41:02 -07001573 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001574 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001575
1576 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001577 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001578 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07001579 if (responseCode != ::NO_ERROR) {
1580 return responseCode;
1581 }
1582 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001583 }
1584
Kenny Root49468902013-03-19 13:41:33 -07001585 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001586 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07001587 pid_t spid = IPCThreadState::self()->getCallingPid();
1588 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001589 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001590 return ::PERMISSION_DENIED;
1591 }
Kenny Root70e3a862012-02-15 17:20:23 -08001592
Kenny Root49468902013-03-19 13:41:33 -07001593 if (targetUid == -1) {
1594 targetUid = callingUid;
1595 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001596 return ::PERMISSION_DENIED;
1597 }
1598
Kenny Root07438c82012-11-02 15:41:02 -07001599 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001600 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001601
Kenny Root655b9582013-04-04 08:37:42 -07001602 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001603 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1604 }
1605 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001606 }
1607
Kenny Root49468902013-03-19 13:41:33 -07001608 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001609 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07001610 pid_t spid = IPCThreadState::self()->getCallingPid();
1611 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001612 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001613 return ::PERMISSION_DENIED;
1614 }
Kenny Root70e3a862012-02-15 17:20:23 -08001615
Kenny Root49468902013-03-19 13:41:33 -07001616 if (targetUid == -1) {
1617 targetUid = callingUid;
1618 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001619 return ::PERMISSION_DENIED;
1620 }
1621
Kenny Root655b9582013-04-04 08:37:42 -07001622 UserState* userState = mKeyStore->getUserState(targetUid);
1623 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001624 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07001625 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001626 return ::SYSTEM_ERROR;
1627 }
Kenny Root70e3a862012-02-15 17:20:23 -08001628
Kenny Root07438c82012-11-02 15:41:02 -07001629 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001630 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1631 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001632
Kenny Root07438c82012-11-02 15:41:02 -07001633 struct dirent* file;
1634 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001635 // We only care about files.
1636 if (file->d_type != DT_REG) {
1637 continue;
1638 }
1639
1640 // Skip anything that starts with a "."
1641 if (file->d_name[0] == '.') {
1642 continue;
1643 }
1644
1645 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001646 const char* p = &file->d_name[n];
1647 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001648
Kenny Root07438c82012-11-02 15:41:02 -07001649 size_t extra = decode_key_length(p, plen);
1650 char *match = (char*) malloc(extra + 1);
1651 if (match != NULL) {
1652 decode_key(match, p, plen);
1653 matches->push(String16(match, extra));
1654 free(match);
1655 } else {
1656 ALOGW("could not allocate match of size %zd", extra);
1657 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001658 }
1659 }
Kenny Root07438c82012-11-02 15:41:02 -07001660 closedir(dir);
1661
1662 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001663 }
1664
Kenny Root07438c82012-11-02 15:41:02 -07001665 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001666 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07001667 pid_t spid = IPCThreadState::self()->getCallingPid();
1668 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001669 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001670 return ::PERMISSION_DENIED;
1671 }
1672
Kenny Root655b9582013-04-04 08:37:42 -07001673 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001674
1675 const keymaster_device_t* device = mKeyStore->getDevice();
1676 if (device == NULL) {
1677 ALOGE("No keymaster device!");
1678 return ::SYSTEM_ERROR;
1679 }
1680
1681 if (device->delete_all == NULL) {
1682 ALOGV("keymaster device doesn't implement delete_all");
1683 return rc;
1684 }
1685
1686 if (device->delete_all(device)) {
1687 ALOGE("Problem calling keymaster's delete_all");
1688 return ::SYSTEM_ERROR;
1689 }
1690
Kenny Root9a53d3e2012-08-14 10:47:54 -07001691 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001692 }
1693
Kenny Root07438c82012-11-02 15:41:02 -07001694 /*
1695 * Here is the history. To improve the security, the parameters to generate the
1696 * master key has been changed. To make a seamless transition, we update the
1697 * file using the same password when the user unlock it for the first time. If
1698 * any thing goes wrong during the transition, the new file will not overwrite
1699 * the old one. This avoids permanent damages of the existing data.
1700 */
1701 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001702 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07001703 pid_t spid = IPCThreadState::self()->getCallingPid();
1704 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001705 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001706 return ::PERMISSION_DENIED;
1707 }
Kenny Root70e3a862012-02-15 17:20:23 -08001708
Kenny Root07438c82012-11-02 15:41:02 -07001709 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001710
Kenny Root655b9582013-04-04 08:37:42 -07001711 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001712 case ::STATE_UNINITIALIZED: {
1713 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001714 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001715 }
1716 case ::STATE_NO_ERROR: {
1717 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001718 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001719 }
1720 case ::STATE_LOCKED: {
1721 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001722 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001723 }
1724 }
1725 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001726 }
1727
Kenny Root07438c82012-11-02 15:41:02 -07001728 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001729 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07001730 pid_t spid = IPCThreadState::self()->getCallingPid();
1731 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001732 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001733 return ::PERMISSION_DENIED;
1734 }
Kenny Root70e3a862012-02-15 17:20:23 -08001735
Kenny Root655b9582013-04-04 08:37:42 -07001736 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001737 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001738 ALOGD("calling lock in state: %d", state);
1739 return state;
1740 }
1741
Kenny Root655b9582013-04-04 08:37:42 -07001742 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001743 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001744 }
1745
Kenny Root07438c82012-11-02 15:41:02 -07001746 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001747 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07001748 pid_t spid = IPCThreadState::self()->getCallingPid();
1749 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001750 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001751 return ::PERMISSION_DENIED;
1752 }
1753
Kenny Root655b9582013-04-04 08:37:42 -07001754 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001755 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001756 ALOGD("calling unlock when not locked");
1757 return state;
1758 }
1759
1760 const String8 password8(pw);
1761 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001762 }
1763
Kenny Root07438c82012-11-02 15:41:02 -07001764 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001765 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07001766 pid_t spid = IPCThreadState::self()->getCallingPid();
1767 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001768 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001769 return -1;
1770 }
Kenny Root70e3a862012-02-15 17:20:23 -08001771
Kenny Root655b9582013-04-04 08:37:42 -07001772 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001773 }
1774
Kenny Root96427ba2013-08-16 14:02:41 -07001775 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1776 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001777 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07001778 pid_t spid = IPCThreadState::self()->getCallingPid();
1779 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001780 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001781 return ::PERMISSION_DENIED;
1782 }
Kenny Root70e3a862012-02-15 17:20:23 -08001783
Kenny Root49468902013-03-19 13:41:33 -07001784 if (targetUid == -1) {
1785 targetUid = callingUid;
1786 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001787 return ::PERMISSION_DENIED;
1788 }
1789
Kenny Root655b9582013-04-04 08:37:42 -07001790 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001791 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1792 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001793 return state;
1794 }
Kenny Root70e3a862012-02-15 17:20:23 -08001795
Kenny Root07438c82012-11-02 15:41:02 -07001796 uint8_t* data;
1797 size_t dataLength;
1798 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001799 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001800
1801 const keymaster_device_t* device = mKeyStore->getDevice();
1802 if (device == NULL) {
1803 return ::SYSTEM_ERROR;
1804 }
1805
1806 if (device->generate_keypair == NULL) {
1807 return ::SYSTEM_ERROR;
1808 }
1809
Kenny Root17208e02013-09-04 13:56:03 -07001810 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001811 keymaster_dsa_keygen_params_t dsa_params;
1812 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001813
Kenny Root96427ba2013-08-16 14:02:41 -07001814 if (keySize == -1) {
1815 keySize = DSA_DEFAULT_KEY_SIZE;
1816 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1817 || keySize > DSA_MAX_KEY_SIZE) {
1818 ALOGI("invalid key size %d", keySize);
1819 return ::SYSTEM_ERROR;
1820 }
1821 dsa_params.key_size = keySize;
1822
1823 if (args->size() == 3) {
1824 sp<KeystoreArg> gArg = args->itemAt(0);
1825 sp<KeystoreArg> pArg = args->itemAt(1);
1826 sp<KeystoreArg> qArg = args->itemAt(2);
1827
1828 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1829 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1830 dsa_params.generator_len = gArg->size();
1831
1832 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1833 dsa_params.prime_p_len = pArg->size();
1834
1835 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1836 dsa_params.prime_q_len = qArg->size();
1837 } else {
1838 ALOGI("not all DSA parameters were read");
1839 return ::SYSTEM_ERROR;
1840 }
1841 } else if (args->size() != 0) {
1842 ALOGI("DSA args must be 3");
1843 return ::SYSTEM_ERROR;
1844 }
1845
Kenny Root1d448c02013-11-21 10:36:53 -08001846 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001847 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1848 } else {
1849 isFallback = true;
1850 rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1851 }
1852 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001853 keymaster_ec_keygen_params_t ec_params;
1854 memset(&ec_params, '\0', sizeof(ec_params));
1855
1856 if (keySize == -1) {
1857 keySize = EC_DEFAULT_KEY_SIZE;
1858 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1859 ALOGI("invalid key size %d", keySize);
1860 return ::SYSTEM_ERROR;
1861 }
1862 ec_params.field_size = keySize;
1863
Kenny Root1d448c02013-11-21 10:36:53 -08001864 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001865 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1866 } else {
1867 isFallback = true;
1868 rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1869 }
Kenny Root96427ba2013-08-16 14:02:41 -07001870 } else if (keyType == EVP_PKEY_RSA) {
1871 keymaster_rsa_keygen_params_t rsa_params;
1872 memset(&rsa_params, '\0', sizeof(rsa_params));
1873 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1874
1875 if (keySize == -1) {
1876 keySize = RSA_DEFAULT_KEY_SIZE;
1877 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1878 ALOGI("invalid key size %d", keySize);
1879 return ::SYSTEM_ERROR;
1880 }
1881 rsa_params.modulus_size = keySize;
1882
1883 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001884 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001885 return ::SYSTEM_ERROR;
1886 } else if (args->size() == 1) {
1887 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1888 if (pubExpBlob != NULL) {
1889 Unique_BIGNUM pubExpBn(
1890 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1891 pubExpBlob->size(), NULL));
1892 if (pubExpBn.get() == NULL) {
1893 ALOGI("Could not convert public exponent to BN");
1894 return ::SYSTEM_ERROR;
1895 }
1896 unsigned long pubExp = BN_get_word(pubExpBn.get());
1897 if (pubExp == 0xFFFFFFFFL) {
1898 ALOGI("cannot represent public exponent as a long value");
1899 return ::SYSTEM_ERROR;
1900 }
1901 rsa_params.public_exponent = pubExp;
1902 }
1903 }
1904
1905 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1906 } else {
1907 ALOGW("Unsupported key type %d", keyType);
1908 rc = -1;
1909 }
1910
Kenny Root07438c82012-11-02 15:41:02 -07001911 if (rc) {
1912 return ::SYSTEM_ERROR;
1913 }
1914
Kenny Root655b9582013-04-04 08:37:42 -07001915 String8 name8(name);
1916 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001917
1918 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1919 free(data);
1920
Kenny Rootee8068b2013-10-07 09:49:15 -07001921 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001922 keyBlob.setFallback(isFallback);
1923
Kenny Root655b9582013-04-04 08:37:42 -07001924 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001925 }
1926
Kenny Rootf9119d62013-04-03 09:22:15 -07001927 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1928 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001929 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07001930 pid_t spid = IPCThreadState::self()->getCallingPid();
1931 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001932 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001933 return ::PERMISSION_DENIED;
1934 }
Kenny Root07438c82012-11-02 15:41:02 -07001935
Kenny Root49468902013-03-19 13:41:33 -07001936 if (targetUid == -1) {
1937 targetUid = callingUid;
1938 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001939 return ::PERMISSION_DENIED;
1940 }
1941
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001942 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001943 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001944 ALOGD("calling import in state: %d", state);
1945 return state;
1946 }
1947
1948 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001949 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001950
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001951 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001952 }
1953
Kenny Root07438c82012-11-02 15:41:02 -07001954 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1955 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001956 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07001957 pid_t spid = IPCThreadState::self()->getCallingPid();
1958 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001959 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001960 return ::PERMISSION_DENIED;
1961 }
Kenny Root07438c82012-11-02 15:41:02 -07001962
Kenny Root07438c82012-11-02 15:41:02 -07001963 Blob keyBlob;
1964 String8 name8(name);
1965
Kenny Rootd38a0b02013-02-13 12:59:14 -08001966 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001967 int rc;
1968
Kenny Root655b9582013-04-04 08:37:42 -07001969 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001970 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001971 if (responseCode != ::NO_ERROR) {
1972 return responseCode;
1973 }
1974
1975 const keymaster_device_t* device = mKeyStore->getDevice();
1976 if (device == NULL) {
1977 ALOGE("no keymaster device; cannot sign");
1978 return ::SYSTEM_ERROR;
1979 }
1980
1981 if (device->sign_data == NULL) {
1982 ALOGE("device doesn't implement signing");
1983 return ::SYSTEM_ERROR;
1984 }
1985
1986 keymaster_rsa_sign_params_t params;
1987 params.digest_type = DIGEST_NONE;
1988 params.padding_type = PADDING_NONE;
1989
Kenny Root17208e02013-09-04 13:56:03 -07001990 if (keyBlob.isFallback()) {
1991 rc = openssl_sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1992 length, out, outLength);
1993 } else {
1994 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1995 length, out, outLength);
1996 }
Kenny Root07438c82012-11-02 15:41:02 -07001997 if (rc) {
1998 ALOGW("device couldn't sign data");
1999 return ::SYSTEM_ERROR;
2000 }
2001
2002 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002003 }
2004
Kenny Root07438c82012-11-02 15:41:02 -07002005 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2006 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002007 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07002008 pid_t spid = IPCThreadState::self()->getCallingPid();
2009 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002010 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002011 return ::PERMISSION_DENIED;
2012 }
Kenny Root70e3a862012-02-15 17:20:23 -08002013
Kenny Root655b9582013-04-04 08:37:42 -07002014 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002015 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002016 ALOGD("calling verify in state: %d", state);
2017 return state;
2018 }
Kenny Root70e3a862012-02-15 17:20:23 -08002019
Kenny Root07438c82012-11-02 15:41:02 -07002020 Blob keyBlob;
2021 String8 name8(name);
2022 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002023
Kenny Root655b9582013-04-04 08:37:42 -07002024 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002025 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002026 if (responseCode != ::NO_ERROR) {
2027 return responseCode;
2028 }
Kenny Root70e3a862012-02-15 17:20:23 -08002029
Kenny Root07438c82012-11-02 15:41:02 -07002030 const keymaster_device_t* device = mKeyStore->getDevice();
2031 if (device == NULL) {
2032 return ::SYSTEM_ERROR;
2033 }
Kenny Root70e3a862012-02-15 17:20:23 -08002034
Kenny Root07438c82012-11-02 15:41:02 -07002035 if (device->verify_data == NULL) {
2036 return ::SYSTEM_ERROR;
2037 }
Kenny Root70e3a862012-02-15 17:20:23 -08002038
Kenny Root07438c82012-11-02 15:41:02 -07002039 keymaster_rsa_sign_params_t params;
2040 params.digest_type = DIGEST_NONE;
2041 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002042
Kenny Root17208e02013-09-04 13:56:03 -07002043 if (keyBlob.isFallback()) {
2044 rc = openssl_verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2045 dataLength, signature, signatureLength);
2046 } else {
2047 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2048 dataLength, signature, signatureLength);
2049 }
Kenny Root07438c82012-11-02 15:41:02 -07002050 if (rc) {
2051 return ::SYSTEM_ERROR;
2052 } else {
2053 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002054 }
2055 }
Kenny Root07438c82012-11-02 15:41:02 -07002056
2057 /*
2058 * TODO: The abstraction between things stored in hardware and regular blobs
2059 * of data stored on the filesystem should be moved down to keystore itself.
2060 * Unfortunately the Java code that calls this has naming conventions that it
2061 * knows about. Ideally keystore shouldn't be used to store random blobs of
2062 * data.
2063 *
2064 * Until that happens, it's necessary to have a separate "get_pubkey" and
2065 * "del_key" since the Java code doesn't really communicate what it's
2066 * intentions are.
2067 */
2068 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002069 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07002070 pid_t spid = IPCThreadState::self()->getCallingPid();
2071 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002072 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002073 return ::PERMISSION_DENIED;
2074 }
Kenny Root07438c82012-11-02 15:41:02 -07002075
Kenny Root07438c82012-11-02 15:41:02 -07002076 Blob keyBlob;
2077 String8 name8(name);
2078
Kenny Rootd38a0b02013-02-13 12:59:14 -08002079 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002080
Kenny Root655b9582013-04-04 08:37:42 -07002081 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002082 TYPE_KEY_PAIR);
2083 if (responseCode != ::NO_ERROR) {
2084 return responseCode;
2085 }
2086
2087 const keymaster_device_t* device = mKeyStore->getDevice();
2088 if (device == NULL) {
2089 return ::SYSTEM_ERROR;
2090 }
2091
2092 if (device->get_keypair_public == NULL) {
2093 ALOGE("device has no get_keypair_public implementation!");
2094 return ::SYSTEM_ERROR;
2095 }
2096
Kenny Root17208e02013-09-04 13:56:03 -07002097 int rc;
2098 if (keyBlob.isFallback()) {
2099 rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2100 pubkeyLength);
2101 } else {
2102 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2103 pubkeyLength);
2104 }
Kenny Root07438c82012-11-02 15:41:02 -07002105 if (rc) {
2106 return ::SYSTEM_ERROR;
2107 }
2108
2109 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002110 }
Kenny Root07438c82012-11-02 15:41:02 -07002111
Kenny Root49468902013-03-19 13:41:33 -07002112 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002113 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07002114 pid_t spid = IPCThreadState::self()->getCallingPid();
2115 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002116 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002117 return ::PERMISSION_DENIED;
2118 }
Kenny Root07438c82012-11-02 15:41:02 -07002119
Kenny Root49468902013-03-19 13:41:33 -07002120 if (targetUid == -1) {
2121 targetUid = callingUid;
2122 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002123 return ::PERMISSION_DENIED;
2124 }
2125
Kenny Root07438c82012-11-02 15:41:02 -07002126 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002127 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002128
2129 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002130 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002131 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002132 if (responseCode != ::NO_ERROR) {
2133 return responseCode;
2134 }
2135
2136 ResponseCode rc = ::NO_ERROR;
2137
2138 const keymaster_device_t* device = mKeyStore->getDevice();
2139 if (device == NULL) {
2140 rc = ::SYSTEM_ERROR;
2141 } else {
2142 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002143 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Root07438c82012-11-02 15:41:02 -07002144 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2145 rc = ::SYSTEM_ERROR;
2146 }
2147 }
2148 }
2149
2150 if (rc != ::NO_ERROR) {
2151 return rc;
2152 }
2153
2154 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
2155 }
2156
2157 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002158 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07002159 pid_t spid = IPCThreadState::self()->getCallingPid();
2160 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002161 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002162 return ::PERMISSION_DENIED;
2163 }
Kenny Root07438c82012-11-02 15:41:02 -07002164
Kenny Root655b9582013-04-04 08:37:42 -07002165 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002166 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002167 ALOGD("calling grant in state: %d", state);
2168 return state;
2169 }
2170
2171 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002172 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002173
Kenny Root655b9582013-04-04 08:37:42 -07002174 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002175 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2176 }
2177
Kenny Root655b9582013-04-04 08:37:42 -07002178 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002179 return ::NO_ERROR;
2180 }
2181
2182 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002183 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07002184 pid_t spid = IPCThreadState::self()->getCallingPid();
2185 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002186 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002187 return ::PERMISSION_DENIED;
2188 }
Kenny Root07438c82012-11-02 15:41:02 -07002189
Kenny Root655b9582013-04-04 08:37:42 -07002190 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002191 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002192 ALOGD("calling ungrant in state: %d", state);
2193 return state;
2194 }
2195
2196 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002197 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002198
Kenny Root655b9582013-04-04 08:37:42 -07002199 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002200 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2201 }
2202
Kenny Root655b9582013-04-04 08:37:42 -07002203 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002204 }
2205
2206 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002207 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07002208 pid_t spid = IPCThreadState::self()->getCallingPid();
2209 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002210 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002211 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002212 }
Kenny Root07438c82012-11-02 15:41:02 -07002213
2214 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002215 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002216
Kenny Root655b9582013-04-04 08:37:42 -07002217 if (access(filename.string(), R_OK) == -1) {
2218 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002219 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002220 }
2221
Kenny Root655b9582013-04-04 08:37:42 -07002222 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002223 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002224 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002225 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002226 }
2227
2228 struct stat s;
2229 int ret = fstat(fd, &s);
2230 close(fd);
2231 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002232 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002233 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002234 }
2235
Kenny Root36a9e232013-02-04 14:24:15 -08002236 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002237 }
2238
Kenny Rootd53bc922013-03-21 14:10:15 -07002239 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2240 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002241 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07002242 pid_t spid = IPCThreadState::self()->getCallingPid();
2243 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002244 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002245 return -1L;
2246 }
2247
Kenny Root655b9582013-04-04 08:37:42 -07002248 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002249 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002250 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002251 return state;
2252 }
2253
Kenny Rootd53bc922013-03-21 14:10:15 -07002254 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2255 srcUid = callingUid;
2256 } else if (!is_granted_to(callingUid, srcUid)) {
2257 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002258 return ::PERMISSION_DENIED;
2259 }
2260
Kenny Rootd53bc922013-03-21 14:10:15 -07002261 if (destUid == -1) {
2262 destUid = callingUid;
2263 }
2264
2265 if (srcUid != destUid) {
2266 if (static_cast<uid_t>(srcUid) != callingUid) {
2267 ALOGD("can only duplicate from caller to other or to same uid: "
2268 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2269 return ::PERMISSION_DENIED;
2270 }
2271
2272 if (!is_granted_to(callingUid, destUid)) {
2273 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2274 return ::PERMISSION_DENIED;
2275 }
2276 }
2277
2278 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002279 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002280
Kenny Rootd53bc922013-03-21 14:10:15 -07002281 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002282 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002283
Kenny Root655b9582013-04-04 08:37:42 -07002284 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2285 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002286 return ::SYSTEM_ERROR;
2287 }
2288
Kenny Rootd53bc922013-03-21 14:10:15 -07002289 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002290 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002291 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002292 if (responseCode != ::NO_ERROR) {
2293 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002294 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002295
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002296 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002297 }
2298
Kenny Root1b0e3932013-09-05 13:06:32 -07002299 int32_t is_hardware_backed(const String16& keyType) {
2300 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002301 }
2302
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002303 int32_t clear_uid(int64_t targetUid64) {
2304 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002305 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahn0e542d02014-06-19 08:27:07 -07002306 pid_t spid = IPCThreadState::self()->getCallingPid();
2307 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002308 ALOGW("permission denied for %d: clear_uid", callingUid);
2309 return ::PERMISSION_DENIED;
2310 }
2311
Kenny Root655b9582013-04-04 08:37:42 -07002312 State state = mKeyStore->getState(callingUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002313 if (!isKeystoreUnlocked(state)) {
2314 ALOGD("calling clear_uid in state: %d", state);
2315 return state;
2316 }
2317
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002318 if (targetUid64 == -1) {
2319 targetUid = callingUid;
2320 } else if (!is_granted_to(callingUid, targetUid)) {
2321 return ::PERMISSION_DENIED;
2322 }
2323
Kenny Roota9bb5492013-04-01 16:29:11 -07002324 const keymaster_device_t* device = mKeyStore->getDevice();
2325 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002326 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002327 return ::SYSTEM_ERROR;
2328 }
2329
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002330 UserState* userState = mKeyStore->getUserState(targetUid);
Kenny Root655b9582013-04-04 08:37:42 -07002331 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota9bb5492013-04-01 16:29:11 -07002332 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07002333 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Roota9bb5492013-04-01 16:29:11 -07002334 return ::SYSTEM_ERROR;
2335 }
2336
Kenny Root655b9582013-04-04 08:37:42 -07002337 char prefix[NAME_MAX];
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002338 int n = snprintf(prefix, NAME_MAX, "%u_", targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002339
2340 ResponseCode rc = ::NO_ERROR;
2341
2342 struct dirent* file;
2343 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002344 // We only care about files.
2345 if (file->d_type != DT_REG) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002346 continue;
2347 }
2348
Kenny Root655b9582013-04-04 08:37:42 -07002349 // Skip anything that starts with a "."
2350 if (file->d_name[0] == '.') {
2351 continue;
2352 }
Kenny Roota9bb5492013-04-01 16:29:11 -07002353
Kenny Root655b9582013-04-04 08:37:42 -07002354 if (strncmp(prefix, file->d_name, n)) {
2355 continue;
2356 }
2357
2358 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Roota9bb5492013-04-01 16:29:11 -07002359 Blob keyBlob;
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002360 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, targetUid)
Kenny Root655b9582013-04-04 08:37:42 -07002361 != ::NO_ERROR) {
2362 ALOGW("couldn't open %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002363 continue;
2364 }
2365
2366 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2367 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002368 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002369 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2370 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002371 ALOGW("device couldn't remove %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002372 }
2373 }
2374 }
2375
Kenny Root5f531242013-04-12 11:31:50 -07002376 if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002377 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002378 ALOGW("couldn't unlink %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002379 }
2380 }
2381 closedir(dir);
2382
2383 return rc;
2384 }
2385
Kenny Root07438c82012-11-02 15:41:02 -07002386private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002387 inline bool isKeystoreUnlocked(State state) {
2388 switch (state) {
2389 case ::STATE_NO_ERROR:
2390 return true;
2391 case ::STATE_UNINITIALIZED:
2392 case ::STATE_LOCKED:
2393 return false;
2394 }
2395 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002396 }
2397
Kenny Root1d448c02013-11-21 10:36:53 -08002398 bool isKeyTypeSupported(const keymaster_device_t* device, keymaster_keypair_t keyType) {
2399 const int32_t device_api = device->common.module->module_api_version;
2400 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2401 switch (keyType) {
2402 case TYPE_RSA:
2403 case TYPE_DSA:
2404 case TYPE_EC:
2405 return true;
2406 default:
2407 return false;
2408 }
2409 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2410 switch (keyType) {
2411 case TYPE_RSA:
2412 return true;
2413 case TYPE_DSA:
2414 return device->flags & KEYMASTER_SUPPORTS_DSA;
2415 case TYPE_EC:
2416 return device->flags & KEYMASTER_SUPPORTS_EC;
2417 default:
2418 return false;
2419 }
2420 } else {
2421 return keyType == TYPE_RSA;
2422 }
2423 }
2424
Kenny Root07438c82012-11-02 15:41:02 -07002425 ::KeyStore* mKeyStore;
2426};
2427
2428}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002429
2430int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002431 if (argc < 2) {
2432 ALOGE("A directory must be specified!");
2433 return 1;
2434 }
2435 if (chdir(argv[1]) == -1) {
2436 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2437 return 1;
2438 }
2439
2440 Entropy entropy;
2441 if (!entropy.open()) {
2442 return 1;
2443 }
Kenny Root70e3a862012-02-15 17:20:23 -08002444
2445 keymaster_device_t* dev;
2446 if (keymaster_device_initialize(&dev)) {
2447 ALOGE("keystore keymaster could not be initialized; exiting");
2448 return 1;
2449 }
2450
Riley Spahn0e542d02014-06-19 08:27:07 -07002451 union selinux_callback cb;
2452 cb.func_log = selinux_log_callback;
2453 selinux_set_callback(SELINUX_CB_LOG, cb);
2454 if (getcon(&tctx) != 0) {
2455 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2456 return -1;
2457 }
2458
Kenny Root70e3a862012-02-15 17:20:23 -08002459 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002460 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002461 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2462 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2463 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2464 if (ret != android::OK) {
2465 ALOGE("Couldn't register binder service!");
2466 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002467 }
Kenny Root07438c82012-11-02 15:41:02 -07002468
2469 /*
2470 * We're the only thread in existence, so we're just going to process
2471 * Binder transaction as a single-threaded program.
2472 */
2473 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002474
2475 keymaster_device_release(dev);
Riley Spahn0e542d02014-06-19 08:27:07 -07002476
Kenny Roota91203b2012-02-15 15:00:46 -08002477 return 1;
2478}