blob: 4fdd593d17353ab1e4c8d4448a78e06e4912facd [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
23#include <unistd.h>
24#include <signal.h>
25#include <errno.h>
26#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070027#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080028#include <fcntl.h>
29#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070030#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080031#include <sys/types.h>
32#include <sys/socket.h>
33#include <sys/stat.h>
34#include <sys/time.h>
35#include <arpa/inet.h>
36
37#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070038#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080039#include <openssl/evp.h>
40#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070041#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080042
Kenny Root70e3a862012-02-15 17:20:23 -080043#include <hardware/keymaster.h>
44
Kenny Root17208e02013-09-04 13:56:03 -070045#include <keymaster/softkeymaster.h>
46
Kenny Root26cfc082013-09-11 14:38:56 -070047#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070048#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070049#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080050
Kenny Root07438c82012-11-02 15:41:02 -070051#include <keystore/IKeystoreService.h>
52#include <binder/IPCThreadState.h>
53#include <binder/IServiceManager.h>
54
Kenny Roota91203b2012-02-15 15:00:46 -080055#include <cutils/log.h>
56#include <cutils/sockets.h>
57#include <private/android_filesystem_config.h>
58
Kenny Root07438c82012-11-02 15:41:02 -070059#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080060
Riley Spahneaabae92014-06-30 12:39:52 -070061#include <selinux/android.h>
62
Kenny Root96427ba2013-08-16 14:02:41 -070063#include "defaults.h"
64
Kenny Roota91203b2012-02-15 15:00:46 -080065/* KeyStore is a secured storage for key-value pairs. In this implementation,
66 * each file stores one key-value pair. Keys are encoded in file names, and
67 * values are encrypted with checksums. The encryption key is protected by a
68 * user-defined password. To keep things simple, buffers are always larger than
69 * the maximum space we needed, so boundary checks on buffers are omitted. */
70
71#define KEY_SIZE ((NAME_MAX - 15) / 2)
72#define VALUE_SIZE 32768
73#define PASSWORD_SIZE VALUE_SIZE
74
Kenny Root822c3a92012-03-23 16:34:39 -070075
Kenny Root96427ba2013-08-16 14:02:41 -070076struct BIGNUM_Delete {
77 void operator()(BIGNUM* p) const {
78 BN_free(p);
79 }
80};
81typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
82
Kenny Root822c3a92012-03-23 16:34:39 -070083struct BIO_Delete {
84 void operator()(BIO* p) const {
85 BIO_free(p);
86 }
87};
88typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
89
90struct EVP_PKEY_Delete {
91 void operator()(EVP_PKEY* p) const {
92 EVP_PKEY_free(p);
93 }
94};
95typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
96
97struct PKCS8_PRIV_KEY_INFO_Delete {
98 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
99 PKCS8_PRIV_KEY_INFO_free(p);
100 }
101};
102typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
103
104
Kenny Root70e3a862012-02-15 17:20:23 -0800105static int keymaster_device_initialize(keymaster_device_t** dev) {
106 int rc;
107
108 const hw_module_t* mod;
109 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
110 if (rc) {
111 ALOGE("could not find any keystore module");
112 goto out;
113 }
114
115 rc = keymaster_open(mod, dev);
116 if (rc) {
117 ALOGE("could not open keymaster device in %s (%s)",
118 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
119 goto out;
120 }
121
122 return 0;
123
124out:
125 *dev = NULL;
126 return rc;
127}
128
129static void keymaster_device_release(keymaster_device_t* dev) {
130 keymaster_close(dev);
131}
132
Kenny Root07438c82012-11-02 15:41:02 -0700133/***************
134 * PERMISSIONS *
135 ***************/
136
137/* Here are the permissions, actions, users, and the main function. */
138typedef enum {
Robin Lee4e865752014-08-19 17:37:55 +0100139 P_TEST = 1 << 0,
140 P_GET = 1 << 1,
141 P_INSERT = 1 << 2,
142 P_DELETE = 1 << 3,
143 P_EXIST = 1 << 4,
144 P_SAW = 1 << 5,
145 P_RESET = 1 << 6,
146 P_PASSWORD = 1 << 7,
147 P_LOCK = 1 << 8,
148 P_UNLOCK = 1 << 9,
149 P_ZERO = 1 << 10,
150 P_SIGN = 1 << 11,
151 P_VERIFY = 1 << 12,
152 P_GRANT = 1 << 13,
153 P_DUPLICATE = 1 << 14,
154 P_CLEAR_UID = 1 << 15,
155 P_RESET_UID = 1 << 16,
156 P_SYNC_UID = 1 << 17,
157 P_PASSWORD_UID = 1 << 18,
Kenny Root07438c82012-11-02 15:41:02 -0700158} perm_t;
159
160static struct user_euid {
161 uid_t uid;
162 uid_t euid;
163} user_euids[] = {
164 {AID_VPN, AID_SYSTEM},
165 {AID_WIFI, AID_SYSTEM},
166 {AID_ROOT, AID_SYSTEM},
167};
168
Riley Spahneaabae92014-06-30 12:39:52 -0700169/* perm_labels associcated with keystore_key SELinux class verbs. */
170const char *perm_labels[] = {
171 "test",
172 "get",
173 "insert",
174 "delete",
175 "exist",
176 "saw",
177 "reset",
178 "password",
179 "lock",
180 "unlock",
181 "zero",
182 "sign",
183 "verify",
184 "grant",
185 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100186 "clear_uid",
187 "reset_uid",
188 "sync_uid",
189 "password_uid",
Riley Spahneaabae92014-06-30 12:39:52 -0700190};
191
Kenny Root07438c82012-11-02 15:41:02 -0700192static struct user_perm {
193 uid_t uid;
194 perm_t perms;
195} user_perms[] = {
196 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
197 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
198 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
199 {AID_ROOT, static_cast<perm_t>(P_GET) },
200};
201
202static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
203 | P_VERIFY);
204
Riley Spahneaabae92014-06-30 12:39:52 -0700205static char *tctx;
206static int ks_is_selinux_enabled;
207
208static const char *get_perm_label(perm_t perm) {
209 unsigned int index = ffs(perm);
210 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
211 return perm_labels[index - 1];
212 } else {
213 ALOGE("Keystore: Failed to retrieve permission label.\n");
214 abort();
215 }
216}
217
Kenny Root655b9582013-04-04 08:37:42 -0700218/**
219 * Returns the app ID (in the Android multi-user sense) for the current
220 * UNIX UID.
221 */
222static uid_t get_app_id(uid_t uid) {
223 return uid % AID_USER;
224}
225
226/**
227 * Returns the user ID (in the Android multi-user sense) for the current
228 * UNIX UID.
229 */
230static uid_t get_user_id(uid_t uid) {
231 return uid / AID_USER;
232}
233
Riley Spahneaabae92014-06-30 12:39:52 -0700234static bool keystore_selinux_check_access(uid_t uid, perm_t perm, pid_t spid) {
235 if (!ks_is_selinux_enabled) {
236 return true;
237 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000238
Riley Spahneaabae92014-06-30 12:39:52 -0700239 char *sctx = NULL;
240 const char *selinux_class = "keystore_key";
241 const char *str_perm = get_perm_label(perm);
242
243 if (!str_perm) {
244 return false;
245 }
246
247 if (getpidcon(spid, &sctx) != 0) {
248 ALOGE("SELinux: Failed to get source pid context.\n");
249 return false;
250 }
251
252 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
253 NULL) == 0;
254 freecon(sctx);
255 return allowed;
256}
257
258static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700259 // All system users are equivalent for multi-user support.
260 if (get_app_id(uid) == AID_SYSTEM) {
261 uid = AID_SYSTEM;
262 }
263
Kenny Root07438c82012-11-02 15:41:02 -0700264 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
265 struct user_perm user = user_perms[i];
266 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700267 return (user.perms & perm) &&
268 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700269 }
270 }
271
Riley Spahneaabae92014-06-30 12:39:52 -0700272 return (DEFAULT_PERMS & perm) &&
273 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700274}
275
Kenny Root49468902013-03-19 13:41:33 -0700276/**
277 * Returns the UID that the callingUid should act as. This is here for
278 * legacy support of the WiFi and VPN systems and should be removed
279 * when WiFi can operate in its own namespace.
280 */
Kenny Root07438c82012-11-02 15:41:02 -0700281static uid_t get_keystore_euid(uid_t uid) {
282 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
283 struct user_euid user = user_euids[i];
284 if (user.uid == uid) {
285 return user.euid;
286 }
287 }
288
289 return uid;
290}
291
Kenny Root49468902013-03-19 13:41:33 -0700292/**
293 * Returns true if the callingUid is allowed to interact in the targetUid's
294 * namespace.
295 */
296static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
297 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
298 struct user_euid user = user_euids[i];
299 if (user.euid == callingUid && user.uid == targetUid) {
300 return true;
301 }
302 }
303
304 return false;
305}
306
Kenny Root007cb232014-07-30 16:59:42 -0700307/**
308 * Allow the system to perform some privileged tasks that have to do with
309 * system maintenance. This should not be used for any function that uses
310 * the keys in any way (e.g., signing).
311 */
312static bool is_self_or_system(uid_t callingUid, uid_t targetUid) {
313 return callingUid == targetUid || callingUid == AID_SYSTEM;
314}
315
Kenny Roota91203b2012-02-15 15:00:46 -0800316/* Here is the encoding of keys. This is necessary in order to allow arbitrary
317 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
318 * into two bytes. The first byte is one of [+-.] which represents the first
319 * two bits of the character. The second byte encodes the rest of the bits into
320 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
321 * that Base64 cannot be used here due to the need of prefix match on keys. */
322
Kenny Root655b9582013-04-04 08:37:42 -0700323static size_t encode_key_length(const android::String8& keyName) {
324 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
325 size_t length = keyName.length();
326 for (int i = length; i > 0; --i, ++in) {
327 if (*in < '0' || *in > '~') {
328 ++length;
329 }
330 }
331 return length;
332}
333
Kenny Root07438c82012-11-02 15:41:02 -0700334static int encode_key(char* out, const android::String8& keyName) {
335 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
336 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800337 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700338 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800339 *out = '+' + (*in >> 6);
340 *++out = '0' + (*in & 0x3F);
341 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700342 } else {
343 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800344 }
345 }
346 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800347 return length;
348}
349
Kenny Root07438c82012-11-02 15:41:02 -0700350/*
351 * Converts from the "escaped" format on disk to actual name.
352 * This will be smaller than the input string.
353 *
354 * Characters that should combine with the next at the end will be truncated.
355 */
356static size_t decode_key_length(const char* in, size_t length) {
357 size_t outLength = 0;
358
359 for (const char* end = in + length; in < end; in++) {
360 /* This combines with the next character. */
361 if (*in < '0' || *in > '~') {
362 continue;
363 }
364
365 outLength++;
366 }
367 return outLength;
368}
369
370static void decode_key(char* out, const char* in, size_t length) {
371 for (const char* end = in + length; in < end; in++) {
372 if (*in < '0' || *in > '~') {
373 /* Truncate combining characters at the end. */
374 if (in + 1 >= end) {
375 break;
376 }
377
378 *out = (*in++ - '+') << 6;
379 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800380 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700381 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800382 }
383 }
384 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800385}
386
387static size_t readFully(int fd, uint8_t* data, size_t size) {
388 size_t remaining = size;
389 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800390 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800391 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800392 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800393 }
394 data += n;
395 remaining -= n;
396 }
397 return size;
398}
399
400static size_t writeFully(int fd, uint8_t* data, size_t size) {
401 size_t remaining = size;
402 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800403 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
404 if (n < 0) {
405 ALOGW("write failed: %s", strerror(errno));
406 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800407 }
408 data += n;
409 remaining -= n;
410 }
411 return size;
412}
413
414class Entropy {
415public:
416 Entropy() : mRandom(-1) {}
417 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800418 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800419 close(mRandom);
420 }
421 }
422
423 bool open() {
424 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800425 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
426 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800427 ALOGE("open: %s: %s", randomDevice, strerror(errno));
428 return false;
429 }
430 return true;
431 }
432
Kenny Root51878182012-03-13 12:53:19 -0700433 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800434 return (readFully(mRandom, data, size) == size);
435 }
436
437private:
438 int mRandom;
439};
440
441/* Here is the file format. There are two parts in blob.value, the secret and
442 * the description. The secret is stored in ciphertext, and its original size
443 * can be found in blob.length. The description is stored after the secret in
444 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700445 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700446 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800447 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
448 * and decryptBlob(). Thus they should not be accessed from outside. */
449
Kenny Root822c3a92012-03-23 16:34:39 -0700450/* ** Note to future implementors of encryption: **
451 * Currently this is the construction:
452 * metadata || Enc(MD5(data) || data)
453 *
454 * This should be the construction used for encrypting if re-implementing:
455 *
456 * Derive independent keys for encryption and MAC:
457 * Kenc = AES_encrypt(masterKey, "Encrypt")
458 * Kmac = AES_encrypt(masterKey, "MAC")
459 *
460 * Store this:
461 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
462 * HMAC(Kmac, metadata || Enc(data))
463 */
Kenny Roota91203b2012-02-15 15:00:46 -0800464struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700465 uint8_t version;
466 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700467 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800468 uint8_t info;
469 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700470 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800471 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700472 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800473 int32_t length; // in network byte order when encrypted
474 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
475};
476
Kenny Root822c3a92012-03-23 16:34:39 -0700477typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700478 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700479 TYPE_GENERIC = 1,
480 TYPE_MASTER_KEY = 2,
481 TYPE_KEY_PAIR = 3,
482} BlobType;
483
Kenny Rootf9119d62013-04-03 09:22:15 -0700484static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700485
Kenny Roota91203b2012-02-15 15:00:46 -0800486class Blob {
487public:
Chad Brubaker77335322015-07-29 13:53:36 -0700488 Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
Kenny Root07438c82012-11-02 15:41:02 -0700489 BlobType type) {
Chad Brubaker2cbc1072015-08-12 13:40:31 -0700490 if (valueLength > VALUE_SIZE) {
491 valueLength = VALUE_SIZE;
Chad Brubaker77335322015-07-29 13:53:36 -0700492 ALOGW("Provided blob length too large");
493 }
Chad Brubaker2cbc1072015-08-12 13:40:31 -0700494 if (infoLength + valueLength > VALUE_SIZE) {
495 infoLength = VALUE_SIZE - valueLength;
Chad Brubaker77335322015-07-29 13:53:36 -0700496 ALOGW("Provided info length too large");
497 }
Kenny Roota91203b2012-02-15 15:00:46 -0800498 mBlob.length = valueLength;
499 memcpy(mBlob.value, value, valueLength);
500
501 mBlob.info = infoLength;
502 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700503
Kenny Root07438c82012-11-02 15:41:02 -0700504 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700505 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700506
Kenny Rootee8068b2013-10-07 09:49:15 -0700507 if (type == TYPE_MASTER_KEY) {
508 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
509 } else {
510 mBlob.flags = KEYSTORE_FLAG_NONE;
511 }
Kenny Roota91203b2012-02-15 15:00:46 -0800512 }
513
514 Blob(blob b) {
515 mBlob = b;
516 }
517
518 Blob() {}
519
Kenny Root51878182012-03-13 12:53:19 -0700520 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800521 return mBlob.value;
522 }
523
Kenny Root51878182012-03-13 12:53:19 -0700524 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800525 return mBlob.length;
526 }
527
Kenny Root51878182012-03-13 12:53:19 -0700528 const uint8_t* getInfo() const {
529 return mBlob.value + mBlob.length;
530 }
531
532 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800533 return mBlob.info;
534 }
535
Kenny Root822c3a92012-03-23 16:34:39 -0700536 uint8_t getVersion() const {
537 return mBlob.version;
538 }
539
Kenny Rootf9119d62013-04-03 09:22:15 -0700540 bool isEncrypted() const {
541 if (mBlob.version < 2) {
542 return true;
543 }
544
545 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
546 }
547
548 void setEncrypted(bool encrypted) {
549 if (encrypted) {
550 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
551 } else {
552 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
553 }
554 }
555
Kenny Root17208e02013-09-04 13:56:03 -0700556 bool isFallback() const {
557 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
558 }
559
560 void setFallback(bool fallback) {
561 if (fallback) {
562 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
563 } else {
564 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
565 }
566 }
567
Kenny Root822c3a92012-03-23 16:34:39 -0700568 void setVersion(uint8_t version) {
569 mBlob.version = version;
570 }
571
572 BlobType getType() const {
573 return BlobType(mBlob.type);
574 }
575
576 void setType(BlobType type) {
577 mBlob.type = uint8_t(type);
578 }
579
Kenny Rootf9119d62013-04-03 09:22:15 -0700580 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
581 ALOGV("writing blob %s", filename);
582 if (isEncrypted()) {
583 if (state != STATE_NO_ERROR) {
584 ALOGD("couldn't insert encrypted blob while not unlocked");
585 return LOCKED;
586 }
587
588 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
589 ALOGW("Could not read random data for: %s", filename);
590 return SYSTEM_ERROR;
591 }
Kenny Roota91203b2012-02-15 15:00:46 -0800592 }
593
594 // data includes the value and the value's length
595 size_t dataLength = mBlob.length + sizeof(mBlob.length);
596 // pad data to the AES_BLOCK_SIZE
597 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
598 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
599 // encrypted data includes the digest value
600 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
601 // move info after space for padding
602 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
603 // zero padding area
604 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
605
606 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800607
Kenny Rootf9119d62013-04-03 09:22:15 -0700608 if (isEncrypted()) {
609 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800610
Kenny Rootf9119d62013-04-03 09:22:15 -0700611 uint8_t vector[AES_BLOCK_SIZE];
612 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
613 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
614 aes_key, vector, AES_ENCRYPT);
615 }
616
Kenny Roota91203b2012-02-15 15:00:46 -0800617 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
618 size_t fileLength = encryptedLength + headerLength + mBlob.info;
619
620 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800621 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
622 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
623 if (out < 0) {
624 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800625 return SYSTEM_ERROR;
626 }
627 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
628 if (close(out) != 0) {
629 return SYSTEM_ERROR;
630 }
631 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800632 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800633 unlink(tmpFileName);
634 return SYSTEM_ERROR;
635 }
Kenny Root150ca932012-11-14 14:29:02 -0800636 if (rename(tmpFileName, filename) == -1) {
637 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
638 return SYSTEM_ERROR;
639 }
640 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800641 }
642
Kenny Rootf9119d62013-04-03 09:22:15 -0700643 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
644 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800645 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
646 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800647 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
648 }
649 // fileLength may be less than sizeof(mBlob) since the in
650 // memory version has extra padding to tolerate rounding up to
651 // the AES_BLOCK_SIZE
652 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
653 if (close(in) != 0) {
654 return SYSTEM_ERROR;
655 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700656
657 if (isEncrypted() && (state != STATE_NO_ERROR)) {
658 return LOCKED;
659 }
660
Kenny Roota91203b2012-02-15 15:00:46 -0800661 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
662 if (fileLength < headerLength) {
663 return VALUE_CORRUPTED;
664 }
665
666 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700667 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800668 return VALUE_CORRUPTED;
669 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700670
671 ssize_t digestedLength;
672 if (isEncrypted()) {
673 if (encryptedLength % AES_BLOCK_SIZE != 0) {
674 return VALUE_CORRUPTED;
675 }
676
677 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
678 mBlob.vector, AES_DECRYPT);
679 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
680 uint8_t computedDigest[MD5_DIGEST_LENGTH];
681 MD5(mBlob.digested, digestedLength, computedDigest);
682 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
683 return VALUE_CORRUPTED;
684 }
685 } else {
686 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800687 }
688
689 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
690 mBlob.length = ntohl(mBlob.length);
691 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
692 return VALUE_CORRUPTED;
693 }
694 if (mBlob.info != 0) {
695 // move info from after padding to after data
696 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
697 }
Kenny Root07438c82012-11-02 15:41:02 -0700698 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800699 }
700
701private:
702 struct blob mBlob;
703};
704
Kenny Root655b9582013-04-04 08:37:42 -0700705class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800706public:
Kenny Root655b9582013-04-04 08:37:42 -0700707 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
708 asprintf(&mUserDir, "user_%u", mUserId);
709 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
710 }
711
712 ~UserState() {
713 free(mUserDir);
714 free(mMasterKeyFile);
715 }
716
717 bool initialize() {
718 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
719 ALOGE("Could not create directory '%s'", mUserDir);
720 return false;
721 }
722
723 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800724 setState(STATE_LOCKED);
725 } else {
726 setState(STATE_UNINITIALIZED);
727 }
Kenny Root70e3a862012-02-15 17:20:23 -0800728
Kenny Root655b9582013-04-04 08:37:42 -0700729 return true;
730 }
731
732 uid_t getUserId() const {
733 return mUserId;
734 }
735
736 const char* getUserDirName() const {
737 return mUserDir;
738 }
739
740 const char* getMasterKeyFileName() const {
741 return mMasterKeyFile;
742 }
743
744 void setState(State state) {
745 mState = state;
746 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
747 mRetry = MAX_RETRY;
748 }
Kenny Roota91203b2012-02-15 15:00:46 -0800749 }
750
Kenny Root51878182012-03-13 12:53:19 -0700751 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800752 return mState;
753 }
754
Kenny Root51878182012-03-13 12:53:19 -0700755 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800756 return mRetry;
757 }
758
Kenny Root655b9582013-04-04 08:37:42 -0700759 void zeroizeMasterKeysInMemory() {
760 memset(mMasterKey, 0, sizeof(mMasterKey));
761 memset(mSalt, 0, sizeof(mSalt));
762 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
763 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800764 }
765
Kenny Root655b9582013-04-04 08:37:42 -0700766 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
767 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800768 return SYSTEM_ERROR;
769 }
Kenny Root655b9582013-04-04 08:37:42 -0700770 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800771 if (response != NO_ERROR) {
772 return response;
773 }
774 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700775 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800776 }
777
Robin Lee4e865752014-08-19 17:37:55 +0100778 ResponseCode copyMasterKey(UserState* src) {
779 if (mState != STATE_UNINITIALIZED) {
780 return ::SYSTEM_ERROR;
781 }
782 if (src->getState() != STATE_NO_ERROR) {
783 return ::SYSTEM_ERROR;
784 }
785 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
786 setupMasterKeys();
787 return ::NO_ERROR;
788 }
789
Kenny Root655b9582013-04-04 08:37:42 -0700790 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800791 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
792 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
793 AES_KEY passwordAesKey;
794 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700795 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700796 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800797 }
798
Kenny Root655b9582013-04-04 08:37:42 -0700799 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
800 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800801 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800802 return SYSTEM_ERROR;
803 }
804
805 // we read the raw blob to just to get the salt to generate
806 // the AES key, then we create the Blob to use with decryptBlob
807 blob rawBlob;
808 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
809 if (close(in) != 0) {
810 return SYSTEM_ERROR;
811 }
812 // find salt at EOF if present, otherwise we have an old file
813 uint8_t* salt;
814 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
815 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
816 } else {
817 salt = NULL;
818 }
819 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
820 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
821 AES_KEY passwordAesKey;
822 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
823 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700824 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
825 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800826 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700827 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800828 }
829 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
830 // if salt was missing, generate one and write a new master key file with the salt.
831 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700832 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800833 return SYSTEM_ERROR;
834 }
Kenny Root655b9582013-04-04 08:37:42 -0700835 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800836 }
837 if (response == NO_ERROR) {
838 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
839 setupMasterKeys();
840 }
841 return response;
842 }
843 if (mRetry <= 0) {
844 reset();
845 return UNINITIALIZED;
846 }
847 --mRetry;
848 switch (mRetry) {
849 case 0: return WRONG_PASSWORD_0;
850 case 1: return WRONG_PASSWORD_1;
851 case 2: return WRONG_PASSWORD_2;
852 case 3: return WRONG_PASSWORD_3;
853 default: return WRONG_PASSWORD_3;
854 }
855 }
856
Kenny Root655b9582013-04-04 08:37:42 -0700857 AES_KEY* getEncryptionKey() {
858 return &mMasterKeyEncryption;
859 }
860
861 AES_KEY* getDecryptionKey() {
862 return &mMasterKeyDecryption;
863 }
864
Kenny Roota91203b2012-02-15 15:00:46 -0800865 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700866 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800867 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700868 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800869 return false;
870 }
Kenny Root655b9582013-04-04 08:37:42 -0700871
872 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800873 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700874 // We only care about files.
875 if (file->d_type != DT_REG) {
876 continue;
877 }
878
879 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700880 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700881 continue;
882 }
883
884 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800885 }
886 closedir(dir);
887 return true;
888 }
889
Kenny Root655b9582013-04-04 08:37:42 -0700890private:
891 static const int MASTER_KEY_SIZE_BYTES = 16;
892 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
893
894 static const int MAX_RETRY = 4;
895 static const size_t SALT_SIZE = 16;
896
897 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
898 uint8_t* salt) {
899 size_t saltSize;
900 if (salt != NULL) {
901 saltSize = SALT_SIZE;
902 } else {
903 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
904 salt = (uint8_t*) "keystore";
905 // sizeof = 9, not strlen = 8
906 saltSize = sizeof("keystore");
907 }
908
909 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
910 saltSize, 8192, keySize, key);
911 }
912
913 bool generateSalt(Entropy* entropy) {
914 return entropy->generate_random_data(mSalt, sizeof(mSalt));
915 }
916
917 bool generateMasterKey(Entropy* entropy) {
918 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
919 return false;
920 }
921 if (!generateSalt(entropy)) {
922 return false;
923 }
924 return true;
925 }
926
927 void setupMasterKeys() {
928 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
929 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
930 setState(STATE_NO_ERROR);
931 }
932
933 uid_t mUserId;
934
935 char* mUserDir;
936 char* mMasterKeyFile;
937
938 State mState;
939 int8_t mRetry;
940
941 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
942 uint8_t mSalt[SALT_SIZE];
943
944 AES_KEY mMasterKeyEncryption;
945 AES_KEY mMasterKeyDecryption;
946};
947
948typedef struct {
949 uint32_t uid;
950 const uint8_t* filename;
951} grant_t;
952
953class KeyStore {
954public:
955 KeyStore(Entropy* entropy, keymaster_device_t* device)
956 : mEntropy(entropy)
957 , mDevice(device)
958 {
959 memset(&mMetaData, '\0', sizeof(mMetaData));
960 }
961
962 ~KeyStore() {
963 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
964 it != mGrants.end(); it++) {
965 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700966 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800967 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700968
969 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
970 it != mMasterKeys.end(); it++) {
971 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700972 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800973 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700974 }
975
976 keymaster_device_t* getDevice() const {
977 return mDevice;
978 }
979
980 ResponseCode initialize() {
981 readMetaData();
982 if (upgradeKeystore()) {
983 writeMetaData();
984 }
985
986 return ::NO_ERROR;
987 }
988
989 State getState(uid_t uid) {
990 return getUserState(uid)->getState();
991 }
992
993 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
994 UserState* userState = getUserState(uid);
995 return userState->initialize(pw, mEntropy);
996 }
997
Robin Lee4e865752014-08-19 17:37:55 +0100998 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
999 UserState *userState = getUserState(uid);
1000 UserState *initState = getUserState(src);
1001 return userState->copyMasterKey(initState);
1002 }
1003
Kenny Root655b9582013-04-04 08:37:42 -07001004 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001005 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001006 return userState->writeMasterKey(pw, mEntropy);
1007 }
1008
1009 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001010 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001011 return userState->readMasterKey(pw, mEntropy);
1012 }
1013
1014 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001015 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001016 encode_key(encoded, keyName);
1017 return android::String8(encoded);
1018 }
1019
1020 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001021 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001022 encode_key(encoded, keyName);
1023 return android::String8::format("%u_%s", uid, encoded);
1024 }
1025
1026 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001027 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001028 encode_key(encoded, keyName);
1029 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1030 encoded);
1031 }
1032
1033 bool reset(uid_t uid) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001034 android::String8 prefix("");
1035 android::Vector<android::String16> aliases;
1036 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1037 return ::SYSTEM_ERROR;
1038 }
1039
Kenny Root655b9582013-04-04 08:37:42 -07001040 UserState* userState = getUserState(uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001041 for (uint32_t i = 0; i < aliases.size(); i++) {
1042 android::String8 filename(aliases[i]);
1043 filename = android::String8::format("%s/%s", userState->getUserDirName(),
1044 getKeyName(filename).string());
1045 del(filename, ::TYPE_ANY, uid);
1046 }
1047
Kenny Root655b9582013-04-04 08:37:42 -07001048 userState->zeroizeMasterKeysInMemory();
1049 userState->setState(STATE_UNINITIALIZED);
1050 return userState->reset();
1051 }
1052
1053 bool isEmpty(uid_t uid) const {
1054 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001055 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001056 return true;
1057 }
1058
1059 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001060 if (!dir) {
1061 return true;
1062 }
Kenny Root31e27462014-09-10 11:28:03 -07001063
Kenny Roota91203b2012-02-15 15:00:46 -08001064 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001065 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001066 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001067 // We only care about files.
1068 if (file->d_type != DT_REG) {
1069 continue;
1070 }
1071
1072 // Skip anything that starts with a "."
1073 if (file->d_name[0] == '.') {
1074 continue;
1075 }
1076
Kenny Root31e27462014-09-10 11:28:03 -07001077 result = false;
1078 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001079 }
1080 closedir(dir);
1081 return result;
1082 }
1083
Kenny Root655b9582013-04-04 08:37:42 -07001084 void lock(uid_t uid) {
1085 UserState* userState = getUserState(uid);
1086 userState->zeroizeMasterKeysInMemory();
1087 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001088 }
1089
Kenny Root655b9582013-04-04 08:37:42 -07001090 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1091 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001092 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1093 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001094 if (rc != NO_ERROR) {
1095 return rc;
1096 }
1097
1098 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001099 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001100 /* If we upgrade the key, we need to write it to disk again. Then
1101 * it must be read it again since the blob is encrypted each time
1102 * it's written.
1103 */
Kenny Root655b9582013-04-04 08:37:42 -07001104 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1105 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001106 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1107 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001108 return rc;
1109 }
1110 }
Kenny Root822c3a92012-03-23 16:34:39 -07001111 }
1112
Kenny Root17208e02013-09-04 13:56:03 -07001113 /*
1114 * This will upgrade software-backed keys to hardware-backed keys when
1115 * the HAL for the device supports the newer key types.
1116 */
1117 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1118 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1119 && keyBlob->isFallback()) {
1120 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1121 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1122
1123 // The HAL allowed the import, reget the key to have the "fresh"
1124 // version.
1125 if (imported == NO_ERROR) {
1126 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1127 }
1128 }
1129
Kenny Rootd53bc922013-03-21 14:10:15 -07001130 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001131 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1132 return KEY_NOT_FOUND;
1133 }
1134
1135 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001136 }
1137
Kenny Root655b9582013-04-04 08:37:42 -07001138 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1139 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001140 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1141 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001142 }
1143
Robin Lee4b84fdc2014-09-24 11:56:57 +01001144 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1145 Blob keyBlob;
1146 ResponseCode rc = get(filename, &keyBlob, type, uid);
1147 if (rc != ::NO_ERROR) {
1148 return rc;
1149 }
1150
1151 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1152 // A device doesn't have to implement delete_keypair.
1153 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1154 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1155 rc = ::SYSTEM_ERROR;
1156 }
1157 }
1158 }
1159 if (rc != ::NO_ERROR) {
1160 return rc;
1161 }
1162
1163 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1164 }
1165
1166 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1167 uid_t uid) {
1168
1169 UserState* userState = getUserState(uid);
1170 size_t n = prefix.length();
1171
1172 DIR* dir = opendir(userState->getUserDirName());
1173 if (!dir) {
1174 ALOGW("can't open directory for user: %s", strerror(errno));
1175 return ::SYSTEM_ERROR;
1176 }
1177
1178 struct dirent* file;
1179 while ((file = readdir(dir)) != NULL) {
1180 // We only care about files.
1181 if (file->d_type != DT_REG) {
1182 continue;
1183 }
1184
1185 // Skip anything that starts with a "."
1186 if (file->d_name[0] == '.') {
1187 continue;
1188 }
1189
1190 if (!strncmp(prefix.string(), file->d_name, n)) {
1191 const char* p = &file->d_name[n];
1192 size_t plen = strlen(p);
1193
1194 size_t extra = decode_key_length(p, plen);
1195 char *match = (char*) malloc(extra + 1);
1196 if (match != NULL) {
1197 decode_key(match, p, plen);
1198 matches->push(android::String16(match, extra));
1199 free(match);
1200 } else {
1201 ALOGW("could not allocate match of size %zd", extra);
1202 }
1203 }
1204 }
1205 closedir(dir);
1206 return ::NO_ERROR;
1207 }
1208
Kenny Root07438c82012-11-02 15:41:02 -07001209 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001210 const grant_t* existing = getGrant(filename, granteeUid);
1211 if (existing == NULL) {
1212 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001213 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001214 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001215 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001216 }
1217 }
1218
Kenny Root07438c82012-11-02 15:41:02 -07001219 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001220 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1221 it != mGrants.end(); it++) {
1222 grant_t* grant = *it;
1223 if (grant->uid == granteeUid
1224 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1225 mGrants.erase(it);
1226 return true;
1227 }
Kenny Root70e3a862012-02-15 17:20:23 -08001228 }
Kenny Root70e3a862012-02-15 17:20:23 -08001229 return false;
1230 }
1231
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001232 bool hasGrant(const char* filename, const uid_t uid) const {
1233 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001234 }
1235
Kenny Rootf9119d62013-04-03 09:22:15 -07001236 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1237 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001238 uint8_t* data;
1239 size_t dataLength;
1240 int rc;
1241
1242 if (mDevice->import_keypair == NULL) {
1243 ALOGE("Keymaster doesn't support import!");
1244 return SYSTEM_ERROR;
1245 }
1246
Kenny Root17208e02013-09-04 13:56:03 -07001247 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001248 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001249 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001250 /*
1251 * Maybe the device doesn't support this type of key. Try to use the
1252 * software fallback keymaster implementation. This is a little bit
1253 * lazier than checking the PKCS#8 key type, but the software
1254 * implementation will do that anyway.
1255 */
1256 rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength);
1257 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001258
1259 if (rc) {
1260 ALOGE("Error while importing keypair: %d", rc);
1261 return SYSTEM_ERROR;
1262 }
Kenny Root822c3a92012-03-23 16:34:39 -07001263 }
1264
1265 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1266 free(data);
1267
Kenny Rootf9119d62013-04-03 09:22:15 -07001268 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001269 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001270
Kenny Root655b9582013-04-04 08:37:42 -07001271 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001272 }
1273
Kenny Root1b0e3932013-09-05 13:06:32 -07001274 bool isHardwareBacked(const android::String16& keyType) const {
1275 if (mDevice == NULL) {
1276 ALOGW("can't get keymaster device");
1277 return false;
1278 }
1279
1280 if (sRSAKeyType == keyType) {
1281 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1282 } else {
1283 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1284 && (mDevice->common.module->module_api_version
1285 >= KEYMASTER_MODULE_API_VERSION_0_2);
1286 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001287 }
1288
Kenny Root655b9582013-04-04 08:37:42 -07001289 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1290 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001291 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001292
1293 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1294 if (responseCode == NO_ERROR) {
1295 return responseCode;
1296 }
1297
1298 // If this is one of the legacy UID->UID mappings, use it.
1299 uid_t euid = get_keystore_euid(uid);
1300 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001301 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001302 responseCode = get(filepath8.string(), keyBlob, type, uid);
1303 if (responseCode == NO_ERROR) {
1304 return responseCode;
1305 }
1306 }
1307
1308 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001309 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001310 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001311 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001312 if (end[0] != '_' || end[1] == 0) {
1313 return KEY_NOT_FOUND;
1314 }
Kenny Root86b16e82013-09-09 11:15:54 -07001315 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1316 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001317 if (!hasGrant(filepath8.string(), uid)) {
1318 return responseCode;
1319 }
1320
1321 // It is a granted key. Try to load it.
1322 return get(filepath8.string(), keyBlob, type, uid);
1323 }
1324
1325 /**
1326 * Returns any existing UserState or creates it if it doesn't exist.
1327 */
1328 UserState* getUserState(uid_t uid) {
1329 uid_t userId = get_user_id(uid);
1330
1331 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1332 it != mMasterKeys.end(); it++) {
1333 UserState* state = *it;
1334 if (state->getUserId() == userId) {
1335 return state;
1336 }
1337 }
1338
1339 UserState* userState = new UserState(userId);
1340 if (!userState->initialize()) {
1341 /* There's not much we can do if initialization fails. Trying to
1342 * unlock the keystore for that user will fail as well, so any
1343 * subsequent request for this user will just return SYSTEM_ERROR.
1344 */
1345 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1346 }
1347 mMasterKeys.add(userState);
1348 return userState;
1349 }
1350
1351 /**
1352 * Returns NULL if the UserState doesn't already exist.
1353 */
1354 const UserState* getUserState(uid_t uid) const {
1355 uid_t userId = get_user_id(uid);
1356
1357 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1358 it != mMasterKeys.end(); it++) {
1359 UserState* state = *it;
1360 if (state->getUserId() == userId) {
1361 return state;
1362 }
1363 }
1364
1365 return NULL;
1366 }
1367
Kenny Roota91203b2012-02-15 15:00:46 -08001368private:
Kenny Root655b9582013-04-04 08:37:42 -07001369 static const char* sOldMasterKey;
1370 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001371 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001372 Entropy* mEntropy;
1373
Kenny Root70e3a862012-02-15 17:20:23 -08001374 keymaster_device_t* mDevice;
1375
Kenny Root655b9582013-04-04 08:37:42 -07001376 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001377
Kenny Root655b9582013-04-04 08:37:42 -07001378 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001379
Kenny Root655b9582013-04-04 08:37:42 -07001380 typedef struct {
1381 uint32_t version;
1382 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001383
Kenny Root655b9582013-04-04 08:37:42 -07001384 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001385
Kenny Root655b9582013-04-04 08:37:42 -07001386 const grant_t* getGrant(const char* filename, uid_t uid) const {
1387 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1388 it != mGrants.end(); it++) {
1389 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001390 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001391 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001392 return grant;
1393 }
1394 }
Kenny Root70e3a862012-02-15 17:20:23 -08001395 return NULL;
1396 }
1397
Kenny Root822c3a92012-03-23 16:34:39 -07001398 /**
1399 * Upgrade code. This will upgrade the key from the current version
1400 * to whatever is newest.
1401 */
Kenny Root655b9582013-04-04 08:37:42 -07001402 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1403 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001404 bool updated = false;
1405 uint8_t version = oldVersion;
1406
1407 /* From V0 -> V1: All old types were unknown */
1408 if (version == 0) {
1409 ALOGV("upgrading to version 1 and setting type %d", type);
1410
1411 blob->setType(type);
1412 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001413 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001414 }
1415 version = 1;
1416 updated = true;
1417 }
1418
Kenny Rootf9119d62013-04-03 09:22:15 -07001419 /* From V1 -> V2: All old keys were encrypted */
1420 if (version == 1) {
1421 ALOGV("upgrading to version 2");
1422
1423 blob->setEncrypted(true);
1424 version = 2;
1425 updated = true;
1426 }
1427
Kenny Root822c3a92012-03-23 16:34:39 -07001428 /*
1429 * If we've updated, set the key blob to the right version
1430 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001431 */
Kenny Root822c3a92012-03-23 16:34:39 -07001432 if (updated) {
1433 ALOGV("updated and writing file %s", filename);
1434 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001435 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001436
1437 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001438 }
1439
1440 /**
1441 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1442 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1443 * Then it overwrites the original blob with the new blob
1444 * format that is returned from the keymaster.
1445 */
Kenny Root655b9582013-04-04 08:37:42 -07001446 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001447 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1448 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1449 if (b.get() == NULL) {
1450 ALOGE("Problem instantiating BIO");
1451 return SYSTEM_ERROR;
1452 }
1453
1454 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1455 if (pkey.get() == NULL) {
1456 ALOGE("Couldn't read old PEM file");
1457 return SYSTEM_ERROR;
1458 }
1459
1460 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1461 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1462 if (len < 0) {
1463 ALOGE("Couldn't measure PKCS#8 length");
1464 return SYSTEM_ERROR;
1465 }
1466
Kenny Root70c98892013-02-07 09:10:36 -08001467 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1468 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001469 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1470 ALOGE("Couldn't convert to PKCS#8");
1471 return SYSTEM_ERROR;
1472 }
1473
Kenny Rootf9119d62013-04-03 09:22:15 -07001474 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1475 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001476 if (rc != NO_ERROR) {
1477 return rc;
1478 }
1479
Kenny Root655b9582013-04-04 08:37:42 -07001480 return get(filename, blob, TYPE_KEY_PAIR, uid);
1481 }
1482
1483 void readMetaData() {
1484 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1485 if (in < 0) {
1486 return;
1487 }
1488 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1489 if (fileLength != sizeof(mMetaData)) {
1490 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1491 sizeof(mMetaData));
1492 }
1493 close(in);
1494 }
1495
1496 void writeMetaData() {
1497 const char* tmpFileName = ".metadata.tmp";
1498 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1499 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1500 if (out < 0) {
1501 ALOGE("couldn't write metadata file: %s", strerror(errno));
1502 return;
1503 }
1504 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1505 if (fileLength != sizeof(mMetaData)) {
1506 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1507 sizeof(mMetaData));
1508 }
1509 close(out);
1510 rename(tmpFileName, sMetaDataFile);
1511 }
1512
1513 bool upgradeKeystore() {
1514 bool upgraded = false;
1515
1516 if (mMetaData.version == 0) {
1517 UserState* userState = getUserState(0);
1518
1519 // Initialize first so the directory is made.
1520 userState->initialize();
1521
1522 // Migrate the old .masterkey file to user 0.
1523 if (access(sOldMasterKey, R_OK) == 0) {
1524 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1525 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1526 return false;
1527 }
1528 }
1529
1530 // Initialize again in case we had a key.
1531 userState->initialize();
1532
1533 // Try to migrate existing keys.
1534 DIR* dir = opendir(".");
1535 if (!dir) {
1536 // Give up now; maybe we can upgrade later.
1537 ALOGE("couldn't open keystore's directory; something is wrong");
1538 return false;
1539 }
1540
1541 struct dirent* file;
1542 while ((file = readdir(dir)) != NULL) {
1543 // We only care about files.
1544 if (file->d_type != DT_REG) {
1545 continue;
1546 }
1547
1548 // Skip anything that starts with a "."
1549 if (file->d_name[0] == '.') {
1550 continue;
1551 }
1552
1553 // Find the current file's user.
1554 char* end;
1555 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1556 if (end[0] != '_' || end[1] == 0) {
1557 continue;
1558 }
1559 UserState* otherUser = getUserState(thisUid);
1560 if (otherUser->getUserId() != 0) {
1561 unlinkat(dirfd(dir), file->d_name, 0);
1562 }
1563
1564 // Rename the file into user directory.
1565 DIR* otherdir = opendir(otherUser->getUserDirName());
1566 if (otherdir == NULL) {
1567 ALOGW("couldn't open user directory for rename");
1568 continue;
1569 }
1570 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1571 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1572 }
1573 closedir(otherdir);
1574 }
1575 closedir(dir);
1576
1577 mMetaData.version = 1;
1578 upgraded = true;
1579 }
1580
1581 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001582 }
Kenny Roota91203b2012-02-15 15:00:46 -08001583};
1584
Kenny Root655b9582013-04-04 08:37:42 -07001585const char* KeyStore::sOldMasterKey = ".masterkey";
1586const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001587
Kenny Root1b0e3932013-09-05 13:06:32 -07001588const android::String16 KeyStore::sRSAKeyType("RSA");
1589
Kenny Root07438c82012-11-02 15:41:02 -07001590namespace android {
1591class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1592public:
1593 KeyStoreProxy(KeyStore* keyStore)
1594 : mKeyStore(keyStore)
1595 {
Kenny Roota91203b2012-02-15 15:00:46 -08001596 }
Kenny Roota91203b2012-02-15 15:00:46 -08001597
Kenny Root07438c82012-11-02 15:41:02 -07001598 void binderDied(const wp<IBinder>&) {
1599 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001600 }
Kenny Roota91203b2012-02-15 15:00:46 -08001601
Kenny Root07438c82012-11-02 15:41:02 -07001602 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001603 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001604 pid_t spid = IPCThreadState::self()->getCallingPid();
1605 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001606 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001607 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001608 }
Kenny Roota91203b2012-02-15 15:00:46 -08001609
Kenny Root655b9582013-04-04 08:37:42 -07001610 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001611 }
1612
Kenny Root07438c82012-11-02 15:41:02 -07001613 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001614 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001615 pid_t spid = IPCThreadState::self()->getCallingPid();
1616 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001617 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001618 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001619 }
Kenny Root07438c82012-11-02 15:41:02 -07001620
Kenny Root07438c82012-11-02 15:41:02 -07001621 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001622 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001623
Kenny Root655b9582013-04-04 08:37:42 -07001624 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001625 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001626 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001627 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001628 *item = NULL;
1629 *itemLength = 0;
1630 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001631 }
Kenny Roota91203b2012-02-15 15:00:46 -08001632
Kenny Root07438c82012-11-02 15:41:02 -07001633 *item = (uint8_t*) malloc(keyBlob.getLength());
1634 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1635 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001636
Kenny Root07438c82012-11-02 15:41:02 -07001637 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001638 }
1639
Kenny Rootf9119d62013-04-03 09:22:15 -07001640 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1641 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001642 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001643 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001644 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001645 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001646 return ::PERMISSION_DENIED;
1647 }
Kenny Root07438c82012-11-02 15:41:02 -07001648
Kenny Rootf9119d62013-04-03 09:22:15 -07001649 State state = mKeyStore->getState(callingUid);
1650 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1651 ALOGD("calling get in state: %d", state);
1652 return state;
1653 }
1654
Kenny Root49468902013-03-19 13:41:33 -07001655 if (targetUid == -1) {
1656 targetUid = callingUid;
1657 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001658 return ::PERMISSION_DENIED;
1659 }
1660
Kenny Root07438c82012-11-02 15:41:02 -07001661 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001662 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001663
1664 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001665 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1666
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001667 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001668 }
1669
Kenny Root49468902013-03-19 13:41:33 -07001670 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001671 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001672 pid_t spid = IPCThreadState::self()->getCallingPid();
1673 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001674 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001675 return ::PERMISSION_DENIED;
1676 }
Kenny Root70e3a862012-02-15 17:20:23 -08001677
Kenny Root49468902013-03-19 13:41:33 -07001678 if (targetUid == -1) {
1679 targetUid = callingUid;
1680 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001681 return ::PERMISSION_DENIED;
1682 }
1683
Kenny Root07438c82012-11-02 15:41:02 -07001684 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001685 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01001686 return mKeyStore->del(filename.string(), ::TYPE_GENERIC, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001687 }
1688
Kenny Root49468902013-03-19 13:41:33 -07001689 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001690 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001691 pid_t spid = IPCThreadState::self()->getCallingPid();
1692 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001693 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001694 return ::PERMISSION_DENIED;
1695 }
Kenny Root70e3a862012-02-15 17:20:23 -08001696
Kenny Root49468902013-03-19 13:41:33 -07001697 if (targetUid == -1) {
1698 targetUid = callingUid;
1699 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001700 return ::PERMISSION_DENIED;
1701 }
1702
Kenny Root07438c82012-11-02 15:41:02 -07001703 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001704 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001705
Kenny Root655b9582013-04-04 08:37:42 -07001706 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001707 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1708 }
1709 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001710 }
1711
Kenny Root49468902013-03-19 13:41:33 -07001712 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001713 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001714 pid_t spid = IPCThreadState::self()->getCallingPid();
1715 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001716 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001717 return ::PERMISSION_DENIED;
1718 }
Kenny Root70e3a862012-02-15 17:20:23 -08001719
Kenny Root49468902013-03-19 13:41:33 -07001720 if (targetUid == -1) {
1721 targetUid = callingUid;
1722 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001723 return ::PERMISSION_DENIED;
1724 }
1725
Kenny Root07438c82012-11-02 15:41:02 -07001726 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001727 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001728
Robin Lee4b84fdc2014-09-24 11:56:57 +01001729 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1730 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001731 }
Kenny Root07438c82012-11-02 15:41:02 -07001732 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001733 }
1734
Kenny Root07438c82012-11-02 15:41:02 -07001735 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001736 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001737 pid_t spid = IPCThreadState::self()->getCallingPid();
1738 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001739 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001740 return ::PERMISSION_DENIED;
1741 }
1742
Robin Lee4b84fdc2014-09-24 11:56:57 +01001743 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001744 }
1745
Kenny Root07438c82012-11-02 15:41:02 -07001746 /*
1747 * Here is the history. To improve the security, the parameters to generate the
1748 * master key has been changed. To make a seamless transition, we update the
1749 * file using the same password when the user unlock it for the first time. If
1750 * any thing goes wrong during the transition, the new file will not overwrite
1751 * the old one. This avoids permanent damages of the existing data.
1752 */
1753 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001754 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001755 pid_t spid = IPCThreadState::self()->getCallingPid();
1756 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001757 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001758 return ::PERMISSION_DENIED;
1759 }
Kenny Root70e3a862012-02-15 17:20:23 -08001760
Kenny Root07438c82012-11-02 15:41:02 -07001761 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001762
Kenny Root655b9582013-04-04 08:37:42 -07001763 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001764 case ::STATE_UNINITIALIZED: {
1765 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001766 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001767 }
1768 case ::STATE_NO_ERROR: {
1769 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001770 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001771 }
1772 case ::STATE_LOCKED: {
1773 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001774 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001775 }
1776 }
1777 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001778 }
1779
Kenny Root07438c82012-11-02 15:41:02 -07001780 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001781 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001782 pid_t spid = IPCThreadState::self()->getCallingPid();
1783 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001784 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001785 return ::PERMISSION_DENIED;
1786 }
Kenny Root70e3a862012-02-15 17:20:23 -08001787
Kenny Root655b9582013-04-04 08:37:42 -07001788 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001789 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001790 ALOGD("calling lock in state: %d", state);
1791 return state;
1792 }
1793
Kenny Root655b9582013-04-04 08:37:42 -07001794 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001795 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001796 }
1797
Kenny Root07438c82012-11-02 15:41:02 -07001798 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001799 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001800 pid_t spid = IPCThreadState::self()->getCallingPid();
1801 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001802 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001803 return ::PERMISSION_DENIED;
1804 }
1805
Kenny Root655b9582013-04-04 08:37:42 -07001806 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001807 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001808 ALOGD("calling unlock when not locked");
1809 return state;
1810 }
1811
1812 const String8 password8(pw);
1813 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001814 }
1815
Kenny Root07438c82012-11-02 15:41:02 -07001816 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001817 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001818 pid_t spid = IPCThreadState::self()->getCallingPid();
1819 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001820 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001821 return -1;
1822 }
Kenny Root70e3a862012-02-15 17:20:23 -08001823
Kenny Root655b9582013-04-04 08:37:42 -07001824 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001825 }
1826
Kenny Root96427ba2013-08-16 14:02:41 -07001827 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1828 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001829 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001830 pid_t spid = IPCThreadState::self()->getCallingPid();
1831 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001832 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001833 return ::PERMISSION_DENIED;
1834 }
Kenny Root70e3a862012-02-15 17:20:23 -08001835
Kenny Root49468902013-03-19 13:41:33 -07001836 if (targetUid == -1) {
1837 targetUid = callingUid;
1838 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001839 return ::PERMISSION_DENIED;
1840 }
1841
Kenny Root655b9582013-04-04 08:37:42 -07001842 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001843 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1844 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001845 return state;
1846 }
Kenny Root70e3a862012-02-15 17:20:23 -08001847
Kenny Root07438c82012-11-02 15:41:02 -07001848 uint8_t* data;
1849 size_t dataLength;
1850 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001851 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001852
1853 const keymaster_device_t* device = mKeyStore->getDevice();
1854 if (device == NULL) {
1855 return ::SYSTEM_ERROR;
1856 }
1857
1858 if (device->generate_keypair == NULL) {
1859 return ::SYSTEM_ERROR;
1860 }
1861
Kenny Root17208e02013-09-04 13:56:03 -07001862 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001863 keymaster_dsa_keygen_params_t dsa_params;
1864 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001865
Kenny Root96427ba2013-08-16 14:02:41 -07001866 if (keySize == -1) {
1867 keySize = DSA_DEFAULT_KEY_SIZE;
1868 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1869 || keySize > DSA_MAX_KEY_SIZE) {
1870 ALOGI("invalid key size %d", keySize);
1871 return ::SYSTEM_ERROR;
1872 }
1873 dsa_params.key_size = keySize;
1874
1875 if (args->size() == 3) {
1876 sp<KeystoreArg> gArg = args->itemAt(0);
1877 sp<KeystoreArg> pArg = args->itemAt(1);
1878 sp<KeystoreArg> qArg = args->itemAt(2);
1879
1880 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1881 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1882 dsa_params.generator_len = gArg->size();
1883
1884 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1885 dsa_params.prime_p_len = pArg->size();
1886
1887 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1888 dsa_params.prime_q_len = qArg->size();
1889 } else {
1890 ALOGI("not all DSA parameters were read");
1891 return ::SYSTEM_ERROR;
1892 }
1893 } else if (args->size() != 0) {
1894 ALOGI("DSA args must be 3");
1895 return ::SYSTEM_ERROR;
1896 }
1897
Kenny Root1d448c02013-11-21 10:36:53 -08001898 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001899 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1900 } else {
1901 isFallback = true;
1902 rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1903 }
1904 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001905 keymaster_ec_keygen_params_t ec_params;
1906 memset(&ec_params, '\0', sizeof(ec_params));
1907
1908 if (keySize == -1) {
1909 keySize = EC_DEFAULT_KEY_SIZE;
1910 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1911 ALOGI("invalid key size %d", keySize);
1912 return ::SYSTEM_ERROR;
1913 }
1914 ec_params.field_size = keySize;
1915
Kenny Root1d448c02013-11-21 10:36:53 -08001916 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001917 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1918 } else {
1919 isFallback = true;
1920 rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1921 }
Kenny Root96427ba2013-08-16 14:02:41 -07001922 } else if (keyType == EVP_PKEY_RSA) {
1923 keymaster_rsa_keygen_params_t rsa_params;
1924 memset(&rsa_params, '\0', sizeof(rsa_params));
1925 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1926
1927 if (keySize == -1) {
1928 keySize = RSA_DEFAULT_KEY_SIZE;
1929 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1930 ALOGI("invalid key size %d", keySize);
1931 return ::SYSTEM_ERROR;
1932 }
1933 rsa_params.modulus_size = keySize;
1934
1935 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001936 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001937 return ::SYSTEM_ERROR;
1938 } else if (args->size() == 1) {
1939 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1940 if (pubExpBlob != NULL) {
1941 Unique_BIGNUM pubExpBn(
1942 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1943 pubExpBlob->size(), NULL));
1944 if (pubExpBn.get() == NULL) {
1945 ALOGI("Could not convert public exponent to BN");
1946 return ::SYSTEM_ERROR;
1947 }
1948 unsigned long pubExp = BN_get_word(pubExpBn.get());
1949 if (pubExp == 0xFFFFFFFFL) {
1950 ALOGI("cannot represent public exponent as a long value");
1951 return ::SYSTEM_ERROR;
1952 }
1953 rsa_params.public_exponent = pubExp;
1954 }
1955 }
1956
1957 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1958 } else {
1959 ALOGW("Unsupported key type %d", keyType);
1960 rc = -1;
1961 }
1962
Kenny Root07438c82012-11-02 15:41:02 -07001963 if (rc) {
1964 return ::SYSTEM_ERROR;
1965 }
1966
Kenny Root655b9582013-04-04 08:37:42 -07001967 String8 name8(name);
1968 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001969
1970 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1971 free(data);
1972
Kenny Rootee8068b2013-10-07 09:49:15 -07001973 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001974 keyBlob.setFallback(isFallback);
1975
Kenny Root655b9582013-04-04 08:37:42 -07001976 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001977 }
1978
Kenny Rootf9119d62013-04-03 09:22:15 -07001979 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1980 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001981 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001982 pid_t spid = IPCThreadState::self()->getCallingPid();
1983 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001984 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001985 return ::PERMISSION_DENIED;
1986 }
Kenny Root07438c82012-11-02 15:41:02 -07001987
Kenny Root49468902013-03-19 13:41:33 -07001988 if (targetUid == -1) {
1989 targetUid = callingUid;
1990 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001991 return ::PERMISSION_DENIED;
1992 }
1993
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001994 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001995 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001996 ALOGD("calling import in state: %d", state);
1997 return state;
1998 }
1999
2000 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002001 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002002
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002003 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002004 }
2005
Kenny Root07438c82012-11-02 15:41:02 -07002006 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2007 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002008 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002009 pid_t spid = IPCThreadState::self()->getCallingPid();
2010 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002011 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002012 return ::PERMISSION_DENIED;
2013 }
Kenny Root07438c82012-11-02 15:41:02 -07002014
Kenny Root07438c82012-11-02 15:41:02 -07002015 Blob keyBlob;
2016 String8 name8(name);
2017
Kenny Rootd38a0b02013-02-13 12:59:14 -08002018 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002019 int rc;
2020
Kenny Root655b9582013-04-04 08:37:42 -07002021 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002022 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002023 if (responseCode != ::NO_ERROR) {
2024 return responseCode;
2025 }
2026
2027 const keymaster_device_t* device = mKeyStore->getDevice();
2028 if (device == NULL) {
2029 ALOGE("no keymaster device; cannot sign");
2030 return ::SYSTEM_ERROR;
2031 }
2032
2033 if (device->sign_data == NULL) {
2034 ALOGE("device doesn't implement signing");
2035 return ::SYSTEM_ERROR;
2036 }
2037
2038 keymaster_rsa_sign_params_t params;
2039 params.digest_type = DIGEST_NONE;
2040 params.padding_type = PADDING_NONE;
2041
Kenny Root17208e02013-09-04 13:56:03 -07002042 if (keyBlob.isFallback()) {
2043 rc = openssl_sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2044 length, out, outLength);
2045 } else {
2046 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2047 length, out, outLength);
2048 }
Kenny Root07438c82012-11-02 15:41:02 -07002049 if (rc) {
2050 ALOGW("device couldn't sign data");
2051 return ::SYSTEM_ERROR;
2052 }
2053
2054 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002055 }
2056
Kenny Root07438c82012-11-02 15:41:02 -07002057 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2058 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002059 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002060 pid_t spid = IPCThreadState::self()->getCallingPid();
2061 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002062 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002063 return ::PERMISSION_DENIED;
2064 }
Kenny Root70e3a862012-02-15 17:20:23 -08002065
Kenny Root655b9582013-04-04 08:37:42 -07002066 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002067 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002068 ALOGD("calling verify in state: %d", state);
2069 return state;
2070 }
Kenny Root70e3a862012-02-15 17:20:23 -08002071
Kenny Root07438c82012-11-02 15:41:02 -07002072 Blob keyBlob;
2073 String8 name8(name);
2074 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002075
Kenny Root655b9582013-04-04 08:37:42 -07002076 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002077 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002078 if (responseCode != ::NO_ERROR) {
2079 return responseCode;
2080 }
Kenny Root70e3a862012-02-15 17:20:23 -08002081
Kenny Root07438c82012-11-02 15:41:02 -07002082 const keymaster_device_t* device = mKeyStore->getDevice();
2083 if (device == NULL) {
2084 return ::SYSTEM_ERROR;
2085 }
Kenny Root70e3a862012-02-15 17:20:23 -08002086
Kenny Root07438c82012-11-02 15:41:02 -07002087 if (device->verify_data == NULL) {
2088 return ::SYSTEM_ERROR;
2089 }
Kenny Root70e3a862012-02-15 17:20:23 -08002090
Kenny Root07438c82012-11-02 15:41:02 -07002091 keymaster_rsa_sign_params_t params;
2092 params.digest_type = DIGEST_NONE;
2093 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002094
Kenny Root17208e02013-09-04 13:56:03 -07002095 if (keyBlob.isFallback()) {
2096 rc = openssl_verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2097 dataLength, signature, signatureLength);
2098 } else {
2099 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2100 dataLength, signature, signatureLength);
2101 }
Kenny Root07438c82012-11-02 15:41:02 -07002102 if (rc) {
2103 return ::SYSTEM_ERROR;
2104 } else {
2105 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002106 }
2107 }
Kenny Root07438c82012-11-02 15:41:02 -07002108
2109 /*
2110 * TODO: The abstraction between things stored in hardware and regular blobs
2111 * of data stored on the filesystem should be moved down to keystore itself.
2112 * Unfortunately the Java code that calls this has naming conventions that it
2113 * knows about. Ideally keystore shouldn't be used to store random blobs of
2114 * data.
2115 *
2116 * Until that happens, it's necessary to have a separate "get_pubkey" and
2117 * "del_key" since the Java code doesn't really communicate what it's
2118 * intentions are.
2119 */
2120 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002121 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002122 pid_t spid = IPCThreadState::self()->getCallingPid();
2123 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002124 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002125 return ::PERMISSION_DENIED;
2126 }
Kenny Root07438c82012-11-02 15:41:02 -07002127
Kenny Root07438c82012-11-02 15:41:02 -07002128 Blob keyBlob;
2129 String8 name8(name);
2130
Kenny Rootd38a0b02013-02-13 12:59:14 -08002131 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002132
Kenny Root655b9582013-04-04 08:37:42 -07002133 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002134 TYPE_KEY_PAIR);
2135 if (responseCode != ::NO_ERROR) {
2136 return responseCode;
2137 }
2138
2139 const keymaster_device_t* device = mKeyStore->getDevice();
2140 if (device == NULL) {
2141 return ::SYSTEM_ERROR;
2142 }
2143
2144 if (device->get_keypair_public == NULL) {
2145 ALOGE("device has no get_keypair_public implementation!");
2146 return ::SYSTEM_ERROR;
2147 }
2148
Kenny Root17208e02013-09-04 13:56:03 -07002149 int rc;
2150 if (keyBlob.isFallback()) {
2151 rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2152 pubkeyLength);
2153 } else {
2154 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2155 pubkeyLength);
2156 }
Kenny Root07438c82012-11-02 15:41:02 -07002157 if (rc) {
2158 return ::SYSTEM_ERROR;
2159 }
2160
2161 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002162 }
Kenny Root07438c82012-11-02 15:41:02 -07002163
Kenny Root49468902013-03-19 13:41:33 -07002164 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002165 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002166 pid_t spid = IPCThreadState::self()->getCallingPid();
2167 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002168 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002169 return ::PERMISSION_DENIED;
2170 }
Kenny Root07438c82012-11-02 15:41:02 -07002171
Kenny Root49468902013-03-19 13:41:33 -07002172 if (targetUid == -1) {
2173 targetUid = callingUid;
2174 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002175 return ::PERMISSION_DENIED;
2176 }
2177
Kenny Root07438c82012-11-02 15:41:02 -07002178 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002179 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01002180 return mKeyStore->del(filename.string(), ::TYPE_KEY_PAIR, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002181 }
2182
2183 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002184 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002185 pid_t spid = IPCThreadState::self()->getCallingPid();
2186 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002187 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002188 return ::PERMISSION_DENIED;
2189 }
Kenny Root07438c82012-11-02 15:41:02 -07002190
Kenny Root655b9582013-04-04 08:37:42 -07002191 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002192 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002193 ALOGD("calling grant in state: %d", state);
2194 return state;
2195 }
2196
2197 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002198 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002199
Kenny Root655b9582013-04-04 08:37:42 -07002200 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002201 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2202 }
2203
Kenny Root655b9582013-04-04 08:37:42 -07002204 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002205 return ::NO_ERROR;
2206 }
2207
2208 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002209 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002210 pid_t spid = IPCThreadState::self()->getCallingPid();
2211 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002212 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002213 return ::PERMISSION_DENIED;
2214 }
Kenny Root07438c82012-11-02 15:41:02 -07002215
Kenny Root655b9582013-04-04 08:37:42 -07002216 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002217 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002218 ALOGD("calling ungrant in state: %d", state);
2219 return state;
2220 }
2221
2222 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002223 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002224
Kenny Root655b9582013-04-04 08:37:42 -07002225 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002226 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2227 }
2228
Kenny Root655b9582013-04-04 08:37:42 -07002229 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002230 }
2231
2232 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002233 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002234 pid_t spid = IPCThreadState::self()->getCallingPid();
2235 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002236 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002237 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002238 }
Kenny Root07438c82012-11-02 15:41:02 -07002239
2240 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002241 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002242
Kenny Root655b9582013-04-04 08:37:42 -07002243 if (access(filename.string(), R_OK) == -1) {
2244 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002245 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002246 }
2247
Kenny Root655b9582013-04-04 08:37:42 -07002248 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002249 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002250 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002251 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002252 }
2253
2254 struct stat s;
2255 int ret = fstat(fd, &s);
2256 close(fd);
2257 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002258 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002259 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002260 }
2261
Kenny Root36a9e232013-02-04 14:24:15 -08002262 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002263 }
2264
Kenny Rootd53bc922013-03-21 14:10:15 -07002265 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2266 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002267 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002268 pid_t spid = IPCThreadState::self()->getCallingPid();
2269 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002270 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002271 return -1L;
2272 }
2273
Kenny Root655b9582013-04-04 08:37:42 -07002274 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002275 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002276 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002277 return state;
2278 }
2279
Kenny Rootd53bc922013-03-21 14:10:15 -07002280 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2281 srcUid = callingUid;
2282 } else if (!is_granted_to(callingUid, srcUid)) {
2283 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002284 return ::PERMISSION_DENIED;
2285 }
2286
Kenny Rootd53bc922013-03-21 14:10:15 -07002287 if (destUid == -1) {
2288 destUid = callingUid;
2289 }
2290
2291 if (srcUid != destUid) {
2292 if (static_cast<uid_t>(srcUid) != callingUid) {
2293 ALOGD("can only duplicate from caller to other or to same uid: "
2294 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2295 return ::PERMISSION_DENIED;
2296 }
2297
2298 if (!is_granted_to(callingUid, destUid)) {
2299 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2300 return ::PERMISSION_DENIED;
2301 }
2302 }
2303
2304 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002305 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002306
Kenny Rootd53bc922013-03-21 14:10:15 -07002307 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002308 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002309
Kenny Root655b9582013-04-04 08:37:42 -07002310 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2311 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002312 return ::SYSTEM_ERROR;
2313 }
2314
Kenny Rootd53bc922013-03-21 14:10:15 -07002315 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002316 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002317 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002318 if (responseCode != ::NO_ERROR) {
2319 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002320 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002321
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002322 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002323 }
2324
Kenny Root1b0e3932013-09-05 13:06:32 -07002325 int32_t is_hardware_backed(const String16& keyType) {
2326 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002327 }
2328
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002329 int32_t clear_uid(int64_t targetUid64) {
2330 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002331 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002332 pid_t spid = IPCThreadState::self()->getCallingPid();
2333 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002334 ALOGW("permission denied for %d: clear_uid", callingUid);
2335 return ::PERMISSION_DENIED;
2336 }
2337
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002338 if (targetUid64 == -1) {
2339 targetUid = callingUid;
Kenny Root007cb232014-07-30 16:59:42 -07002340 } else if (!is_self_or_system(callingUid, targetUid)) {
2341 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002342 return ::PERMISSION_DENIED;
2343 }
2344
Kenny Roota9bb5492013-04-01 16:29:11 -07002345 const keymaster_device_t* device = mKeyStore->getDevice();
2346 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002347 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002348 return ::SYSTEM_ERROR;
2349 }
2350
Robin Lee4b84fdc2014-09-24 11:56:57 +01002351 String8 prefix = String8::format("%u_", targetUid);
2352 Vector<String16> aliases;
2353 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002354 return ::SYSTEM_ERROR;
2355 }
2356
Robin Lee4b84fdc2014-09-24 11:56:57 +01002357 for (uint32_t i = 0; i < aliases.size(); i++) {
2358 String8 name8(aliases[i]);
2359 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2360 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002361 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002362 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002363 }
2364
Robin Lee4b84fdc2014-09-24 11:56:57 +01002365 int32_t reset_uid(int32_t targetUid) {
Robin Lee4e865752014-08-19 17:37:55 +01002366 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2367 pid_t spid = IPCThreadState::self()->getCallingPid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01002368
Robin Lee4e865752014-08-19 17:37:55 +01002369 if (!has_permission(callingUid, P_RESET_UID, spid)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01002370 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002371 return ::PERMISSION_DENIED;
2372 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002373 if (!is_self_or_system(callingUid, targetUid)) {
2374 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002375 return ::PERMISSION_DENIED;
2376 }
2377
Robin Lee4b84fdc2014-09-24 11:56:57 +01002378 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002379 }
2380
2381 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
2382 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2383 pid_t spid = IPCThreadState::self()->getCallingPid();
2384 if (!has_permission(callingUid, P_SYNC_UID, spid)) {
2385 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2386 return ::PERMISSION_DENIED;
2387 }
2388 if (callingUid != AID_SYSTEM) {
2389 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2390 return ::PERMISSION_DENIED;
2391 }
2392 if (sourceUid == targetUid) {
2393 return ::SYSTEM_ERROR;
2394 }
2395
2396 // Initialise user keystore with existing master key held in-memory
2397 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2398 }
2399
2400 int32_t password_uid(const String16& pw, int32_t targetUid) {
2401 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2402 pid_t spid = IPCThreadState::self()->getCallingPid();
2403 if (!has_permission(callingUid, P_PASSWORD_UID, spid)) {
2404 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2405 return ::PERMISSION_DENIED;
2406 }
2407 if (callingUid != AID_SYSTEM) {
2408 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2409 return ::PERMISSION_DENIED;
2410 }
2411
2412 const String8 password8(pw);
2413
2414 switch (mKeyStore->getState(targetUid)) {
2415 case ::STATE_UNINITIALIZED: {
2416 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2417 return mKeyStore->initializeUser(password8, targetUid);
2418 }
2419 case ::STATE_NO_ERROR: {
2420 // rewrite master key with new password.
2421 return mKeyStore->writeMasterKey(password8, targetUid);
2422 }
2423 case ::STATE_LOCKED: {
2424 // read master key, decrypt with password, initialize mMasterKey*.
2425 return mKeyStore->readMasterKey(password8, targetUid);
2426 }
2427 }
2428 return ::SYSTEM_ERROR;
2429 }
2430
Kenny Root07438c82012-11-02 15:41:02 -07002431private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002432 inline bool isKeystoreUnlocked(State state) {
2433 switch (state) {
2434 case ::STATE_NO_ERROR:
2435 return true;
2436 case ::STATE_UNINITIALIZED:
2437 case ::STATE_LOCKED:
2438 return false;
2439 }
2440 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002441 }
2442
Kenny Root1d448c02013-11-21 10:36:53 -08002443 bool isKeyTypeSupported(const keymaster_device_t* device, keymaster_keypair_t keyType) {
2444 const int32_t device_api = device->common.module->module_api_version;
2445 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2446 switch (keyType) {
2447 case TYPE_RSA:
2448 case TYPE_DSA:
2449 case TYPE_EC:
2450 return true;
2451 default:
2452 return false;
2453 }
2454 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2455 switch (keyType) {
2456 case TYPE_RSA:
2457 return true;
2458 case TYPE_DSA:
2459 return device->flags & KEYMASTER_SUPPORTS_DSA;
2460 case TYPE_EC:
2461 return device->flags & KEYMASTER_SUPPORTS_EC;
2462 default:
2463 return false;
2464 }
2465 } else {
2466 return keyType == TYPE_RSA;
2467 }
2468 }
2469
Kenny Root07438c82012-11-02 15:41:02 -07002470 ::KeyStore* mKeyStore;
2471};
2472
2473}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002474
2475int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002476 if (argc < 2) {
2477 ALOGE("A directory must be specified!");
2478 return 1;
2479 }
2480 if (chdir(argv[1]) == -1) {
2481 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2482 return 1;
2483 }
2484
2485 Entropy entropy;
2486 if (!entropy.open()) {
2487 return 1;
2488 }
Kenny Root70e3a862012-02-15 17:20:23 -08002489
2490 keymaster_device_t* dev;
2491 if (keymaster_device_initialize(&dev)) {
2492 ALOGE("keystore keymaster could not be initialized; exiting");
2493 return 1;
2494 }
2495
Riley Spahneaabae92014-06-30 12:39:52 -07002496 ks_is_selinux_enabled = is_selinux_enabled();
2497 if (ks_is_selinux_enabled) {
2498 union selinux_callback cb;
2499 cb.func_log = selinux_log_callback;
2500 selinux_set_callback(SELINUX_CB_LOG, cb);
2501 if (getcon(&tctx) != 0) {
2502 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2503 return -1;
2504 }
2505 } else {
2506 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2507 }
2508
Kenny Root70e3a862012-02-15 17:20:23 -08002509 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002510 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002511 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2512 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2513 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2514 if (ret != android::OK) {
2515 ALOGE("Couldn't register binder service!");
2516 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002517 }
Kenny Root07438c82012-11-02 15:41:02 -07002518
2519 /*
2520 * We're the only thread in existence, so we're just going to process
2521 * Binder transaction as a single-threaded program.
2522 */
2523 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002524
2525 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002526 return 1;
2527}