blob: 9ee2598809423aea65cf5ac026475a1c9f529700 [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>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
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 Spahneaabae92014-06-30 12:39:52 -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 {
Robin Lee4e865752014-08-19 17:37:55 +0100140 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,
155 P_CLEAR_UID = 1 << 15,
156 P_RESET_UID = 1 << 16,
157 P_SYNC_UID = 1 << 17,
158 P_PASSWORD_UID = 1 << 18,
Kenny Root07438c82012-11-02 15:41:02 -0700159} perm_t;
160
161static struct user_euid {
162 uid_t uid;
163 uid_t euid;
164} user_euids[] = {
165 {AID_VPN, AID_SYSTEM},
166 {AID_WIFI, AID_SYSTEM},
167 {AID_ROOT, AID_SYSTEM},
168};
169
Riley Spahneaabae92014-06-30 12:39:52 -0700170/* perm_labels associcated with keystore_key SELinux class verbs. */
171const char *perm_labels[] = {
172 "test",
173 "get",
174 "insert",
175 "delete",
176 "exist",
177 "saw",
178 "reset",
179 "password",
180 "lock",
181 "unlock",
182 "zero",
183 "sign",
184 "verify",
185 "grant",
186 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100187 "clear_uid",
188 "reset_uid",
189 "sync_uid",
190 "password_uid",
Riley Spahneaabae92014-06-30 12:39:52 -0700191};
192
Kenny Root07438c82012-11-02 15:41:02 -0700193static struct user_perm {
194 uid_t uid;
195 perm_t perms;
196} user_perms[] = {
197 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
198 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
199 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
200 {AID_ROOT, static_cast<perm_t>(P_GET) },
201};
202
203static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
204 | P_VERIFY);
205
Riley Spahneaabae92014-06-30 12:39:52 -0700206static char *tctx;
207static int ks_is_selinux_enabled;
208
209static const char *get_perm_label(perm_t perm) {
210 unsigned int index = ffs(perm);
211 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
212 return perm_labels[index - 1];
213 } else {
214 ALOGE("Keystore: Failed to retrieve permission label.\n");
215 abort();
216 }
217}
218
Kenny Root655b9582013-04-04 08:37:42 -0700219/**
220 * Returns the app ID (in the Android multi-user sense) for the current
221 * UNIX UID.
222 */
223static uid_t get_app_id(uid_t uid) {
224 return uid % AID_USER;
225}
226
227/**
228 * Returns the user ID (in the Android multi-user sense) for the current
229 * UNIX UID.
230 */
231static uid_t get_user_id(uid_t uid) {
232 return uid / AID_USER;
233}
234
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700235static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700236 if (!ks_is_selinux_enabled) {
237 return true;
238 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000239
Riley Spahneaabae92014-06-30 12:39:52 -0700240 char *sctx = NULL;
241 const char *selinux_class = "keystore_key";
242 const char *str_perm = get_perm_label(perm);
243
244 if (!str_perm) {
245 return false;
246 }
247
248 if (getpidcon(spid, &sctx) != 0) {
249 ALOGE("SELinux: Failed to get source pid context.\n");
250 return false;
251 }
252
253 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
254 NULL) == 0;
255 freecon(sctx);
256 return allowed;
257}
258
259static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700260 // All system users are equivalent for multi-user support.
261 if (get_app_id(uid) == AID_SYSTEM) {
262 uid = AID_SYSTEM;
263 }
264
Kenny Root07438c82012-11-02 15:41:02 -0700265 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
266 struct user_perm user = user_perms[i];
267 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700268 return (user.perms & perm) &&
269 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700270 }
271 }
272
Riley Spahneaabae92014-06-30 12:39:52 -0700273 return (DEFAULT_PERMS & perm) &&
274 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700275}
276
Kenny Root49468902013-03-19 13:41:33 -0700277/**
278 * Returns the UID that the callingUid should act as. This is here for
279 * legacy support of the WiFi and VPN systems and should be removed
280 * when WiFi can operate in its own namespace.
281 */
Kenny Root07438c82012-11-02 15:41:02 -0700282static uid_t get_keystore_euid(uid_t uid) {
283 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
284 struct user_euid user = user_euids[i];
285 if (user.uid == uid) {
286 return user.euid;
287 }
288 }
289
290 return uid;
291}
292
Kenny Root49468902013-03-19 13:41:33 -0700293/**
294 * Returns true if the callingUid is allowed to interact in the targetUid's
295 * namespace.
296 */
297static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
298 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
299 struct user_euid user = user_euids[i];
300 if (user.euid == callingUid && user.uid == targetUid) {
301 return true;
302 }
303 }
304
305 return false;
306}
307
Kenny Root007cb232014-07-30 16:59:42 -0700308/**
309 * Allow the system to perform some privileged tasks that have to do with
310 * system maintenance. This should not be used for any function that uses
311 * the keys in any way (e.g., signing).
312 */
313static bool is_self_or_system(uid_t callingUid, uid_t targetUid) {
314 return callingUid == targetUid || callingUid == AID_SYSTEM;
315}
316
Kenny Roota91203b2012-02-15 15:00:46 -0800317/* Here is the encoding of keys. This is necessary in order to allow arbitrary
318 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
319 * into two bytes. The first byte is one of [+-.] which represents the first
320 * two bits of the character. The second byte encodes the rest of the bits into
321 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
322 * that Base64 cannot be used here due to the need of prefix match on keys. */
323
Kenny Root655b9582013-04-04 08:37:42 -0700324static size_t encode_key_length(const android::String8& keyName) {
325 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
326 size_t length = keyName.length();
327 for (int i = length; i > 0; --i, ++in) {
328 if (*in < '0' || *in > '~') {
329 ++length;
330 }
331 }
332 return length;
333}
334
Kenny Root07438c82012-11-02 15:41:02 -0700335static int encode_key(char* out, const android::String8& keyName) {
336 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
337 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800338 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700339 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800340 *out = '+' + (*in >> 6);
341 *++out = '0' + (*in & 0x3F);
342 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700343 } else {
344 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800345 }
346 }
347 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800348 return length;
349}
350
Kenny Root07438c82012-11-02 15:41:02 -0700351/*
352 * Converts from the "escaped" format on disk to actual name.
353 * This will be smaller than the input string.
354 *
355 * Characters that should combine with the next at the end will be truncated.
356 */
357static size_t decode_key_length(const char* in, size_t length) {
358 size_t outLength = 0;
359
360 for (const char* end = in + length; in < end; in++) {
361 /* This combines with the next character. */
362 if (*in < '0' || *in > '~') {
363 continue;
364 }
365
366 outLength++;
367 }
368 return outLength;
369}
370
371static void decode_key(char* out, const char* in, size_t length) {
372 for (const char* end = in + length; in < end; in++) {
373 if (*in < '0' || *in > '~') {
374 /* Truncate combining characters at the end. */
375 if (in + 1 >= end) {
376 break;
377 }
378
379 *out = (*in++ - '+') << 6;
380 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800381 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700382 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800383 }
384 }
385 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800386}
387
388static size_t readFully(int fd, uint8_t* data, size_t size) {
389 size_t remaining = size;
390 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800391 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800392 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800393 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800394 }
395 data += n;
396 remaining -= n;
397 }
398 return size;
399}
400
401static size_t writeFully(int fd, uint8_t* data, size_t size) {
402 size_t remaining = size;
403 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800404 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
405 if (n < 0) {
406 ALOGW("write failed: %s", strerror(errno));
407 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800408 }
409 data += n;
410 remaining -= n;
411 }
412 return size;
413}
414
415class Entropy {
416public:
417 Entropy() : mRandom(-1) {}
418 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800419 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800420 close(mRandom);
421 }
422 }
423
424 bool open() {
425 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800426 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
427 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800428 ALOGE("open: %s: %s", randomDevice, strerror(errno));
429 return false;
430 }
431 return true;
432 }
433
Kenny Root51878182012-03-13 12:53:19 -0700434 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800435 return (readFully(mRandom, data, size) == size);
436 }
437
438private:
439 int mRandom;
440};
441
442/* Here is the file format. There are two parts in blob.value, the secret and
443 * the description. The secret is stored in ciphertext, and its original size
444 * can be found in blob.length. The description is stored after the secret in
445 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700446 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700447 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800448 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
449 * and decryptBlob(). Thus they should not be accessed from outside. */
450
Kenny Root822c3a92012-03-23 16:34:39 -0700451/* ** Note to future implementors of encryption: **
452 * Currently this is the construction:
453 * metadata || Enc(MD5(data) || data)
454 *
455 * This should be the construction used for encrypting if re-implementing:
456 *
457 * Derive independent keys for encryption and MAC:
458 * Kenc = AES_encrypt(masterKey, "Encrypt")
459 * Kmac = AES_encrypt(masterKey, "MAC")
460 *
461 * Store this:
462 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
463 * HMAC(Kmac, metadata || Enc(data))
464 */
Kenny Roota91203b2012-02-15 15:00:46 -0800465struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700466 uint8_t version;
467 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700468 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800469 uint8_t info;
470 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700471 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800472 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700473 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800474 int32_t length; // in network byte order when encrypted
475 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
476};
477
Kenny Root822c3a92012-03-23 16:34:39 -0700478typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700479 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700480 TYPE_GENERIC = 1,
481 TYPE_MASTER_KEY = 2,
482 TYPE_KEY_PAIR = 3,
483} BlobType;
484
Kenny Rootf9119d62013-04-03 09:22:15 -0700485static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700486
Kenny Roota91203b2012-02-15 15:00:46 -0800487class Blob {
488public:
Kenny Root07438c82012-11-02 15:41:02 -0700489 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
490 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800491 mBlob.length = valueLength;
492 memcpy(mBlob.value, value, valueLength);
493
494 mBlob.info = infoLength;
495 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700496
Kenny Root07438c82012-11-02 15:41:02 -0700497 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700498 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700499
Kenny Rootee8068b2013-10-07 09:49:15 -0700500 if (type == TYPE_MASTER_KEY) {
501 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
502 } else {
503 mBlob.flags = KEYSTORE_FLAG_NONE;
504 }
Kenny Roota91203b2012-02-15 15:00:46 -0800505 }
506
507 Blob(blob b) {
508 mBlob = b;
509 }
510
511 Blob() {}
512
Kenny Root51878182012-03-13 12:53:19 -0700513 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800514 return mBlob.value;
515 }
516
Kenny Root51878182012-03-13 12:53:19 -0700517 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800518 return mBlob.length;
519 }
520
Kenny Root51878182012-03-13 12:53:19 -0700521 const uint8_t* getInfo() const {
522 return mBlob.value + mBlob.length;
523 }
524
525 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800526 return mBlob.info;
527 }
528
Kenny Root822c3a92012-03-23 16:34:39 -0700529 uint8_t getVersion() const {
530 return mBlob.version;
531 }
532
Kenny Rootf9119d62013-04-03 09:22:15 -0700533 bool isEncrypted() const {
534 if (mBlob.version < 2) {
535 return true;
536 }
537
538 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
539 }
540
541 void setEncrypted(bool encrypted) {
542 if (encrypted) {
543 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
544 } else {
545 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
546 }
547 }
548
Kenny Root17208e02013-09-04 13:56:03 -0700549 bool isFallback() const {
550 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
551 }
552
553 void setFallback(bool fallback) {
554 if (fallback) {
555 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
556 } else {
557 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
558 }
559 }
560
Kenny Root822c3a92012-03-23 16:34:39 -0700561 void setVersion(uint8_t version) {
562 mBlob.version = version;
563 }
564
565 BlobType getType() const {
566 return BlobType(mBlob.type);
567 }
568
569 void setType(BlobType type) {
570 mBlob.type = uint8_t(type);
571 }
572
Kenny Rootf9119d62013-04-03 09:22:15 -0700573 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
574 ALOGV("writing blob %s", filename);
575 if (isEncrypted()) {
576 if (state != STATE_NO_ERROR) {
577 ALOGD("couldn't insert encrypted blob while not unlocked");
578 return LOCKED;
579 }
580
581 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
582 ALOGW("Could not read random data for: %s", filename);
583 return SYSTEM_ERROR;
584 }
Kenny Roota91203b2012-02-15 15:00:46 -0800585 }
586
587 // data includes the value and the value's length
588 size_t dataLength = mBlob.length + sizeof(mBlob.length);
589 // pad data to the AES_BLOCK_SIZE
590 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
591 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
592 // encrypted data includes the digest value
593 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
594 // move info after space for padding
595 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
596 // zero padding area
597 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
598
599 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800600
Kenny Rootf9119d62013-04-03 09:22:15 -0700601 if (isEncrypted()) {
602 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800603
Kenny Rootf9119d62013-04-03 09:22:15 -0700604 uint8_t vector[AES_BLOCK_SIZE];
605 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
606 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
607 aes_key, vector, AES_ENCRYPT);
608 }
609
Kenny Roota91203b2012-02-15 15:00:46 -0800610 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
611 size_t fileLength = encryptedLength + headerLength + mBlob.info;
612
613 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800614 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
615 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
616 if (out < 0) {
617 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800618 return SYSTEM_ERROR;
619 }
620 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
621 if (close(out) != 0) {
622 return SYSTEM_ERROR;
623 }
624 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800625 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800626 unlink(tmpFileName);
627 return SYSTEM_ERROR;
628 }
Kenny Root150ca932012-11-14 14:29:02 -0800629 if (rename(tmpFileName, filename) == -1) {
630 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
631 return SYSTEM_ERROR;
632 }
633 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800634 }
635
Kenny Rootf9119d62013-04-03 09:22:15 -0700636 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
637 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800638 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
639 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800640 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
641 }
642 // fileLength may be less than sizeof(mBlob) since the in
643 // memory version has extra padding to tolerate rounding up to
644 // the AES_BLOCK_SIZE
645 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
646 if (close(in) != 0) {
647 return SYSTEM_ERROR;
648 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700649
650 if (isEncrypted() && (state != STATE_NO_ERROR)) {
651 return LOCKED;
652 }
653
Kenny Roota91203b2012-02-15 15:00:46 -0800654 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
655 if (fileLength < headerLength) {
656 return VALUE_CORRUPTED;
657 }
658
659 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700660 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800661 return VALUE_CORRUPTED;
662 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700663
664 ssize_t digestedLength;
665 if (isEncrypted()) {
666 if (encryptedLength % AES_BLOCK_SIZE != 0) {
667 return VALUE_CORRUPTED;
668 }
669
670 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
671 mBlob.vector, AES_DECRYPT);
672 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
673 uint8_t computedDigest[MD5_DIGEST_LENGTH];
674 MD5(mBlob.digested, digestedLength, computedDigest);
675 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
676 return VALUE_CORRUPTED;
677 }
678 } else {
679 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800680 }
681
682 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
683 mBlob.length = ntohl(mBlob.length);
684 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
685 return VALUE_CORRUPTED;
686 }
687 if (mBlob.info != 0) {
688 // move info from after padding to after data
689 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
690 }
Kenny Root07438c82012-11-02 15:41:02 -0700691 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800692 }
693
694private:
695 struct blob mBlob;
696};
697
Kenny Root655b9582013-04-04 08:37:42 -0700698class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800699public:
Kenny Root655b9582013-04-04 08:37:42 -0700700 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
701 asprintf(&mUserDir, "user_%u", mUserId);
702 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
703 }
704
705 ~UserState() {
706 free(mUserDir);
707 free(mMasterKeyFile);
708 }
709
710 bool initialize() {
711 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
712 ALOGE("Could not create directory '%s'", mUserDir);
713 return false;
714 }
715
716 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800717 setState(STATE_LOCKED);
718 } else {
719 setState(STATE_UNINITIALIZED);
720 }
Kenny Root70e3a862012-02-15 17:20:23 -0800721
Kenny Root655b9582013-04-04 08:37:42 -0700722 return true;
723 }
724
725 uid_t getUserId() const {
726 return mUserId;
727 }
728
729 const char* getUserDirName() const {
730 return mUserDir;
731 }
732
733 const char* getMasterKeyFileName() const {
734 return mMasterKeyFile;
735 }
736
737 void setState(State state) {
738 mState = state;
739 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
740 mRetry = MAX_RETRY;
741 }
Kenny Roota91203b2012-02-15 15:00:46 -0800742 }
743
Kenny Root51878182012-03-13 12:53:19 -0700744 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800745 return mState;
746 }
747
Kenny Root51878182012-03-13 12:53:19 -0700748 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800749 return mRetry;
750 }
751
Kenny Root655b9582013-04-04 08:37:42 -0700752 void zeroizeMasterKeysInMemory() {
753 memset(mMasterKey, 0, sizeof(mMasterKey));
754 memset(mSalt, 0, sizeof(mSalt));
755 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
756 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800757 }
758
Kenny Root655b9582013-04-04 08:37:42 -0700759 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
760 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800761 return SYSTEM_ERROR;
762 }
Kenny Root655b9582013-04-04 08:37:42 -0700763 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800764 if (response != NO_ERROR) {
765 return response;
766 }
767 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700768 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800769 }
770
Robin Lee4e865752014-08-19 17:37:55 +0100771 ResponseCode copyMasterKey(UserState* src) {
772 if (mState != STATE_UNINITIALIZED) {
773 return ::SYSTEM_ERROR;
774 }
775 if (src->getState() != STATE_NO_ERROR) {
776 return ::SYSTEM_ERROR;
777 }
778 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
779 setupMasterKeys();
780 return ::NO_ERROR;
781 }
782
Kenny Root655b9582013-04-04 08:37:42 -0700783 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800784 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
785 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
786 AES_KEY passwordAesKey;
787 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700788 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700789 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800790 }
791
Kenny Root655b9582013-04-04 08:37:42 -0700792 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
793 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800794 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800795 return SYSTEM_ERROR;
796 }
797
798 // we read the raw blob to just to get the salt to generate
799 // the AES key, then we create the Blob to use with decryptBlob
800 blob rawBlob;
801 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
802 if (close(in) != 0) {
803 return SYSTEM_ERROR;
804 }
805 // find salt at EOF if present, otherwise we have an old file
806 uint8_t* salt;
807 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
808 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
809 } else {
810 salt = NULL;
811 }
812 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
813 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
814 AES_KEY passwordAesKey;
815 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
816 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700817 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
818 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800819 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700820 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800821 }
822 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
823 // if salt was missing, generate one and write a new master key file with the salt.
824 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700825 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800826 return SYSTEM_ERROR;
827 }
Kenny Root655b9582013-04-04 08:37:42 -0700828 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800829 }
830 if (response == NO_ERROR) {
831 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
832 setupMasterKeys();
833 }
834 return response;
835 }
836 if (mRetry <= 0) {
837 reset();
838 return UNINITIALIZED;
839 }
840 --mRetry;
841 switch (mRetry) {
842 case 0: return WRONG_PASSWORD_0;
843 case 1: return WRONG_PASSWORD_1;
844 case 2: return WRONG_PASSWORD_2;
845 case 3: return WRONG_PASSWORD_3;
846 default: return WRONG_PASSWORD_3;
847 }
848 }
849
Kenny Root655b9582013-04-04 08:37:42 -0700850 AES_KEY* getEncryptionKey() {
851 return &mMasterKeyEncryption;
852 }
853
854 AES_KEY* getDecryptionKey() {
855 return &mMasterKeyDecryption;
856 }
857
Kenny Roota91203b2012-02-15 15:00:46 -0800858 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700859 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800860 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700861 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800862 return false;
863 }
Kenny Root655b9582013-04-04 08:37:42 -0700864
865 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800866 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700867 // We only care about files.
868 if (file->d_type != DT_REG) {
869 continue;
870 }
871
872 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700873 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700874 continue;
875 }
876
877 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800878 }
879 closedir(dir);
880 return true;
881 }
882
Kenny Root655b9582013-04-04 08:37:42 -0700883private:
884 static const int MASTER_KEY_SIZE_BYTES = 16;
885 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
886
887 static const int MAX_RETRY = 4;
888 static const size_t SALT_SIZE = 16;
889
890 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
891 uint8_t* salt) {
892 size_t saltSize;
893 if (salt != NULL) {
894 saltSize = SALT_SIZE;
895 } else {
896 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
897 salt = (uint8_t*) "keystore";
898 // sizeof = 9, not strlen = 8
899 saltSize = sizeof("keystore");
900 }
901
902 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
903 saltSize, 8192, keySize, key);
904 }
905
906 bool generateSalt(Entropy* entropy) {
907 return entropy->generate_random_data(mSalt, sizeof(mSalt));
908 }
909
910 bool generateMasterKey(Entropy* entropy) {
911 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
912 return false;
913 }
914 if (!generateSalt(entropy)) {
915 return false;
916 }
917 return true;
918 }
919
920 void setupMasterKeys() {
921 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
922 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
923 setState(STATE_NO_ERROR);
924 }
925
926 uid_t mUserId;
927
928 char* mUserDir;
929 char* mMasterKeyFile;
930
931 State mState;
932 int8_t mRetry;
933
934 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
935 uint8_t mSalt[SALT_SIZE];
936
937 AES_KEY mMasterKeyEncryption;
938 AES_KEY mMasterKeyDecryption;
939};
940
941typedef struct {
942 uint32_t uid;
943 const uint8_t* filename;
944} grant_t;
945
946class KeyStore {
947public:
948 KeyStore(Entropy* entropy, keymaster_device_t* device)
949 : mEntropy(entropy)
950 , mDevice(device)
951 {
952 memset(&mMetaData, '\0', sizeof(mMetaData));
953 }
954
955 ~KeyStore() {
956 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
957 it != mGrants.end(); it++) {
958 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700959 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800960 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700961
962 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
963 it != mMasterKeys.end(); it++) {
964 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700965 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800966 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700967 }
968
969 keymaster_device_t* getDevice() const {
970 return mDevice;
971 }
972
973 ResponseCode initialize() {
974 readMetaData();
975 if (upgradeKeystore()) {
976 writeMetaData();
977 }
978
979 return ::NO_ERROR;
980 }
981
982 State getState(uid_t uid) {
983 return getUserState(uid)->getState();
984 }
985
986 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
987 UserState* userState = getUserState(uid);
988 return userState->initialize(pw, mEntropy);
989 }
990
Robin Lee4e865752014-08-19 17:37:55 +0100991 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
992 UserState *userState = getUserState(uid);
993 UserState *initState = getUserState(src);
994 return userState->copyMasterKey(initState);
995 }
996
Kenny Root655b9582013-04-04 08:37:42 -0700997 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +0100998 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -0700999 return userState->writeMasterKey(pw, mEntropy);
1000 }
1001
1002 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001003 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001004 return userState->readMasterKey(pw, mEntropy);
1005 }
1006
1007 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001008 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001009 encode_key(encoded, keyName);
1010 return android::String8(encoded);
1011 }
1012
1013 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001014 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001015 encode_key(encoded, keyName);
1016 return android::String8::format("%u_%s", uid, encoded);
1017 }
1018
1019 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001020 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001021 encode_key(encoded, keyName);
1022 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1023 encoded);
1024 }
1025
1026 bool reset(uid_t uid) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001027 android::String8 prefix("");
1028 android::Vector<android::String16> aliases;
1029 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1030 return ::SYSTEM_ERROR;
1031 }
1032
Kenny Root655b9582013-04-04 08:37:42 -07001033 UserState* userState = getUserState(uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001034 for (uint32_t i = 0; i < aliases.size(); i++) {
1035 android::String8 filename(aliases[i]);
1036 filename = android::String8::format("%s/%s", userState->getUserDirName(),
1037 getKeyName(filename).string());
1038 del(filename, ::TYPE_ANY, uid);
1039 }
1040
Kenny Root655b9582013-04-04 08:37:42 -07001041 userState->zeroizeMasterKeysInMemory();
1042 userState->setState(STATE_UNINITIALIZED);
1043 return userState->reset();
1044 }
1045
1046 bool isEmpty(uid_t uid) const {
1047 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001048 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001049 return true;
1050 }
1051
1052 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001053 if (!dir) {
1054 return true;
1055 }
Kenny Root31e27462014-09-10 11:28:03 -07001056
Kenny Roota91203b2012-02-15 15:00:46 -08001057 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001058 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001059 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001060 // We only care about files.
1061 if (file->d_type != DT_REG) {
1062 continue;
1063 }
1064
1065 // Skip anything that starts with a "."
1066 if (file->d_name[0] == '.') {
1067 continue;
1068 }
1069
Kenny Root31e27462014-09-10 11:28:03 -07001070 result = false;
1071 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001072 }
1073 closedir(dir);
1074 return result;
1075 }
1076
Kenny Root655b9582013-04-04 08:37:42 -07001077 void lock(uid_t uid) {
1078 UserState* userState = getUserState(uid);
1079 userState->zeroizeMasterKeysInMemory();
1080 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001081 }
1082
Kenny Root655b9582013-04-04 08:37:42 -07001083 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1084 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001085 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1086 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001087 if (rc != NO_ERROR) {
1088 return rc;
1089 }
1090
1091 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001092 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001093 /* If we upgrade the key, we need to write it to disk again. Then
1094 * it must be read it again since the blob is encrypted each time
1095 * it's written.
1096 */
Kenny Root655b9582013-04-04 08:37:42 -07001097 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1098 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001099 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1100 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001101 return rc;
1102 }
1103 }
Kenny Root822c3a92012-03-23 16:34:39 -07001104 }
1105
Kenny Root17208e02013-09-04 13:56:03 -07001106 /*
1107 * This will upgrade software-backed keys to hardware-backed keys when
1108 * the HAL for the device supports the newer key types.
1109 */
1110 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1111 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1112 && keyBlob->isFallback()) {
1113 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1114 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1115
1116 // The HAL allowed the import, reget the key to have the "fresh"
1117 // version.
1118 if (imported == NO_ERROR) {
1119 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1120 }
1121 }
1122
Kenny Rootd53bc922013-03-21 14:10:15 -07001123 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001124 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1125 return KEY_NOT_FOUND;
1126 }
1127
1128 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001129 }
1130
Kenny Root655b9582013-04-04 08:37:42 -07001131 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1132 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001133 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1134 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001135 }
1136
Robin Lee4b84fdc2014-09-24 11:56:57 +01001137 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1138 Blob keyBlob;
1139 ResponseCode rc = get(filename, &keyBlob, type, uid);
1140 if (rc != ::NO_ERROR) {
1141 return rc;
1142 }
1143
1144 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1145 // A device doesn't have to implement delete_keypair.
1146 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1147 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1148 rc = ::SYSTEM_ERROR;
1149 }
1150 }
1151 }
1152 if (rc != ::NO_ERROR) {
1153 return rc;
1154 }
1155
1156 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1157 }
1158
1159 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1160 uid_t uid) {
1161
1162 UserState* userState = getUserState(uid);
1163 size_t n = prefix.length();
1164
1165 DIR* dir = opendir(userState->getUserDirName());
1166 if (!dir) {
1167 ALOGW("can't open directory for user: %s", strerror(errno));
1168 return ::SYSTEM_ERROR;
1169 }
1170
1171 struct dirent* file;
1172 while ((file = readdir(dir)) != NULL) {
1173 // We only care about files.
1174 if (file->d_type != DT_REG) {
1175 continue;
1176 }
1177
1178 // Skip anything that starts with a "."
1179 if (file->d_name[0] == '.') {
1180 continue;
1181 }
1182
1183 if (!strncmp(prefix.string(), file->d_name, n)) {
1184 const char* p = &file->d_name[n];
1185 size_t plen = strlen(p);
1186
1187 size_t extra = decode_key_length(p, plen);
1188 char *match = (char*) malloc(extra + 1);
1189 if (match != NULL) {
1190 decode_key(match, p, plen);
1191 matches->push(android::String16(match, extra));
1192 free(match);
1193 } else {
1194 ALOGW("could not allocate match of size %zd", extra);
1195 }
1196 }
1197 }
1198 closedir(dir);
1199 return ::NO_ERROR;
1200 }
1201
Kenny Root07438c82012-11-02 15:41:02 -07001202 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001203 const grant_t* existing = getGrant(filename, granteeUid);
1204 if (existing == NULL) {
1205 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001206 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001207 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001208 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001209 }
1210 }
1211
Kenny Root07438c82012-11-02 15:41:02 -07001212 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001213 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1214 it != mGrants.end(); it++) {
1215 grant_t* grant = *it;
1216 if (grant->uid == granteeUid
1217 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1218 mGrants.erase(it);
1219 return true;
1220 }
Kenny Root70e3a862012-02-15 17:20:23 -08001221 }
Kenny Root70e3a862012-02-15 17:20:23 -08001222 return false;
1223 }
1224
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001225 bool hasGrant(const char* filename, const uid_t uid) const {
1226 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001227 }
1228
Kenny Rootf9119d62013-04-03 09:22:15 -07001229 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1230 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001231 uint8_t* data;
1232 size_t dataLength;
1233 int rc;
1234
1235 if (mDevice->import_keypair == NULL) {
1236 ALOGE("Keymaster doesn't support import!");
1237 return SYSTEM_ERROR;
1238 }
1239
Kenny Root17208e02013-09-04 13:56:03 -07001240 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001241 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001242 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001243 /*
1244 * Maybe the device doesn't support this type of key. Try to use the
1245 * software fallback keymaster implementation. This is a little bit
1246 * lazier than checking the PKCS#8 key type, but the software
1247 * implementation will do that anyway.
1248 */
1249 rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength);
1250 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001251
1252 if (rc) {
1253 ALOGE("Error while importing keypair: %d", rc);
1254 return SYSTEM_ERROR;
1255 }
Kenny Root822c3a92012-03-23 16:34:39 -07001256 }
1257
1258 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1259 free(data);
1260
Kenny Rootf9119d62013-04-03 09:22:15 -07001261 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001262 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001263
Kenny Root655b9582013-04-04 08:37:42 -07001264 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001265 }
1266
Kenny Root1b0e3932013-09-05 13:06:32 -07001267 bool isHardwareBacked(const android::String16& keyType) const {
1268 if (mDevice == NULL) {
1269 ALOGW("can't get keymaster device");
1270 return false;
1271 }
1272
1273 if (sRSAKeyType == keyType) {
1274 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1275 } else {
1276 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1277 && (mDevice->common.module->module_api_version
1278 >= KEYMASTER_MODULE_API_VERSION_0_2);
1279 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001280 }
1281
Kenny Root655b9582013-04-04 08:37:42 -07001282 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1283 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001284 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001285
1286 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1287 if (responseCode == NO_ERROR) {
1288 return responseCode;
1289 }
1290
1291 // If this is one of the legacy UID->UID mappings, use it.
1292 uid_t euid = get_keystore_euid(uid);
1293 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001294 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001295 responseCode = get(filepath8.string(), keyBlob, type, uid);
1296 if (responseCode == NO_ERROR) {
1297 return responseCode;
1298 }
1299 }
1300
1301 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001302 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001303 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001304 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001305 if (end[0] != '_' || end[1] == 0) {
1306 return KEY_NOT_FOUND;
1307 }
Kenny Root86b16e82013-09-09 11:15:54 -07001308 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1309 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001310 if (!hasGrant(filepath8.string(), uid)) {
1311 return responseCode;
1312 }
1313
1314 // It is a granted key. Try to load it.
1315 return get(filepath8.string(), keyBlob, type, uid);
1316 }
1317
1318 /**
1319 * Returns any existing UserState or creates it if it doesn't exist.
1320 */
1321 UserState* getUserState(uid_t uid) {
1322 uid_t userId = get_user_id(uid);
1323
1324 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1325 it != mMasterKeys.end(); it++) {
1326 UserState* state = *it;
1327 if (state->getUserId() == userId) {
1328 return state;
1329 }
1330 }
1331
1332 UserState* userState = new UserState(userId);
1333 if (!userState->initialize()) {
1334 /* There's not much we can do if initialization fails. Trying to
1335 * unlock the keystore for that user will fail as well, so any
1336 * subsequent request for this user will just return SYSTEM_ERROR.
1337 */
1338 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1339 }
1340 mMasterKeys.add(userState);
1341 return userState;
1342 }
1343
1344 /**
1345 * Returns NULL if the UserState doesn't already exist.
1346 */
1347 const UserState* getUserState(uid_t uid) const {
1348 uid_t userId = get_user_id(uid);
1349
1350 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1351 it != mMasterKeys.end(); it++) {
1352 UserState* state = *it;
1353 if (state->getUserId() == userId) {
1354 return state;
1355 }
1356 }
1357
1358 return NULL;
1359 }
1360
Kenny Roota91203b2012-02-15 15:00:46 -08001361private:
Kenny Root655b9582013-04-04 08:37:42 -07001362 static const char* sOldMasterKey;
1363 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001364 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001365 Entropy* mEntropy;
1366
Kenny Root70e3a862012-02-15 17:20:23 -08001367 keymaster_device_t* mDevice;
1368
Kenny Root655b9582013-04-04 08:37:42 -07001369 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001370
Kenny Root655b9582013-04-04 08:37:42 -07001371 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001372
Kenny Root655b9582013-04-04 08:37:42 -07001373 typedef struct {
1374 uint32_t version;
1375 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001376
Kenny Root655b9582013-04-04 08:37:42 -07001377 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001378
Kenny Root655b9582013-04-04 08:37:42 -07001379 const grant_t* getGrant(const char* filename, uid_t uid) const {
1380 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1381 it != mGrants.end(); it++) {
1382 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001383 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001384 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001385 return grant;
1386 }
1387 }
Kenny Root70e3a862012-02-15 17:20:23 -08001388 return NULL;
1389 }
1390
Kenny Root822c3a92012-03-23 16:34:39 -07001391 /**
1392 * Upgrade code. This will upgrade the key from the current version
1393 * to whatever is newest.
1394 */
Kenny Root655b9582013-04-04 08:37:42 -07001395 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1396 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001397 bool updated = false;
1398 uint8_t version = oldVersion;
1399
1400 /* From V0 -> V1: All old types were unknown */
1401 if (version == 0) {
1402 ALOGV("upgrading to version 1 and setting type %d", type);
1403
1404 blob->setType(type);
1405 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001406 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001407 }
1408 version = 1;
1409 updated = true;
1410 }
1411
Kenny Rootf9119d62013-04-03 09:22:15 -07001412 /* From V1 -> V2: All old keys were encrypted */
1413 if (version == 1) {
1414 ALOGV("upgrading to version 2");
1415
1416 blob->setEncrypted(true);
1417 version = 2;
1418 updated = true;
1419 }
1420
Kenny Root822c3a92012-03-23 16:34:39 -07001421 /*
1422 * If we've updated, set the key blob to the right version
1423 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001424 */
Kenny Root822c3a92012-03-23 16:34:39 -07001425 if (updated) {
1426 ALOGV("updated and writing file %s", filename);
1427 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001428 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001429
1430 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001431 }
1432
1433 /**
1434 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1435 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1436 * Then it overwrites the original blob with the new blob
1437 * format that is returned from the keymaster.
1438 */
Kenny Root655b9582013-04-04 08:37:42 -07001439 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001440 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1441 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1442 if (b.get() == NULL) {
1443 ALOGE("Problem instantiating BIO");
1444 return SYSTEM_ERROR;
1445 }
1446
1447 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1448 if (pkey.get() == NULL) {
1449 ALOGE("Couldn't read old PEM file");
1450 return SYSTEM_ERROR;
1451 }
1452
1453 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1454 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1455 if (len < 0) {
1456 ALOGE("Couldn't measure PKCS#8 length");
1457 return SYSTEM_ERROR;
1458 }
1459
Kenny Root70c98892013-02-07 09:10:36 -08001460 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1461 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001462 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1463 ALOGE("Couldn't convert to PKCS#8");
1464 return SYSTEM_ERROR;
1465 }
1466
Kenny Rootf9119d62013-04-03 09:22:15 -07001467 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1468 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001469 if (rc != NO_ERROR) {
1470 return rc;
1471 }
1472
Kenny Root655b9582013-04-04 08:37:42 -07001473 return get(filename, blob, TYPE_KEY_PAIR, uid);
1474 }
1475
1476 void readMetaData() {
1477 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1478 if (in < 0) {
1479 return;
1480 }
1481 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1482 if (fileLength != sizeof(mMetaData)) {
1483 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1484 sizeof(mMetaData));
1485 }
1486 close(in);
1487 }
1488
1489 void writeMetaData() {
1490 const char* tmpFileName = ".metadata.tmp";
1491 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1492 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1493 if (out < 0) {
1494 ALOGE("couldn't write metadata file: %s", strerror(errno));
1495 return;
1496 }
1497 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1498 if (fileLength != sizeof(mMetaData)) {
1499 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1500 sizeof(mMetaData));
1501 }
1502 close(out);
1503 rename(tmpFileName, sMetaDataFile);
1504 }
1505
1506 bool upgradeKeystore() {
1507 bool upgraded = false;
1508
1509 if (mMetaData.version == 0) {
1510 UserState* userState = getUserState(0);
1511
1512 // Initialize first so the directory is made.
1513 userState->initialize();
1514
1515 // Migrate the old .masterkey file to user 0.
1516 if (access(sOldMasterKey, R_OK) == 0) {
1517 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1518 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1519 return false;
1520 }
1521 }
1522
1523 // Initialize again in case we had a key.
1524 userState->initialize();
1525
1526 // Try to migrate existing keys.
1527 DIR* dir = opendir(".");
1528 if (!dir) {
1529 // Give up now; maybe we can upgrade later.
1530 ALOGE("couldn't open keystore's directory; something is wrong");
1531 return false;
1532 }
1533
1534 struct dirent* file;
1535 while ((file = readdir(dir)) != NULL) {
1536 // We only care about files.
1537 if (file->d_type != DT_REG) {
1538 continue;
1539 }
1540
1541 // Skip anything that starts with a "."
1542 if (file->d_name[0] == '.') {
1543 continue;
1544 }
1545
1546 // Find the current file's user.
1547 char* end;
1548 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1549 if (end[0] != '_' || end[1] == 0) {
1550 continue;
1551 }
1552 UserState* otherUser = getUserState(thisUid);
1553 if (otherUser->getUserId() != 0) {
1554 unlinkat(dirfd(dir), file->d_name, 0);
1555 }
1556
1557 // Rename the file into user directory.
1558 DIR* otherdir = opendir(otherUser->getUserDirName());
1559 if (otherdir == NULL) {
1560 ALOGW("couldn't open user directory for rename");
1561 continue;
1562 }
1563 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1564 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1565 }
1566 closedir(otherdir);
1567 }
1568 closedir(dir);
1569
1570 mMetaData.version = 1;
1571 upgraded = true;
1572 }
1573
1574 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001575 }
Kenny Roota91203b2012-02-15 15:00:46 -08001576};
1577
Kenny Root655b9582013-04-04 08:37:42 -07001578const char* KeyStore::sOldMasterKey = ".masterkey";
1579const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001580
Kenny Root1b0e3932013-09-05 13:06:32 -07001581const android::String16 KeyStore::sRSAKeyType("RSA");
1582
Kenny Root07438c82012-11-02 15:41:02 -07001583namespace android {
1584class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1585public:
1586 KeyStoreProxy(KeyStore* keyStore)
1587 : mKeyStore(keyStore)
1588 {
Kenny Roota91203b2012-02-15 15:00:46 -08001589 }
Kenny Roota91203b2012-02-15 15:00:46 -08001590
Kenny Root07438c82012-11-02 15:41:02 -07001591 void binderDied(const wp<IBinder>&) {
1592 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001593 }
Kenny Roota91203b2012-02-15 15:00:46 -08001594
Kenny Root07438c82012-11-02 15:41:02 -07001595 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001596 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001597 pid_t spid = IPCThreadState::self()->getCallingPid();
1598 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001599 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001600 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001601 }
Kenny Roota91203b2012-02-15 15:00:46 -08001602
Kenny Root655b9582013-04-04 08:37:42 -07001603 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001604 }
1605
Kenny Root07438c82012-11-02 15:41:02 -07001606 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001607 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001608 pid_t spid = IPCThreadState::self()->getCallingPid();
1609 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001610 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001611 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001612 }
Kenny Root07438c82012-11-02 15:41:02 -07001613
Kenny Root07438c82012-11-02 15:41:02 -07001614 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001615 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001616
Kenny Root655b9582013-04-04 08:37:42 -07001617 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001618 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001619 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001620 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001621 *item = NULL;
1622 *itemLength = 0;
1623 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001624 }
Kenny Roota91203b2012-02-15 15:00:46 -08001625
Kenny Root07438c82012-11-02 15:41:02 -07001626 *item = (uint8_t*) malloc(keyBlob.getLength());
1627 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1628 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001629
Kenny Root07438c82012-11-02 15:41:02 -07001630 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001631 }
1632
Kenny Rootf9119d62013-04-03 09:22:15 -07001633 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1634 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001635 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001636 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001637 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001638 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001639 return ::PERMISSION_DENIED;
1640 }
Kenny Root07438c82012-11-02 15:41:02 -07001641
Kenny Rootf9119d62013-04-03 09:22:15 -07001642 State state = mKeyStore->getState(callingUid);
1643 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1644 ALOGD("calling get in state: %d", state);
1645 return state;
1646 }
1647
Kenny Root49468902013-03-19 13:41:33 -07001648 if (targetUid == -1) {
1649 targetUid = callingUid;
1650 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001651 return ::PERMISSION_DENIED;
1652 }
1653
Kenny Root07438c82012-11-02 15:41:02 -07001654 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001655 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001656
1657 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001658 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1659
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001660 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001661 }
1662
Kenny Root49468902013-03-19 13:41:33 -07001663 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001664 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001665 pid_t spid = IPCThreadState::self()->getCallingPid();
1666 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001667 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001668 return ::PERMISSION_DENIED;
1669 }
Kenny Root70e3a862012-02-15 17:20:23 -08001670
Kenny Root49468902013-03-19 13:41:33 -07001671 if (targetUid == -1) {
1672 targetUid = callingUid;
1673 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001674 return ::PERMISSION_DENIED;
1675 }
1676
Kenny Root07438c82012-11-02 15:41:02 -07001677 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001678 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01001679 return mKeyStore->del(filename.string(), ::TYPE_GENERIC, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001680 }
1681
Kenny Root49468902013-03-19 13:41:33 -07001682 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001683 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001684 pid_t spid = IPCThreadState::self()->getCallingPid();
1685 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001686 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001687 return ::PERMISSION_DENIED;
1688 }
Kenny Root70e3a862012-02-15 17:20:23 -08001689
Kenny Root49468902013-03-19 13:41:33 -07001690 if (targetUid == -1) {
1691 targetUid = callingUid;
1692 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001693 return ::PERMISSION_DENIED;
1694 }
1695
Kenny Root07438c82012-11-02 15:41:02 -07001696 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001697 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001698
Kenny Root655b9582013-04-04 08:37:42 -07001699 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001700 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1701 }
1702 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001703 }
1704
Kenny Root49468902013-03-19 13:41:33 -07001705 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001706 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001707 pid_t spid = IPCThreadState::self()->getCallingPid();
1708 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001709 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001710 return ::PERMISSION_DENIED;
1711 }
Kenny Root70e3a862012-02-15 17:20:23 -08001712
Kenny Root49468902013-03-19 13:41:33 -07001713 if (targetUid == -1) {
1714 targetUid = callingUid;
1715 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001716 return ::PERMISSION_DENIED;
1717 }
1718
Kenny Root07438c82012-11-02 15:41:02 -07001719 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001720 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001721
Robin Lee4b84fdc2014-09-24 11:56:57 +01001722 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1723 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001724 }
Kenny Root07438c82012-11-02 15:41:02 -07001725 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001726 }
1727
Kenny Root07438c82012-11-02 15:41:02 -07001728 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001729 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001730 pid_t spid = IPCThreadState::self()->getCallingPid();
1731 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001732 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001733 return ::PERMISSION_DENIED;
1734 }
1735
Robin Lee4b84fdc2014-09-24 11:56:57 +01001736 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001737 }
1738
Kenny Root07438c82012-11-02 15:41:02 -07001739 /*
1740 * Here is the history. To improve the security, the parameters to generate the
1741 * master key has been changed. To make a seamless transition, we update the
1742 * file using the same password when the user unlock it for the first time. If
1743 * any thing goes wrong during the transition, the new file will not overwrite
1744 * the old one. This avoids permanent damages of the existing data.
1745 */
1746 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001747 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001748 pid_t spid = IPCThreadState::self()->getCallingPid();
1749 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001750 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001751 return ::PERMISSION_DENIED;
1752 }
Kenny Root70e3a862012-02-15 17:20:23 -08001753
Kenny Root07438c82012-11-02 15:41:02 -07001754 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001755
Kenny Root655b9582013-04-04 08:37:42 -07001756 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001757 case ::STATE_UNINITIALIZED: {
1758 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001759 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001760 }
1761 case ::STATE_NO_ERROR: {
1762 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001763 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001764 }
1765 case ::STATE_LOCKED: {
1766 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001767 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001768 }
1769 }
1770 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001771 }
1772
Kenny Root07438c82012-11-02 15:41:02 -07001773 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001774 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001775 pid_t spid = IPCThreadState::self()->getCallingPid();
1776 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001777 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001778 return ::PERMISSION_DENIED;
1779 }
Kenny Root70e3a862012-02-15 17:20:23 -08001780
Kenny Root655b9582013-04-04 08:37:42 -07001781 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001782 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001783 ALOGD("calling lock in state: %d", state);
1784 return state;
1785 }
1786
Kenny Root655b9582013-04-04 08:37:42 -07001787 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001788 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001789 }
1790
Kenny Root07438c82012-11-02 15:41:02 -07001791 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001792 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001793 pid_t spid = IPCThreadState::self()->getCallingPid();
1794 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001795 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001796 return ::PERMISSION_DENIED;
1797 }
1798
Kenny Root655b9582013-04-04 08:37:42 -07001799 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001800 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001801 ALOGD("calling unlock when not locked");
1802 return state;
1803 }
1804
1805 const String8 password8(pw);
1806 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001807 }
1808
Kenny Root07438c82012-11-02 15:41:02 -07001809 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001810 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001811 pid_t spid = IPCThreadState::self()->getCallingPid();
1812 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001813 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001814 return -1;
1815 }
Kenny Root70e3a862012-02-15 17:20:23 -08001816
Kenny Root655b9582013-04-04 08:37:42 -07001817 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001818 }
1819
Kenny Root96427ba2013-08-16 14:02:41 -07001820 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1821 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001822 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001823 pid_t spid = IPCThreadState::self()->getCallingPid();
1824 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001825 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001826 return ::PERMISSION_DENIED;
1827 }
Kenny Root70e3a862012-02-15 17:20:23 -08001828
Kenny Root49468902013-03-19 13:41:33 -07001829 if (targetUid == -1) {
1830 targetUid = callingUid;
1831 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001832 return ::PERMISSION_DENIED;
1833 }
1834
Kenny Root655b9582013-04-04 08:37:42 -07001835 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001836 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1837 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001838 return state;
1839 }
Kenny Root70e3a862012-02-15 17:20:23 -08001840
Kenny Root07438c82012-11-02 15:41:02 -07001841 uint8_t* data;
1842 size_t dataLength;
1843 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001844 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001845
1846 const keymaster_device_t* device = mKeyStore->getDevice();
1847 if (device == NULL) {
1848 return ::SYSTEM_ERROR;
1849 }
1850
1851 if (device->generate_keypair == NULL) {
1852 return ::SYSTEM_ERROR;
1853 }
1854
Kenny Root17208e02013-09-04 13:56:03 -07001855 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001856 keymaster_dsa_keygen_params_t dsa_params;
1857 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001858
Kenny Root96427ba2013-08-16 14:02:41 -07001859 if (keySize == -1) {
1860 keySize = DSA_DEFAULT_KEY_SIZE;
1861 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1862 || keySize > DSA_MAX_KEY_SIZE) {
1863 ALOGI("invalid key size %d", keySize);
1864 return ::SYSTEM_ERROR;
1865 }
1866 dsa_params.key_size = keySize;
1867
1868 if (args->size() == 3) {
1869 sp<KeystoreArg> gArg = args->itemAt(0);
1870 sp<KeystoreArg> pArg = args->itemAt(1);
1871 sp<KeystoreArg> qArg = args->itemAt(2);
1872
1873 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1874 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1875 dsa_params.generator_len = gArg->size();
1876
1877 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1878 dsa_params.prime_p_len = pArg->size();
1879
1880 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1881 dsa_params.prime_q_len = qArg->size();
1882 } else {
1883 ALOGI("not all DSA parameters were read");
1884 return ::SYSTEM_ERROR;
1885 }
1886 } else if (args->size() != 0) {
1887 ALOGI("DSA args must be 3");
1888 return ::SYSTEM_ERROR;
1889 }
1890
Kenny Root1d448c02013-11-21 10:36:53 -08001891 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001892 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1893 } else {
1894 isFallback = true;
1895 rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1896 }
1897 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001898 keymaster_ec_keygen_params_t ec_params;
1899 memset(&ec_params, '\0', sizeof(ec_params));
1900
1901 if (keySize == -1) {
1902 keySize = EC_DEFAULT_KEY_SIZE;
1903 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1904 ALOGI("invalid key size %d", keySize);
1905 return ::SYSTEM_ERROR;
1906 }
1907 ec_params.field_size = keySize;
1908
Kenny Root1d448c02013-11-21 10:36:53 -08001909 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001910 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1911 } else {
1912 isFallback = true;
1913 rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1914 }
Kenny Root96427ba2013-08-16 14:02:41 -07001915 } else if (keyType == EVP_PKEY_RSA) {
1916 keymaster_rsa_keygen_params_t rsa_params;
1917 memset(&rsa_params, '\0', sizeof(rsa_params));
1918 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1919
1920 if (keySize == -1) {
1921 keySize = RSA_DEFAULT_KEY_SIZE;
1922 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1923 ALOGI("invalid key size %d", keySize);
1924 return ::SYSTEM_ERROR;
1925 }
1926 rsa_params.modulus_size = keySize;
1927
1928 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001929 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001930 return ::SYSTEM_ERROR;
1931 } else if (args->size() == 1) {
1932 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1933 if (pubExpBlob != NULL) {
1934 Unique_BIGNUM pubExpBn(
1935 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1936 pubExpBlob->size(), NULL));
1937 if (pubExpBn.get() == NULL) {
1938 ALOGI("Could not convert public exponent to BN");
1939 return ::SYSTEM_ERROR;
1940 }
1941 unsigned long pubExp = BN_get_word(pubExpBn.get());
1942 if (pubExp == 0xFFFFFFFFL) {
1943 ALOGI("cannot represent public exponent as a long value");
1944 return ::SYSTEM_ERROR;
1945 }
1946 rsa_params.public_exponent = pubExp;
1947 }
1948 }
1949
1950 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1951 } else {
1952 ALOGW("Unsupported key type %d", keyType);
1953 rc = -1;
1954 }
1955
Kenny Root07438c82012-11-02 15:41:02 -07001956 if (rc) {
1957 return ::SYSTEM_ERROR;
1958 }
1959
Kenny Root655b9582013-04-04 08:37:42 -07001960 String8 name8(name);
1961 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001962
1963 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1964 free(data);
1965
Kenny Rootee8068b2013-10-07 09:49:15 -07001966 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001967 keyBlob.setFallback(isFallback);
1968
Kenny Root655b9582013-04-04 08:37:42 -07001969 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001970 }
1971
Kenny Rootf9119d62013-04-03 09:22:15 -07001972 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1973 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001974 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001975 pid_t spid = IPCThreadState::self()->getCallingPid();
1976 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001977 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001978 return ::PERMISSION_DENIED;
1979 }
Kenny Root07438c82012-11-02 15:41:02 -07001980
Kenny Root49468902013-03-19 13:41:33 -07001981 if (targetUid == -1) {
1982 targetUid = callingUid;
1983 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001984 return ::PERMISSION_DENIED;
1985 }
1986
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001987 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001988 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001989 ALOGD("calling import in state: %d", state);
1990 return state;
1991 }
1992
1993 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001994 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001995
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001996 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001997 }
1998
Kenny Root07438c82012-11-02 15:41:02 -07001999 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2000 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002001 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002002 pid_t spid = IPCThreadState::self()->getCallingPid();
2003 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002004 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002005 return ::PERMISSION_DENIED;
2006 }
Kenny Root07438c82012-11-02 15:41:02 -07002007
Kenny Root07438c82012-11-02 15:41:02 -07002008 Blob keyBlob;
2009 String8 name8(name);
2010
Kenny Rootd38a0b02013-02-13 12:59:14 -08002011 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002012 int rc;
2013
Kenny Root655b9582013-04-04 08:37:42 -07002014 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002015 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002016 if (responseCode != ::NO_ERROR) {
2017 return responseCode;
2018 }
2019
2020 const keymaster_device_t* device = mKeyStore->getDevice();
2021 if (device == NULL) {
2022 ALOGE("no keymaster device; cannot sign");
2023 return ::SYSTEM_ERROR;
2024 }
2025
2026 if (device->sign_data == NULL) {
2027 ALOGE("device doesn't implement signing");
2028 return ::SYSTEM_ERROR;
2029 }
2030
2031 keymaster_rsa_sign_params_t params;
2032 params.digest_type = DIGEST_NONE;
2033 params.padding_type = PADDING_NONE;
2034
Kenny Root17208e02013-09-04 13:56:03 -07002035 if (keyBlob.isFallback()) {
2036 rc = openssl_sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2037 length, out, outLength);
2038 } else {
2039 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2040 length, out, outLength);
2041 }
Kenny Root07438c82012-11-02 15:41:02 -07002042 if (rc) {
2043 ALOGW("device couldn't sign data");
2044 return ::SYSTEM_ERROR;
2045 }
2046
2047 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002048 }
2049
Kenny Root07438c82012-11-02 15:41:02 -07002050 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2051 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002052 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002053 pid_t spid = IPCThreadState::self()->getCallingPid();
2054 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002055 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002056 return ::PERMISSION_DENIED;
2057 }
Kenny Root70e3a862012-02-15 17:20:23 -08002058
Kenny Root655b9582013-04-04 08:37:42 -07002059 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002060 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002061 ALOGD("calling verify in state: %d", state);
2062 return state;
2063 }
Kenny Root70e3a862012-02-15 17:20:23 -08002064
Kenny Root07438c82012-11-02 15:41:02 -07002065 Blob keyBlob;
2066 String8 name8(name);
2067 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002068
Kenny Root655b9582013-04-04 08:37:42 -07002069 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002070 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002071 if (responseCode != ::NO_ERROR) {
2072 return responseCode;
2073 }
Kenny Root70e3a862012-02-15 17:20:23 -08002074
Kenny Root07438c82012-11-02 15:41:02 -07002075 const keymaster_device_t* device = mKeyStore->getDevice();
2076 if (device == NULL) {
2077 return ::SYSTEM_ERROR;
2078 }
Kenny Root70e3a862012-02-15 17:20:23 -08002079
Kenny Root07438c82012-11-02 15:41:02 -07002080 if (device->verify_data == NULL) {
2081 return ::SYSTEM_ERROR;
2082 }
Kenny Root70e3a862012-02-15 17:20:23 -08002083
Kenny Root07438c82012-11-02 15:41:02 -07002084 keymaster_rsa_sign_params_t params;
2085 params.digest_type = DIGEST_NONE;
2086 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002087
Kenny Root17208e02013-09-04 13:56:03 -07002088 if (keyBlob.isFallback()) {
2089 rc = openssl_verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2090 dataLength, signature, signatureLength);
2091 } else {
2092 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2093 dataLength, signature, signatureLength);
2094 }
Kenny Root07438c82012-11-02 15:41:02 -07002095 if (rc) {
2096 return ::SYSTEM_ERROR;
2097 } else {
2098 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002099 }
2100 }
Kenny Root07438c82012-11-02 15:41:02 -07002101
2102 /*
2103 * TODO: The abstraction between things stored in hardware and regular blobs
2104 * of data stored on the filesystem should be moved down to keystore itself.
2105 * Unfortunately the Java code that calls this has naming conventions that it
2106 * knows about. Ideally keystore shouldn't be used to store random blobs of
2107 * data.
2108 *
2109 * Until that happens, it's necessary to have a separate "get_pubkey" and
2110 * "del_key" since the Java code doesn't really communicate what it's
2111 * intentions are.
2112 */
2113 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002114 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002115 pid_t spid = IPCThreadState::self()->getCallingPid();
2116 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002117 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002118 return ::PERMISSION_DENIED;
2119 }
Kenny Root07438c82012-11-02 15:41:02 -07002120
Kenny Root07438c82012-11-02 15:41:02 -07002121 Blob keyBlob;
2122 String8 name8(name);
2123
Kenny Rootd38a0b02013-02-13 12:59:14 -08002124 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002125
Kenny Root655b9582013-04-04 08:37:42 -07002126 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002127 TYPE_KEY_PAIR);
2128 if (responseCode != ::NO_ERROR) {
2129 return responseCode;
2130 }
2131
2132 const keymaster_device_t* device = mKeyStore->getDevice();
2133 if (device == NULL) {
2134 return ::SYSTEM_ERROR;
2135 }
2136
2137 if (device->get_keypair_public == NULL) {
2138 ALOGE("device has no get_keypair_public implementation!");
2139 return ::SYSTEM_ERROR;
2140 }
2141
Kenny Root17208e02013-09-04 13:56:03 -07002142 int rc;
2143 if (keyBlob.isFallback()) {
2144 rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2145 pubkeyLength);
2146 } else {
2147 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2148 pubkeyLength);
2149 }
Kenny Root07438c82012-11-02 15:41:02 -07002150 if (rc) {
2151 return ::SYSTEM_ERROR;
2152 }
2153
2154 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002155 }
Kenny Root07438c82012-11-02 15:41:02 -07002156
Kenny Root49468902013-03-19 13:41:33 -07002157 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002158 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002159 pid_t spid = IPCThreadState::self()->getCallingPid();
2160 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002161 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002162 return ::PERMISSION_DENIED;
2163 }
Kenny Root07438c82012-11-02 15:41:02 -07002164
Kenny Root49468902013-03-19 13:41:33 -07002165 if (targetUid == -1) {
2166 targetUid = callingUid;
2167 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002168 return ::PERMISSION_DENIED;
2169 }
2170
Kenny Root07438c82012-11-02 15:41:02 -07002171 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002172 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01002173 return mKeyStore->del(filename.string(), ::TYPE_KEY_PAIR, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002174 }
2175
2176 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002177 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002178 pid_t spid = IPCThreadState::self()->getCallingPid();
2179 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002180 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002181 return ::PERMISSION_DENIED;
2182 }
Kenny Root07438c82012-11-02 15:41:02 -07002183
Kenny Root655b9582013-04-04 08:37:42 -07002184 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002185 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002186 ALOGD("calling grant in state: %d", state);
2187 return state;
2188 }
2189
2190 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002191 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002192
Kenny Root655b9582013-04-04 08:37:42 -07002193 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002194 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2195 }
2196
Kenny Root655b9582013-04-04 08:37:42 -07002197 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002198 return ::NO_ERROR;
2199 }
2200
2201 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002202 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002203 pid_t spid = IPCThreadState::self()->getCallingPid();
2204 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002205 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002206 return ::PERMISSION_DENIED;
2207 }
Kenny Root07438c82012-11-02 15:41:02 -07002208
Kenny Root655b9582013-04-04 08:37:42 -07002209 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002210 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002211 ALOGD("calling ungrant in state: %d", state);
2212 return state;
2213 }
2214
2215 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002216 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002217
Kenny Root655b9582013-04-04 08:37:42 -07002218 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002219 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2220 }
2221
Kenny Root655b9582013-04-04 08:37:42 -07002222 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002223 }
2224
2225 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002226 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002227 pid_t spid = IPCThreadState::self()->getCallingPid();
2228 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002229 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002230 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002231 }
Kenny Root07438c82012-11-02 15:41:02 -07002232
2233 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002234 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002235
Kenny Root655b9582013-04-04 08:37:42 -07002236 if (access(filename.string(), R_OK) == -1) {
2237 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002238 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002239 }
2240
Kenny Root655b9582013-04-04 08:37:42 -07002241 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002242 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002243 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002244 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002245 }
2246
2247 struct stat s;
2248 int ret = fstat(fd, &s);
2249 close(fd);
2250 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002251 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002252 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002253 }
2254
Kenny Root36a9e232013-02-04 14:24:15 -08002255 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002256 }
2257
Kenny Rootd53bc922013-03-21 14:10:15 -07002258 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2259 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002260 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002261 pid_t spid = IPCThreadState::self()->getCallingPid();
2262 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002263 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002264 return -1L;
2265 }
2266
Kenny Root655b9582013-04-04 08:37:42 -07002267 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002268 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002269 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002270 return state;
2271 }
2272
Kenny Rootd53bc922013-03-21 14:10:15 -07002273 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2274 srcUid = callingUid;
2275 } else if (!is_granted_to(callingUid, srcUid)) {
2276 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002277 return ::PERMISSION_DENIED;
2278 }
2279
Kenny Rootd53bc922013-03-21 14:10:15 -07002280 if (destUid == -1) {
2281 destUid = callingUid;
2282 }
2283
2284 if (srcUid != destUid) {
2285 if (static_cast<uid_t>(srcUid) != callingUid) {
2286 ALOGD("can only duplicate from caller to other or to same uid: "
2287 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2288 return ::PERMISSION_DENIED;
2289 }
2290
2291 if (!is_granted_to(callingUid, destUid)) {
2292 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2293 return ::PERMISSION_DENIED;
2294 }
2295 }
2296
2297 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002298 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002299
Kenny Rootd53bc922013-03-21 14:10:15 -07002300 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002301 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002302
Kenny Root655b9582013-04-04 08:37:42 -07002303 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2304 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002305 return ::SYSTEM_ERROR;
2306 }
2307
Kenny Rootd53bc922013-03-21 14:10:15 -07002308 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002309 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002310 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002311 if (responseCode != ::NO_ERROR) {
2312 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002313 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002314
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002315 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002316 }
2317
Kenny Root1b0e3932013-09-05 13:06:32 -07002318 int32_t is_hardware_backed(const String16& keyType) {
2319 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002320 }
2321
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002322 int32_t clear_uid(int64_t targetUid64) {
2323 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002324 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002325 pid_t spid = IPCThreadState::self()->getCallingPid();
2326 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002327 ALOGW("permission denied for %d: clear_uid", callingUid);
2328 return ::PERMISSION_DENIED;
2329 }
2330
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002331 if (targetUid64 == -1) {
2332 targetUid = callingUid;
Kenny Root007cb232014-07-30 16:59:42 -07002333 } else if (!is_self_or_system(callingUid, targetUid)) {
2334 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002335 return ::PERMISSION_DENIED;
2336 }
2337
Kenny Roota9bb5492013-04-01 16:29:11 -07002338 const keymaster_device_t* device = mKeyStore->getDevice();
2339 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002340 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002341 return ::SYSTEM_ERROR;
2342 }
2343
Robin Lee4b84fdc2014-09-24 11:56:57 +01002344 String8 prefix = String8::format("%u_", targetUid);
2345 Vector<String16> aliases;
2346 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002347 return ::SYSTEM_ERROR;
2348 }
2349
Robin Lee4b84fdc2014-09-24 11:56:57 +01002350 for (uint32_t i = 0; i < aliases.size(); i++) {
2351 String8 name8(aliases[i]);
2352 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2353 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002354 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002355 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002356 }
2357
Robin Lee4b84fdc2014-09-24 11:56:57 +01002358 int32_t reset_uid(int32_t targetUid) {
Robin Lee4e865752014-08-19 17:37:55 +01002359 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2360 pid_t spid = IPCThreadState::self()->getCallingPid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01002361
Robin Lee4e865752014-08-19 17:37:55 +01002362 if (!has_permission(callingUid, P_RESET_UID, spid)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01002363 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002364 return ::PERMISSION_DENIED;
2365 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002366 if (!is_self_or_system(callingUid, targetUid)) {
2367 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002368 return ::PERMISSION_DENIED;
2369 }
2370
Robin Lee4b84fdc2014-09-24 11:56:57 +01002371 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002372 }
2373
2374 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
2375 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2376 pid_t spid = IPCThreadState::self()->getCallingPid();
2377 if (!has_permission(callingUid, P_SYNC_UID, spid)) {
2378 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2379 return ::PERMISSION_DENIED;
2380 }
2381 if (callingUid != AID_SYSTEM) {
2382 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2383 return ::PERMISSION_DENIED;
2384 }
2385 if (sourceUid == targetUid) {
2386 return ::SYSTEM_ERROR;
2387 }
2388
2389 // Initialise user keystore with existing master key held in-memory
2390 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2391 }
2392
2393 int32_t password_uid(const String16& pw, int32_t targetUid) {
2394 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2395 pid_t spid = IPCThreadState::self()->getCallingPid();
2396 if (!has_permission(callingUid, P_PASSWORD_UID, spid)) {
2397 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2398 return ::PERMISSION_DENIED;
2399 }
2400 if (callingUid != AID_SYSTEM) {
2401 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2402 return ::PERMISSION_DENIED;
2403 }
2404
2405 const String8 password8(pw);
2406
2407 switch (mKeyStore->getState(targetUid)) {
2408 case ::STATE_UNINITIALIZED: {
2409 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2410 return mKeyStore->initializeUser(password8, targetUid);
2411 }
2412 case ::STATE_NO_ERROR: {
2413 // rewrite master key with new password.
2414 return mKeyStore->writeMasterKey(password8, targetUid);
2415 }
2416 case ::STATE_LOCKED: {
2417 // read master key, decrypt with password, initialize mMasterKey*.
2418 return mKeyStore->readMasterKey(password8, targetUid);
2419 }
2420 }
2421 return ::SYSTEM_ERROR;
2422 }
2423
Kenny Root07438c82012-11-02 15:41:02 -07002424private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002425 inline bool isKeystoreUnlocked(State state) {
2426 switch (state) {
2427 case ::STATE_NO_ERROR:
2428 return true;
2429 case ::STATE_UNINITIALIZED:
2430 case ::STATE_LOCKED:
2431 return false;
2432 }
2433 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002434 }
2435
Kenny Root1d448c02013-11-21 10:36:53 -08002436 bool isKeyTypeSupported(const keymaster_device_t* device, keymaster_keypair_t keyType) {
2437 const int32_t device_api = device->common.module->module_api_version;
2438 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2439 switch (keyType) {
2440 case TYPE_RSA:
2441 case TYPE_DSA:
2442 case TYPE_EC:
2443 return true;
2444 default:
2445 return false;
2446 }
2447 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2448 switch (keyType) {
2449 case TYPE_RSA:
2450 return true;
2451 case TYPE_DSA:
2452 return device->flags & KEYMASTER_SUPPORTS_DSA;
2453 case TYPE_EC:
2454 return device->flags & KEYMASTER_SUPPORTS_EC;
2455 default:
2456 return false;
2457 }
2458 } else {
2459 return keyType == TYPE_RSA;
2460 }
2461 }
2462
Kenny Root07438c82012-11-02 15:41:02 -07002463 ::KeyStore* mKeyStore;
2464};
2465
2466}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002467
2468int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002469 if (argc < 2) {
2470 ALOGE("A directory must be specified!");
2471 return 1;
2472 }
2473 if (chdir(argv[1]) == -1) {
2474 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2475 return 1;
2476 }
2477
2478 Entropy entropy;
2479 if (!entropy.open()) {
2480 return 1;
2481 }
Kenny Root70e3a862012-02-15 17:20:23 -08002482
2483 keymaster_device_t* dev;
2484 if (keymaster_device_initialize(&dev)) {
2485 ALOGE("keystore keymaster could not be initialized; exiting");
2486 return 1;
2487 }
2488
Riley Spahneaabae92014-06-30 12:39:52 -07002489 ks_is_selinux_enabled = is_selinux_enabled();
2490 if (ks_is_selinux_enabled) {
2491 union selinux_callback cb;
2492 cb.func_log = selinux_log_callback;
2493 selinux_set_callback(SELINUX_CB_LOG, cb);
2494 if (getcon(&tctx) != 0) {
2495 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2496 return -1;
2497 }
2498 } else {
2499 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2500 }
2501
Kenny Root70e3a862012-02-15 17:20:23 -08002502 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002503 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002504 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2505 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2506 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2507 if (ret != android::OK) {
2508 ALOGE("Couldn't register binder service!");
2509 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002510 }
Kenny Root07438c82012-11-02 15:41:02 -07002511
2512 /*
2513 * We're the only thread in existence, so we're just going to process
2514 * Binder transaction as a single-threaded program.
2515 */
2516 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002517
2518 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002519 return 1;
2520}