blob: d2875e55184f57d923162a88b698e00c3bd98543 [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
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800129static int fallback_keymaster_device_initialize(keymaster_device_t** dev) {
130 int rc;
131 rc = openssl_open(reinterpret_cast<hw_module_t*>(&softkeymaster_module),
132 KEYSTORE_KEYMASTER,
133 reinterpret_cast<hw_device_t**>(dev));
134 if (rc) {
135 ALOGE("could not open softkeymaster device (%s)",
136 strerror(-rc));
137 goto out;
138 }
139 return 0;
140out:
141 *dev = NULL;
142 return rc;
143}
144
Kenny Root70e3a862012-02-15 17:20:23 -0800145static void keymaster_device_release(keymaster_device_t* dev) {
146 keymaster_close(dev);
147}
148
Kenny Root07438c82012-11-02 15:41:02 -0700149/***************
150 * PERMISSIONS *
151 ***************/
152
153/* Here are the permissions, actions, users, and the main function. */
154typedef enum {
Robin Lee4e865752014-08-19 17:37:55 +0100155 P_TEST = 1 << 0,
156 P_GET = 1 << 1,
157 P_INSERT = 1 << 2,
158 P_DELETE = 1 << 3,
159 P_EXIST = 1 << 4,
160 P_SAW = 1 << 5,
161 P_RESET = 1 << 6,
162 P_PASSWORD = 1 << 7,
163 P_LOCK = 1 << 8,
164 P_UNLOCK = 1 << 9,
165 P_ZERO = 1 << 10,
166 P_SIGN = 1 << 11,
167 P_VERIFY = 1 << 12,
168 P_GRANT = 1 << 13,
169 P_DUPLICATE = 1 << 14,
170 P_CLEAR_UID = 1 << 15,
171 P_RESET_UID = 1 << 16,
172 P_SYNC_UID = 1 << 17,
173 P_PASSWORD_UID = 1 << 18,
Kenny Root07438c82012-11-02 15:41:02 -0700174} perm_t;
175
176static struct user_euid {
177 uid_t uid;
178 uid_t euid;
179} user_euids[] = {
180 {AID_VPN, AID_SYSTEM},
181 {AID_WIFI, AID_SYSTEM},
182 {AID_ROOT, AID_SYSTEM},
183};
184
Riley Spahneaabae92014-06-30 12:39:52 -0700185/* perm_labels associcated with keystore_key SELinux class verbs. */
186const char *perm_labels[] = {
187 "test",
188 "get",
189 "insert",
190 "delete",
191 "exist",
192 "saw",
193 "reset",
194 "password",
195 "lock",
196 "unlock",
197 "zero",
198 "sign",
199 "verify",
200 "grant",
201 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100202 "clear_uid",
203 "reset_uid",
204 "sync_uid",
205 "password_uid",
Riley Spahneaabae92014-06-30 12:39:52 -0700206};
207
Kenny Root07438c82012-11-02 15:41:02 -0700208static struct user_perm {
209 uid_t uid;
210 perm_t perms;
211} user_perms[] = {
212 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
213 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
214 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
215 {AID_ROOT, static_cast<perm_t>(P_GET) },
216};
217
218static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
219 | P_VERIFY);
220
Riley Spahneaabae92014-06-30 12:39:52 -0700221static char *tctx;
222static int ks_is_selinux_enabled;
223
224static const char *get_perm_label(perm_t perm) {
225 unsigned int index = ffs(perm);
226 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
227 return perm_labels[index - 1];
228 } else {
229 ALOGE("Keystore: Failed to retrieve permission label.\n");
230 abort();
231 }
232}
233
Kenny Root655b9582013-04-04 08:37:42 -0700234/**
235 * Returns the app ID (in the Android multi-user sense) for the current
236 * UNIX UID.
237 */
238static uid_t get_app_id(uid_t uid) {
239 return uid % AID_USER;
240}
241
242/**
243 * Returns the user ID (in the Android multi-user sense) for the current
244 * UNIX UID.
245 */
246static uid_t get_user_id(uid_t uid) {
247 return uid / AID_USER;
248}
249
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700250static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700251 if (!ks_is_selinux_enabled) {
252 return true;
253 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000254
Riley Spahneaabae92014-06-30 12:39:52 -0700255 char *sctx = NULL;
256 const char *selinux_class = "keystore_key";
257 const char *str_perm = get_perm_label(perm);
258
259 if (!str_perm) {
260 return false;
261 }
262
263 if (getpidcon(spid, &sctx) != 0) {
264 ALOGE("SELinux: Failed to get source pid context.\n");
265 return false;
266 }
267
268 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
269 NULL) == 0;
270 freecon(sctx);
271 return allowed;
272}
273
274static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700275 // All system users are equivalent for multi-user support.
276 if (get_app_id(uid) == AID_SYSTEM) {
277 uid = AID_SYSTEM;
278 }
279
Kenny Root07438c82012-11-02 15:41:02 -0700280 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
281 struct user_perm user = user_perms[i];
282 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700283 return (user.perms & perm) &&
284 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700285 }
286 }
287
Riley Spahneaabae92014-06-30 12:39:52 -0700288 return (DEFAULT_PERMS & perm) &&
289 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700290}
291
Kenny Root49468902013-03-19 13:41:33 -0700292/**
293 * Returns the UID that the callingUid should act as. This is here for
294 * legacy support of the WiFi and VPN systems and should be removed
295 * when WiFi can operate in its own namespace.
296 */
Kenny Root07438c82012-11-02 15:41:02 -0700297static uid_t get_keystore_euid(uid_t uid) {
298 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
299 struct user_euid user = user_euids[i];
300 if (user.uid == uid) {
301 return user.euid;
302 }
303 }
304
305 return uid;
306}
307
Kenny Root49468902013-03-19 13:41:33 -0700308/**
309 * Returns true if the callingUid is allowed to interact in the targetUid's
310 * namespace.
311 */
312static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
313 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
314 struct user_euid user = user_euids[i];
315 if (user.euid == callingUid && user.uid == targetUid) {
316 return true;
317 }
318 }
319
320 return false;
321}
322
Kenny Root007cb232014-07-30 16:59:42 -0700323/**
324 * Allow the system to perform some privileged tasks that have to do with
325 * system maintenance. This should not be used for any function that uses
326 * the keys in any way (e.g., signing).
327 */
328static bool is_self_or_system(uid_t callingUid, uid_t targetUid) {
329 return callingUid == targetUid || callingUid == AID_SYSTEM;
330}
331
Kenny Roota91203b2012-02-15 15:00:46 -0800332/* Here is the encoding of keys. This is necessary in order to allow arbitrary
333 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
334 * into two bytes. The first byte is one of [+-.] which represents the first
335 * two bits of the character. The second byte encodes the rest of the bits into
336 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
337 * that Base64 cannot be used here due to the need of prefix match on keys. */
338
Kenny Root655b9582013-04-04 08:37:42 -0700339static size_t encode_key_length(const android::String8& keyName) {
340 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
341 size_t length = keyName.length();
342 for (int i = length; i > 0; --i, ++in) {
343 if (*in < '0' || *in > '~') {
344 ++length;
345 }
346 }
347 return length;
348}
349
Kenny Root07438c82012-11-02 15:41:02 -0700350static int encode_key(char* out, const android::String8& keyName) {
351 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
352 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800353 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700354 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800355 *out = '+' + (*in >> 6);
356 *++out = '0' + (*in & 0x3F);
357 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700358 } else {
359 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800360 }
361 }
362 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800363 return length;
364}
365
Kenny Root07438c82012-11-02 15:41:02 -0700366/*
367 * Converts from the "escaped" format on disk to actual name.
368 * This will be smaller than the input string.
369 *
370 * Characters that should combine with the next at the end will be truncated.
371 */
372static size_t decode_key_length(const char* in, size_t length) {
373 size_t outLength = 0;
374
375 for (const char* end = in + length; in < end; in++) {
376 /* This combines with the next character. */
377 if (*in < '0' || *in > '~') {
378 continue;
379 }
380
381 outLength++;
382 }
383 return outLength;
384}
385
386static void decode_key(char* out, const char* in, size_t length) {
387 for (const char* end = in + length; in < end; in++) {
388 if (*in < '0' || *in > '~') {
389 /* Truncate combining characters at the end. */
390 if (in + 1 >= end) {
391 break;
392 }
393
394 *out = (*in++ - '+') << 6;
395 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800396 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700397 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800398 }
399 }
400 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800401}
402
403static size_t readFully(int fd, uint8_t* data, size_t size) {
404 size_t remaining = size;
405 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800406 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800407 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800408 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800409 }
410 data += n;
411 remaining -= n;
412 }
413 return size;
414}
415
416static size_t writeFully(int fd, uint8_t* data, size_t size) {
417 size_t remaining = size;
418 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800419 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
420 if (n < 0) {
421 ALOGW("write failed: %s", strerror(errno));
422 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800423 }
424 data += n;
425 remaining -= n;
426 }
427 return size;
428}
429
430class Entropy {
431public:
432 Entropy() : mRandom(-1) {}
433 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800434 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800435 close(mRandom);
436 }
437 }
438
439 bool open() {
440 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800441 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
442 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800443 ALOGE("open: %s: %s", randomDevice, strerror(errno));
444 return false;
445 }
446 return true;
447 }
448
Kenny Root51878182012-03-13 12:53:19 -0700449 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800450 return (readFully(mRandom, data, size) == size);
451 }
452
453private:
454 int mRandom;
455};
456
457/* Here is the file format. There are two parts in blob.value, the secret and
458 * the description. The secret is stored in ciphertext, and its original size
459 * can be found in blob.length. The description is stored after the secret in
460 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700461 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700462 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800463 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
464 * and decryptBlob(). Thus they should not be accessed from outside. */
465
Kenny Root822c3a92012-03-23 16:34:39 -0700466/* ** Note to future implementors of encryption: **
467 * Currently this is the construction:
468 * metadata || Enc(MD5(data) || data)
469 *
470 * This should be the construction used for encrypting if re-implementing:
471 *
472 * Derive independent keys for encryption and MAC:
473 * Kenc = AES_encrypt(masterKey, "Encrypt")
474 * Kmac = AES_encrypt(masterKey, "MAC")
475 *
476 * Store this:
477 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
478 * HMAC(Kmac, metadata || Enc(data))
479 */
Kenny Roota91203b2012-02-15 15:00:46 -0800480struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700481 uint8_t version;
482 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700483 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800484 uint8_t info;
485 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700486 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800487 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700488 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800489 int32_t length; // in network byte order when encrypted
490 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
491};
492
Kenny Root822c3a92012-03-23 16:34:39 -0700493typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700494 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700495 TYPE_GENERIC = 1,
496 TYPE_MASTER_KEY = 2,
497 TYPE_KEY_PAIR = 3,
498} BlobType;
499
Kenny Rootf9119d62013-04-03 09:22:15 -0700500static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700501
Kenny Roota91203b2012-02-15 15:00:46 -0800502class Blob {
503public:
Kenny Root07438c82012-11-02 15:41:02 -0700504 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
505 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800506 mBlob.length = valueLength;
507 memcpy(mBlob.value, value, valueLength);
508
509 mBlob.info = infoLength;
510 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700511
Kenny Root07438c82012-11-02 15:41:02 -0700512 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700513 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700514
Kenny Rootee8068b2013-10-07 09:49:15 -0700515 if (type == TYPE_MASTER_KEY) {
516 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
517 } else {
518 mBlob.flags = KEYSTORE_FLAG_NONE;
519 }
Kenny Roota91203b2012-02-15 15:00:46 -0800520 }
521
522 Blob(blob b) {
523 mBlob = b;
524 }
525
526 Blob() {}
527
Kenny Root51878182012-03-13 12:53:19 -0700528 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800529 return mBlob.value;
530 }
531
Kenny Root51878182012-03-13 12:53:19 -0700532 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800533 return mBlob.length;
534 }
535
Kenny Root51878182012-03-13 12:53:19 -0700536 const uint8_t* getInfo() const {
537 return mBlob.value + mBlob.length;
538 }
539
540 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800541 return mBlob.info;
542 }
543
Kenny Root822c3a92012-03-23 16:34:39 -0700544 uint8_t getVersion() const {
545 return mBlob.version;
546 }
547
Kenny Rootf9119d62013-04-03 09:22:15 -0700548 bool isEncrypted() const {
549 if (mBlob.version < 2) {
550 return true;
551 }
552
553 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
554 }
555
556 void setEncrypted(bool encrypted) {
557 if (encrypted) {
558 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
559 } else {
560 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
561 }
562 }
563
Kenny Root17208e02013-09-04 13:56:03 -0700564 bool isFallback() const {
565 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
566 }
567
568 void setFallback(bool fallback) {
569 if (fallback) {
570 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
571 } else {
572 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
573 }
574 }
575
Kenny Root822c3a92012-03-23 16:34:39 -0700576 void setVersion(uint8_t version) {
577 mBlob.version = version;
578 }
579
580 BlobType getType() const {
581 return BlobType(mBlob.type);
582 }
583
584 void setType(BlobType type) {
585 mBlob.type = uint8_t(type);
586 }
587
Kenny Rootf9119d62013-04-03 09:22:15 -0700588 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
589 ALOGV("writing blob %s", filename);
590 if (isEncrypted()) {
591 if (state != STATE_NO_ERROR) {
592 ALOGD("couldn't insert encrypted blob while not unlocked");
593 return LOCKED;
594 }
595
596 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
597 ALOGW("Could not read random data for: %s", filename);
598 return SYSTEM_ERROR;
599 }
Kenny Roota91203b2012-02-15 15:00:46 -0800600 }
601
602 // data includes the value and the value's length
603 size_t dataLength = mBlob.length + sizeof(mBlob.length);
604 // pad data to the AES_BLOCK_SIZE
605 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
606 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
607 // encrypted data includes the digest value
608 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
609 // move info after space for padding
610 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
611 // zero padding area
612 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
613
614 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800615
Kenny Rootf9119d62013-04-03 09:22:15 -0700616 if (isEncrypted()) {
617 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800618
Kenny Rootf9119d62013-04-03 09:22:15 -0700619 uint8_t vector[AES_BLOCK_SIZE];
620 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
621 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
622 aes_key, vector, AES_ENCRYPT);
623 }
624
Kenny Roota91203b2012-02-15 15:00:46 -0800625 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
626 size_t fileLength = encryptedLength + headerLength + mBlob.info;
627
628 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800629 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
630 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
631 if (out < 0) {
632 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800633 return SYSTEM_ERROR;
634 }
635 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
636 if (close(out) != 0) {
637 return SYSTEM_ERROR;
638 }
639 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800640 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800641 unlink(tmpFileName);
642 return SYSTEM_ERROR;
643 }
Kenny Root150ca932012-11-14 14:29:02 -0800644 if (rename(tmpFileName, filename) == -1) {
645 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
646 return SYSTEM_ERROR;
647 }
648 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800649 }
650
Kenny Rootf9119d62013-04-03 09:22:15 -0700651 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
652 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800653 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
654 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800655 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
656 }
657 // fileLength may be less than sizeof(mBlob) since the in
658 // memory version has extra padding to tolerate rounding up to
659 // the AES_BLOCK_SIZE
660 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
661 if (close(in) != 0) {
662 return SYSTEM_ERROR;
663 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700664
665 if (isEncrypted() && (state != STATE_NO_ERROR)) {
666 return LOCKED;
667 }
668
Kenny Roota91203b2012-02-15 15:00:46 -0800669 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
670 if (fileLength < headerLength) {
671 return VALUE_CORRUPTED;
672 }
673
674 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700675 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800676 return VALUE_CORRUPTED;
677 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700678
679 ssize_t digestedLength;
680 if (isEncrypted()) {
681 if (encryptedLength % AES_BLOCK_SIZE != 0) {
682 return VALUE_CORRUPTED;
683 }
684
685 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
686 mBlob.vector, AES_DECRYPT);
687 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
688 uint8_t computedDigest[MD5_DIGEST_LENGTH];
689 MD5(mBlob.digested, digestedLength, computedDigest);
690 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
691 return VALUE_CORRUPTED;
692 }
693 } else {
694 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800695 }
696
697 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
698 mBlob.length = ntohl(mBlob.length);
699 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
700 return VALUE_CORRUPTED;
701 }
702 if (mBlob.info != 0) {
703 // move info from after padding to after data
704 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
705 }
Kenny Root07438c82012-11-02 15:41:02 -0700706 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800707 }
708
709private:
710 struct blob mBlob;
711};
712
Kenny Root655b9582013-04-04 08:37:42 -0700713class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800714public:
Kenny Root655b9582013-04-04 08:37:42 -0700715 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
716 asprintf(&mUserDir, "user_%u", mUserId);
717 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
718 }
719
720 ~UserState() {
721 free(mUserDir);
722 free(mMasterKeyFile);
723 }
724
725 bool initialize() {
726 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
727 ALOGE("Could not create directory '%s'", mUserDir);
728 return false;
729 }
730
731 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800732 setState(STATE_LOCKED);
733 } else {
734 setState(STATE_UNINITIALIZED);
735 }
Kenny Root70e3a862012-02-15 17:20:23 -0800736
Kenny Root655b9582013-04-04 08:37:42 -0700737 return true;
738 }
739
740 uid_t getUserId() const {
741 return mUserId;
742 }
743
744 const char* getUserDirName() const {
745 return mUserDir;
746 }
747
748 const char* getMasterKeyFileName() const {
749 return mMasterKeyFile;
750 }
751
752 void setState(State state) {
753 mState = state;
754 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
755 mRetry = MAX_RETRY;
756 }
Kenny Roota91203b2012-02-15 15:00:46 -0800757 }
758
Kenny Root51878182012-03-13 12:53:19 -0700759 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800760 return mState;
761 }
762
Kenny Root51878182012-03-13 12:53:19 -0700763 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800764 return mRetry;
765 }
766
Kenny Root655b9582013-04-04 08:37:42 -0700767 void zeroizeMasterKeysInMemory() {
768 memset(mMasterKey, 0, sizeof(mMasterKey));
769 memset(mSalt, 0, sizeof(mSalt));
770 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
771 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800772 }
773
Kenny Root655b9582013-04-04 08:37:42 -0700774 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
775 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800776 return SYSTEM_ERROR;
777 }
Kenny Root655b9582013-04-04 08:37:42 -0700778 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800779 if (response != NO_ERROR) {
780 return response;
781 }
782 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700783 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800784 }
785
Robin Lee4e865752014-08-19 17:37:55 +0100786 ResponseCode copyMasterKey(UserState* src) {
787 if (mState != STATE_UNINITIALIZED) {
788 return ::SYSTEM_ERROR;
789 }
790 if (src->getState() != STATE_NO_ERROR) {
791 return ::SYSTEM_ERROR;
792 }
793 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
794 setupMasterKeys();
795 return ::NO_ERROR;
796 }
797
Kenny Root655b9582013-04-04 08:37:42 -0700798 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800799 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
800 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
801 AES_KEY passwordAesKey;
802 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700803 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700804 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800805 }
806
Kenny Root655b9582013-04-04 08:37:42 -0700807 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
808 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800809 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800810 return SYSTEM_ERROR;
811 }
812
813 // we read the raw blob to just to get the salt to generate
814 // the AES key, then we create the Blob to use with decryptBlob
815 blob rawBlob;
816 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
817 if (close(in) != 0) {
818 return SYSTEM_ERROR;
819 }
820 // find salt at EOF if present, otherwise we have an old file
821 uint8_t* salt;
822 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
823 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
824 } else {
825 salt = NULL;
826 }
827 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
828 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
829 AES_KEY passwordAesKey;
830 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
831 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700832 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
833 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800834 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700835 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800836 }
837 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
838 // if salt was missing, generate one and write a new master key file with the salt.
839 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700840 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800841 return SYSTEM_ERROR;
842 }
Kenny Root655b9582013-04-04 08:37:42 -0700843 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800844 }
845 if (response == NO_ERROR) {
846 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
847 setupMasterKeys();
848 }
849 return response;
850 }
851 if (mRetry <= 0) {
852 reset();
853 return UNINITIALIZED;
854 }
855 --mRetry;
856 switch (mRetry) {
857 case 0: return WRONG_PASSWORD_0;
858 case 1: return WRONG_PASSWORD_1;
859 case 2: return WRONG_PASSWORD_2;
860 case 3: return WRONG_PASSWORD_3;
861 default: return WRONG_PASSWORD_3;
862 }
863 }
864
Kenny Root655b9582013-04-04 08:37:42 -0700865 AES_KEY* getEncryptionKey() {
866 return &mMasterKeyEncryption;
867 }
868
869 AES_KEY* getDecryptionKey() {
870 return &mMasterKeyDecryption;
871 }
872
Kenny Roota91203b2012-02-15 15:00:46 -0800873 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700874 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800875 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700876 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800877 return false;
878 }
Kenny Root655b9582013-04-04 08:37:42 -0700879
880 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800881 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700882 // We only care about files.
883 if (file->d_type != DT_REG) {
884 continue;
885 }
886
887 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700888 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700889 continue;
890 }
891
892 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800893 }
894 closedir(dir);
895 return true;
896 }
897
Kenny Root655b9582013-04-04 08:37:42 -0700898private:
899 static const int MASTER_KEY_SIZE_BYTES = 16;
900 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
901
902 static const int MAX_RETRY = 4;
903 static const size_t SALT_SIZE = 16;
904
905 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
906 uint8_t* salt) {
907 size_t saltSize;
908 if (salt != NULL) {
909 saltSize = SALT_SIZE;
910 } else {
911 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
912 salt = (uint8_t*) "keystore";
913 // sizeof = 9, not strlen = 8
914 saltSize = sizeof("keystore");
915 }
916
917 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
918 saltSize, 8192, keySize, key);
919 }
920
921 bool generateSalt(Entropy* entropy) {
922 return entropy->generate_random_data(mSalt, sizeof(mSalt));
923 }
924
925 bool generateMasterKey(Entropy* entropy) {
926 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
927 return false;
928 }
929 if (!generateSalt(entropy)) {
930 return false;
931 }
932 return true;
933 }
934
935 void setupMasterKeys() {
936 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
937 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
938 setState(STATE_NO_ERROR);
939 }
940
941 uid_t mUserId;
942
943 char* mUserDir;
944 char* mMasterKeyFile;
945
946 State mState;
947 int8_t mRetry;
948
949 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
950 uint8_t mSalt[SALT_SIZE];
951
952 AES_KEY mMasterKeyEncryption;
953 AES_KEY mMasterKeyDecryption;
954};
955
956typedef struct {
957 uint32_t uid;
958 const uint8_t* filename;
959} grant_t;
960
961class KeyStore {
962public:
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800963 KeyStore(Entropy* entropy, keymaster_device_t* device, keymaster_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700964 : mEntropy(entropy)
965 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800966 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700967 {
968 memset(&mMetaData, '\0', sizeof(mMetaData));
969 }
970
971 ~KeyStore() {
972 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
973 it != mGrants.end(); it++) {
974 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700975 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800976 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700977
978 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
979 it != mMasterKeys.end(); it++) {
980 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700981 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800982 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700983 }
984
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800985 keymaster_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700986 return mDevice;
987 }
988
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800989 keymaster_device_t *getFallbackDevice() const {
990 return mFallbackDevice;
991 }
992
993 keymaster_device_t *getDeviceForBlob(const Blob& blob) const {
994 return blob.isFallback() ? mFallbackDevice: mDevice;
995 }
996
Kenny Root655b9582013-04-04 08:37:42 -0700997 ResponseCode initialize() {
998 readMetaData();
999 if (upgradeKeystore()) {
1000 writeMetaData();
1001 }
1002
1003 return ::NO_ERROR;
1004 }
1005
1006 State getState(uid_t uid) {
1007 return getUserState(uid)->getState();
1008 }
1009
1010 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
1011 UserState* userState = getUserState(uid);
1012 return userState->initialize(pw, mEntropy);
1013 }
1014
Robin Lee4e865752014-08-19 17:37:55 +01001015 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
1016 UserState *userState = getUserState(uid);
1017 UserState *initState = getUserState(src);
1018 return userState->copyMasterKey(initState);
1019 }
1020
Kenny Root655b9582013-04-04 08:37:42 -07001021 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001022 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001023 return userState->writeMasterKey(pw, mEntropy);
1024 }
1025
1026 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001027 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001028 return userState->readMasterKey(pw, mEntropy);
1029 }
1030
1031 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001032 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001033 encode_key(encoded, keyName);
1034 return android::String8(encoded);
1035 }
1036
1037 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001038 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001039 encode_key(encoded, keyName);
1040 return android::String8::format("%u_%s", uid, encoded);
1041 }
1042
1043 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001044 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001045 encode_key(encoded, keyName);
1046 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1047 encoded);
1048 }
1049
1050 bool reset(uid_t uid) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001051 android::String8 prefix("");
1052 android::Vector<android::String16> aliases;
1053 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1054 return ::SYSTEM_ERROR;
1055 }
1056
Kenny Root655b9582013-04-04 08:37:42 -07001057 UserState* userState = getUserState(uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001058 for (uint32_t i = 0; i < aliases.size(); i++) {
1059 android::String8 filename(aliases[i]);
1060 filename = android::String8::format("%s/%s", userState->getUserDirName(),
1061 getKeyName(filename).string());
1062 del(filename, ::TYPE_ANY, uid);
1063 }
1064
Kenny Root655b9582013-04-04 08:37:42 -07001065 userState->zeroizeMasterKeysInMemory();
1066 userState->setState(STATE_UNINITIALIZED);
1067 return userState->reset();
1068 }
1069
1070 bool isEmpty(uid_t uid) const {
1071 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001072 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001073 return true;
1074 }
1075
1076 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001077 if (!dir) {
1078 return true;
1079 }
Kenny Root31e27462014-09-10 11:28:03 -07001080
Kenny Roota91203b2012-02-15 15:00:46 -08001081 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001082 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001083 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001084 // We only care about files.
1085 if (file->d_type != DT_REG) {
1086 continue;
1087 }
1088
1089 // Skip anything that starts with a "."
1090 if (file->d_name[0] == '.') {
1091 continue;
1092 }
1093
Kenny Root31e27462014-09-10 11:28:03 -07001094 result = false;
1095 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001096 }
1097 closedir(dir);
1098 return result;
1099 }
1100
Kenny Root655b9582013-04-04 08:37:42 -07001101 void lock(uid_t uid) {
1102 UserState* userState = getUserState(uid);
1103 userState->zeroizeMasterKeysInMemory();
1104 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001105 }
1106
Kenny Root655b9582013-04-04 08:37:42 -07001107 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1108 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001109 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1110 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001111 if (rc != NO_ERROR) {
1112 return rc;
1113 }
1114
1115 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001116 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001117 /* If we upgrade the key, we need to write it to disk again. Then
1118 * it must be read it again since the blob is encrypted each time
1119 * it's written.
1120 */
Kenny Root655b9582013-04-04 08:37:42 -07001121 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1122 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001123 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1124 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001125 return rc;
1126 }
1127 }
Kenny Root822c3a92012-03-23 16:34:39 -07001128 }
1129
Kenny Root17208e02013-09-04 13:56:03 -07001130 /*
1131 * This will upgrade software-backed keys to hardware-backed keys when
1132 * the HAL for the device supports the newer key types.
1133 */
1134 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1135 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1136 && keyBlob->isFallback()) {
1137 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1138 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1139
1140 // The HAL allowed the import, reget the key to have the "fresh"
1141 // version.
1142 if (imported == NO_ERROR) {
1143 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1144 }
1145 }
1146
Kenny Rootd53bc922013-03-21 14:10:15 -07001147 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001148 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1149 return KEY_NOT_FOUND;
1150 }
1151
1152 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001153 }
1154
Kenny Root655b9582013-04-04 08:37:42 -07001155 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1156 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001157 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1158 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001159 }
1160
Robin Lee4b84fdc2014-09-24 11:56:57 +01001161 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1162 Blob keyBlob;
1163 ResponseCode rc = get(filename, &keyBlob, type, uid);
1164 if (rc != ::NO_ERROR) {
1165 return rc;
1166 }
1167
1168 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1169 // A device doesn't have to implement delete_keypair.
1170 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1171 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1172 rc = ::SYSTEM_ERROR;
1173 }
1174 }
1175 }
1176 if (rc != ::NO_ERROR) {
1177 return rc;
1178 }
1179
1180 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1181 }
1182
1183 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1184 uid_t uid) {
1185
1186 UserState* userState = getUserState(uid);
1187 size_t n = prefix.length();
1188
1189 DIR* dir = opendir(userState->getUserDirName());
1190 if (!dir) {
1191 ALOGW("can't open directory for user: %s", strerror(errno));
1192 return ::SYSTEM_ERROR;
1193 }
1194
1195 struct dirent* file;
1196 while ((file = readdir(dir)) != NULL) {
1197 // We only care about files.
1198 if (file->d_type != DT_REG) {
1199 continue;
1200 }
1201
1202 // Skip anything that starts with a "."
1203 if (file->d_name[0] == '.') {
1204 continue;
1205 }
1206
1207 if (!strncmp(prefix.string(), file->d_name, n)) {
1208 const char* p = &file->d_name[n];
1209 size_t plen = strlen(p);
1210
1211 size_t extra = decode_key_length(p, plen);
1212 char *match = (char*) malloc(extra + 1);
1213 if (match != NULL) {
1214 decode_key(match, p, plen);
1215 matches->push(android::String16(match, extra));
1216 free(match);
1217 } else {
1218 ALOGW("could not allocate match of size %zd", extra);
1219 }
1220 }
1221 }
1222 closedir(dir);
1223 return ::NO_ERROR;
1224 }
1225
Kenny Root07438c82012-11-02 15:41:02 -07001226 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001227 const grant_t* existing = getGrant(filename, granteeUid);
1228 if (existing == NULL) {
1229 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001230 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001231 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001232 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001233 }
1234 }
1235
Kenny Root07438c82012-11-02 15:41:02 -07001236 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001237 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1238 it != mGrants.end(); it++) {
1239 grant_t* grant = *it;
1240 if (grant->uid == granteeUid
1241 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1242 mGrants.erase(it);
1243 return true;
1244 }
Kenny Root70e3a862012-02-15 17:20:23 -08001245 }
Kenny Root70e3a862012-02-15 17:20:23 -08001246 return false;
1247 }
1248
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001249 bool hasGrant(const char* filename, const uid_t uid) const {
1250 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001251 }
1252
Kenny Rootf9119d62013-04-03 09:22:15 -07001253 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1254 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001255 uint8_t* data;
1256 size_t dataLength;
1257 int rc;
1258
1259 if (mDevice->import_keypair == NULL) {
1260 ALOGE("Keymaster doesn't support import!");
1261 return SYSTEM_ERROR;
1262 }
1263
Kenny Root17208e02013-09-04 13:56:03 -07001264 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001265 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001266 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001267 /*
1268 * Maybe the device doesn't support this type of key. Try to use the
1269 * software fallback keymaster implementation. This is a little bit
1270 * lazier than checking the PKCS#8 key type, but the software
1271 * implementation will do that anyway.
1272 */
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001273 rc = mFallbackDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001274 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001275
1276 if (rc) {
1277 ALOGE("Error while importing keypair: %d", rc);
1278 return SYSTEM_ERROR;
1279 }
Kenny Root822c3a92012-03-23 16:34:39 -07001280 }
1281
1282 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1283 free(data);
1284
Kenny Rootf9119d62013-04-03 09:22:15 -07001285 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001286 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001287
Kenny Root655b9582013-04-04 08:37:42 -07001288 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001289 }
1290
Kenny Root1b0e3932013-09-05 13:06:32 -07001291 bool isHardwareBacked(const android::String16& keyType) const {
1292 if (mDevice == NULL) {
1293 ALOGW("can't get keymaster device");
1294 return false;
1295 }
1296
1297 if (sRSAKeyType == keyType) {
1298 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1299 } else {
1300 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1301 && (mDevice->common.module->module_api_version
1302 >= KEYMASTER_MODULE_API_VERSION_0_2);
1303 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001304 }
1305
Kenny Root655b9582013-04-04 08:37:42 -07001306 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1307 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001308 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001309
1310 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1311 if (responseCode == NO_ERROR) {
1312 return responseCode;
1313 }
1314
1315 // If this is one of the legacy UID->UID mappings, use it.
1316 uid_t euid = get_keystore_euid(uid);
1317 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001318 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001319 responseCode = get(filepath8.string(), keyBlob, type, uid);
1320 if (responseCode == NO_ERROR) {
1321 return responseCode;
1322 }
1323 }
1324
1325 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001326 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001327 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001328 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001329 if (end[0] != '_' || end[1] == 0) {
1330 return KEY_NOT_FOUND;
1331 }
Kenny Root86b16e82013-09-09 11:15:54 -07001332 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1333 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001334 if (!hasGrant(filepath8.string(), uid)) {
1335 return responseCode;
1336 }
1337
1338 // It is a granted key. Try to load it.
1339 return get(filepath8.string(), keyBlob, type, uid);
1340 }
1341
1342 /**
1343 * Returns any existing UserState or creates it if it doesn't exist.
1344 */
1345 UserState* getUserState(uid_t uid) {
1346 uid_t userId = get_user_id(uid);
1347
1348 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1349 it != mMasterKeys.end(); it++) {
1350 UserState* state = *it;
1351 if (state->getUserId() == userId) {
1352 return state;
1353 }
1354 }
1355
1356 UserState* userState = new UserState(userId);
1357 if (!userState->initialize()) {
1358 /* There's not much we can do if initialization fails. Trying to
1359 * unlock the keystore for that user will fail as well, so any
1360 * subsequent request for this user will just return SYSTEM_ERROR.
1361 */
1362 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1363 }
1364 mMasterKeys.add(userState);
1365 return userState;
1366 }
1367
1368 /**
1369 * Returns NULL if the UserState doesn't already exist.
1370 */
1371 const UserState* getUserState(uid_t uid) const {
1372 uid_t userId = get_user_id(uid);
1373
1374 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1375 it != mMasterKeys.end(); it++) {
1376 UserState* state = *it;
1377 if (state->getUserId() == userId) {
1378 return state;
1379 }
1380 }
1381
1382 return NULL;
1383 }
1384
Kenny Roota91203b2012-02-15 15:00:46 -08001385private:
Kenny Root655b9582013-04-04 08:37:42 -07001386 static const char* sOldMasterKey;
1387 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001388 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001389 Entropy* mEntropy;
1390
Kenny Root70e3a862012-02-15 17:20:23 -08001391 keymaster_device_t* mDevice;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001392 keymaster_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001393
Kenny Root655b9582013-04-04 08:37:42 -07001394 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001395
Kenny Root655b9582013-04-04 08:37:42 -07001396 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001397
Kenny Root655b9582013-04-04 08:37:42 -07001398 typedef struct {
1399 uint32_t version;
1400 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001401
Kenny Root655b9582013-04-04 08:37:42 -07001402 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001403
Kenny Root655b9582013-04-04 08:37:42 -07001404 const grant_t* getGrant(const char* filename, uid_t uid) const {
1405 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1406 it != mGrants.end(); it++) {
1407 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001408 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001409 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001410 return grant;
1411 }
1412 }
Kenny Root70e3a862012-02-15 17:20:23 -08001413 return NULL;
1414 }
1415
Kenny Root822c3a92012-03-23 16:34:39 -07001416 /**
1417 * Upgrade code. This will upgrade the key from the current version
1418 * to whatever is newest.
1419 */
Kenny Root655b9582013-04-04 08:37:42 -07001420 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1421 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001422 bool updated = false;
1423 uint8_t version = oldVersion;
1424
1425 /* From V0 -> V1: All old types were unknown */
1426 if (version == 0) {
1427 ALOGV("upgrading to version 1 and setting type %d", type);
1428
1429 blob->setType(type);
1430 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001431 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001432 }
1433 version = 1;
1434 updated = true;
1435 }
1436
Kenny Rootf9119d62013-04-03 09:22:15 -07001437 /* From V1 -> V2: All old keys were encrypted */
1438 if (version == 1) {
1439 ALOGV("upgrading to version 2");
1440
1441 blob->setEncrypted(true);
1442 version = 2;
1443 updated = true;
1444 }
1445
Kenny Root822c3a92012-03-23 16:34:39 -07001446 /*
1447 * If we've updated, set the key blob to the right version
1448 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001449 */
Kenny Root822c3a92012-03-23 16:34:39 -07001450 if (updated) {
1451 ALOGV("updated and writing file %s", filename);
1452 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001453 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001454
1455 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001456 }
1457
1458 /**
1459 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1460 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1461 * Then it overwrites the original blob with the new blob
1462 * format that is returned from the keymaster.
1463 */
Kenny Root655b9582013-04-04 08:37:42 -07001464 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001465 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1466 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1467 if (b.get() == NULL) {
1468 ALOGE("Problem instantiating BIO");
1469 return SYSTEM_ERROR;
1470 }
1471
1472 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1473 if (pkey.get() == NULL) {
1474 ALOGE("Couldn't read old PEM file");
1475 return SYSTEM_ERROR;
1476 }
1477
1478 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1479 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1480 if (len < 0) {
1481 ALOGE("Couldn't measure PKCS#8 length");
1482 return SYSTEM_ERROR;
1483 }
1484
Kenny Root70c98892013-02-07 09:10:36 -08001485 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1486 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001487 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1488 ALOGE("Couldn't convert to PKCS#8");
1489 return SYSTEM_ERROR;
1490 }
1491
Kenny Rootf9119d62013-04-03 09:22:15 -07001492 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1493 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001494 if (rc != NO_ERROR) {
1495 return rc;
1496 }
1497
Kenny Root655b9582013-04-04 08:37:42 -07001498 return get(filename, blob, TYPE_KEY_PAIR, uid);
1499 }
1500
1501 void readMetaData() {
1502 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1503 if (in < 0) {
1504 return;
1505 }
1506 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1507 if (fileLength != sizeof(mMetaData)) {
1508 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1509 sizeof(mMetaData));
1510 }
1511 close(in);
1512 }
1513
1514 void writeMetaData() {
1515 const char* tmpFileName = ".metadata.tmp";
1516 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1517 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1518 if (out < 0) {
1519 ALOGE("couldn't write metadata file: %s", strerror(errno));
1520 return;
1521 }
1522 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1523 if (fileLength != sizeof(mMetaData)) {
1524 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1525 sizeof(mMetaData));
1526 }
1527 close(out);
1528 rename(tmpFileName, sMetaDataFile);
1529 }
1530
1531 bool upgradeKeystore() {
1532 bool upgraded = false;
1533
1534 if (mMetaData.version == 0) {
1535 UserState* userState = getUserState(0);
1536
1537 // Initialize first so the directory is made.
1538 userState->initialize();
1539
1540 // Migrate the old .masterkey file to user 0.
1541 if (access(sOldMasterKey, R_OK) == 0) {
1542 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1543 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1544 return false;
1545 }
1546 }
1547
1548 // Initialize again in case we had a key.
1549 userState->initialize();
1550
1551 // Try to migrate existing keys.
1552 DIR* dir = opendir(".");
1553 if (!dir) {
1554 // Give up now; maybe we can upgrade later.
1555 ALOGE("couldn't open keystore's directory; something is wrong");
1556 return false;
1557 }
1558
1559 struct dirent* file;
1560 while ((file = readdir(dir)) != NULL) {
1561 // We only care about files.
1562 if (file->d_type != DT_REG) {
1563 continue;
1564 }
1565
1566 // Skip anything that starts with a "."
1567 if (file->d_name[0] == '.') {
1568 continue;
1569 }
1570
1571 // Find the current file's user.
1572 char* end;
1573 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1574 if (end[0] != '_' || end[1] == 0) {
1575 continue;
1576 }
1577 UserState* otherUser = getUserState(thisUid);
1578 if (otherUser->getUserId() != 0) {
1579 unlinkat(dirfd(dir), file->d_name, 0);
1580 }
1581
1582 // Rename the file into user directory.
1583 DIR* otherdir = opendir(otherUser->getUserDirName());
1584 if (otherdir == NULL) {
1585 ALOGW("couldn't open user directory for rename");
1586 continue;
1587 }
1588 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1589 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1590 }
1591 closedir(otherdir);
1592 }
1593 closedir(dir);
1594
1595 mMetaData.version = 1;
1596 upgraded = true;
1597 }
1598
1599 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001600 }
Kenny Roota91203b2012-02-15 15:00:46 -08001601};
1602
Kenny Root655b9582013-04-04 08:37:42 -07001603const char* KeyStore::sOldMasterKey = ".masterkey";
1604const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001605
Kenny Root1b0e3932013-09-05 13:06:32 -07001606const android::String16 KeyStore::sRSAKeyType("RSA");
1607
Kenny Root07438c82012-11-02 15:41:02 -07001608namespace android {
1609class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1610public:
1611 KeyStoreProxy(KeyStore* keyStore)
1612 : mKeyStore(keyStore)
1613 {
Kenny Roota91203b2012-02-15 15:00:46 -08001614 }
Kenny Roota91203b2012-02-15 15:00:46 -08001615
Kenny Root07438c82012-11-02 15:41:02 -07001616 void binderDied(const wp<IBinder>&) {
1617 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001618 }
Kenny Roota91203b2012-02-15 15:00:46 -08001619
Kenny Root07438c82012-11-02 15:41:02 -07001620 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001621 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001622 pid_t spid = IPCThreadState::self()->getCallingPid();
1623 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001624 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001625 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001626 }
Kenny Roota91203b2012-02-15 15:00:46 -08001627
Kenny Root655b9582013-04-04 08:37:42 -07001628 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001629 }
1630
Kenny Root07438c82012-11-02 15:41:02 -07001631 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001632 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001633 pid_t spid = IPCThreadState::self()->getCallingPid();
1634 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001635 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001636 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001637 }
Kenny Root07438c82012-11-02 15:41:02 -07001638
Kenny Root07438c82012-11-02 15:41:02 -07001639 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001640 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001641
Kenny Root655b9582013-04-04 08:37:42 -07001642 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001643 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001644 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001645 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001646 *item = NULL;
1647 *itemLength = 0;
1648 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001649 }
Kenny Roota91203b2012-02-15 15:00:46 -08001650
Kenny Root07438c82012-11-02 15:41:02 -07001651 *item = (uint8_t*) malloc(keyBlob.getLength());
1652 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1653 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001654
Kenny Root07438c82012-11-02 15:41:02 -07001655 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001656 }
1657
Kenny Rootf9119d62013-04-03 09:22:15 -07001658 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1659 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001660 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001661 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001662 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001663 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001664 return ::PERMISSION_DENIED;
1665 }
Kenny Root07438c82012-11-02 15:41:02 -07001666
Kenny Rootf9119d62013-04-03 09:22:15 -07001667 State state = mKeyStore->getState(callingUid);
1668 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1669 ALOGD("calling get in state: %d", state);
1670 return state;
1671 }
1672
Kenny Root49468902013-03-19 13:41:33 -07001673 if (targetUid == -1) {
1674 targetUid = callingUid;
1675 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001676 return ::PERMISSION_DENIED;
1677 }
1678
Kenny Root07438c82012-11-02 15:41:02 -07001679 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001680 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001681
1682 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001683 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1684
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001685 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001686 }
1687
Kenny Root49468902013-03-19 13:41:33 -07001688 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001689 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001690 pid_t spid = IPCThreadState::self()->getCallingPid();
1691 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001692 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001693 return ::PERMISSION_DENIED;
1694 }
Kenny Root70e3a862012-02-15 17:20:23 -08001695
Kenny Root49468902013-03-19 13:41:33 -07001696 if (targetUid == -1) {
1697 targetUid = callingUid;
1698 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001699 return ::PERMISSION_DENIED;
1700 }
1701
Kenny Root07438c82012-11-02 15:41:02 -07001702 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001703 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01001704 return mKeyStore->del(filename.string(), ::TYPE_GENERIC, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001705 }
1706
Kenny Root49468902013-03-19 13:41:33 -07001707 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001708 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001709 pid_t spid = IPCThreadState::self()->getCallingPid();
1710 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001711 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001712 return ::PERMISSION_DENIED;
1713 }
Kenny Root70e3a862012-02-15 17:20:23 -08001714
Kenny Root49468902013-03-19 13:41:33 -07001715 if (targetUid == -1) {
1716 targetUid = callingUid;
1717 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001718 return ::PERMISSION_DENIED;
1719 }
1720
Kenny Root07438c82012-11-02 15:41:02 -07001721 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001722 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001723
Kenny Root655b9582013-04-04 08:37:42 -07001724 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001725 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1726 }
1727 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001728 }
1729
Kenny Root49468902013-03-19 13:41:33 -07001730 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001731 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001732 pid_t spid = IPCThreadState::self()->getCallingPid();
1733 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001734 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001735 return ::PERMISSION_DENIED;
1736 }
Kenny Root70e3a862012-02-15 17:20:23 -08001737
Kenny Root49468902013-03-19 13:41:33 -07001738 if (targetUid == -1) {
1739 targetUid = callingUid;
1740 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001741 return ::PERMISSION_DENIED;
1742 }
1743
Kenny Root07438c82012-11-02 15:41:02 -07001744 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001745 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001746
Robin Lee4b84fdc2014-09-24 11:56:57 +01001747 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1748 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001749 }
Kenny Root07438c82012-11-02 15:41:02 -07001750 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001751 }
1752
Kenny Root07438c82012-11-02 15:41:02 -07001753 int32_t reset() {
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_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001757 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001758 return ::PERMISSION_DENIED;
1759 }
1760
Robin Lee4b84fdc2014-09-24 11:56:57 +01001761 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001762 }
1763
Kenny Root07438c82012-11-02 15:41:02 -07001764 /*
1765 * Here is the history. To improve the security, the parameters to generate the
1766 * master key has been changed. To make a seamless transition, we update the
1767 * file using the same password when the user unlock it for the first time. If
1768 * any thing goes wrong during the transition, the new file will not overwrite
1769 * the old one. This avoids permanent damages of the existing data.
1770 */
1771 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001772 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001773 pid_t spid = IPCThreadState::self()->getCallingPid();
1774 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001775 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001776 return ::PERMISSION_DENIED;
1777 }
Kenny Root70e3a862012-02-15 17:20:23 -08001778
Kenny Root07438c82012-11-02 15:41:02 -07001779 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001780
Kenny Root655b9582013-04-04 08:37:42 -07001781 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001782 case ::STATE_UNINITIALIZED: {
1783 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001784 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001785 }
1786 case ::STATE_NO_ERROR: {
1787 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001788 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001789 }
1790 case ::STATE_LOCKED: {
1791 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001792 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001793 }
1794 }
1795 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001796 }
1797
Kenny Root07438c82012-11-02 15:41:02 -07001798 int32_t lock() {
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_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001802 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001803 return ::PERMISSION_DENIED;
1804 }
Kenny Root70e3a862012-02-15 17:20:23 -08001805
Kenny Root655b9582013-04-04 08:37:42 -07001806 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001807 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001808 ALOGD("calling lock in state: %d", state);
1809 return state;
1810 }
1811
Kenny Root655b9582013-04-04 08:37:42 -07001812 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001813 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001814 }
1815
Kenny Root07438c82012-11-02 15:41:02 -07001816 int32_t unlock(const String16& pw) {
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_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001820 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001821 return ::PERMISSION_DENIED;
1822 }
1823
Kenny Root655b9582013-04-04 08:37:42 -07001824 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001825 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001826 ALOGD("calling unlock when not locked");
1827 return state;
1828 }
1829
1830 const String8 password8(pw);
1831 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001832 }
1833
Kenny Root07438c82012-11-02 15:41:02 -07001834 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001835 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001836 pid_t spid = IPCThreadState::self()->getCallingPid();
1837 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001838 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001839 return -1;
1840 }
Kenny Root70e3a862012-02-15 17:20:23 -08001841
Kenny Root655b9582013-04-04 08:37:42 -07001842 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001843 }
1844
Kenny Root96427ba2013-08-16 14:02:41 -07001845 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1846 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001847 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001848 pid_t spid = IPCThreadState::self()->getCallingPid();
1849 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001850 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001851 return ::PERMISSION_DENIED;
1852 }
Kenny Root70e3a862012-02-15 17:20:23 -08001853
Kenny Root49468902013-03-19 13:41:33 -07001854 if (targetUid == -1) {
1855 targetUid = callingUid;
1856 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001857 return ::PERMISSION_DENIED;
1858 }
1859
Kenny Root655b9582013-04-04 08:37:42 -07001860 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001861 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1862 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001863 return state;
1864 }
Kenny Root70e3a862012-02-15 17:20:23 -08001865
Kenny Root07438c82012-11-02 15:41:02 -07001866 uint8_t* data;
1867 size_t dataLength;
1868 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001869 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001870
1871 const keymaster_device_t* device = mKeyStore->getDevice();
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001872 const keymaster_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001873 if (device == NULL) {
1874 return ::SYSTEM_ERROR;
1875 }
1876
1877 if (device->generate_keypair == NULL) {
1878 return ::SYSTEM_ERROR;
1879 }
1880
Kenny Root17208e02013-09-04 13:56:03 -07001881 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001882 keymaster_dsa_keygen_params_t dsa_params;
1883 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001884
Kenny Root96427ba2013-08-16 14:02:41 -07001885 if (keySize == -1) {
1886 keySize = DSA_DEFAULT_KEY_SIZE;
1887 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1888 || keySize > DSA_MAX_KEY_SIZE) {
1889 ALOGI("invalid key size %d", keySize);
1890 return ::SYSTEM_ERROR;
1891 }
1892 dsa_params.key_size = keySize;
1893
1894 if (args->size() == 3) {
1895 sp<KeystoreArg> gArg = args->itemAt(0);
1896 sp<KeystoreArg> pArg = args->itemAt(1);
1897 sp<KeystoreArg> qArg = args->itemAt(2);
1898
1899 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1900 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1901 dsa_params.generator_len = gArg->size();
1902
1903 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1904 dsa_params.prime_p_len = pArg->size();
1905
1906 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1907 dsa_params.prime_q_len = qArg->size();
1908 } else {
1909 ALOGI("not all DSA parameters were read");
1910 return ::SYSTEM_ERROR;
1911 }
1912 } else if (args->size() != 0) {
1913 ALOGI("DSA args must be 3");
1914 return ::SYSTEM_ERROR;
1915 }
1916
Kenny Root1d448c02013-11-21 10:36:53 -08001917 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001918 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1919 } else {
1920 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001921 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1922 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001923 }
1924 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001925 keymaster_ec_keygen_params_t ec_params;
1926 memset(&ec_params, '\0', sizeof(ec_params));
1927
1928 if (keySize == -1) {
1929 keySize = EC_DEFAULT_KEY_SIZE;
1930 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1931 ALOGI("invalid key size %d", keySize);
1932 return ::SYSTEM_ERROR;
1933 }
1934 ec_params.field_size = keySize;
1935
Kenny Root1d448c02013-11-21 10:36:53 -08001936 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001937 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1938 } else {
1939 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001940 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001941 }
Kenny Root96427ba2013-08-16 14:02:41 -07001942 } else if (keyType == EVP_PKEY_RSA) {
1943 keymaster_rsa_keygen_params_t rsa_params;
1944 memset(&rsa_params, '\0', sizeof(rsa_params));
1945 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1946
1947 if (keySize == -1) {
1948 keySize = RSA_DEFAULT_KEY_SIZE;
1949 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1950 ALOGI("invalid key size %d", keySize);
1951 return ::SYSTEM_ERROR;
1952 }
1953 rsa_params.modulus_size = keySize;
1954
1955 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001956 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001957 return ::SYSTEM_ERROR;
1958 } else if (args->size() == 1) {
1959 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1960 if (pubExpBlob != NULL) {
1961 Unique_BIGNUM pubExpBn(
1962 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1963 pubExpBlob->size(), NULL));
1964 if (pubExpBn.get() == NULL) {
1965 ALOGI("Could not convert public exponent to BN");
1966 return ::SYSTEM_ERROR;
1967 }
1968 unsigned long pubExp = BN_get_word(pubExpBn.get());
1969 if (pubExp == 0xFFFFFFFFL) {
1970 ALOGI("cannot represent public exponent as a long value");
1971 return ::SYSTEM_ERROR;
1972 }
1973 rsa_params.public_exponent = pubExp;
1974 }
1975 }
1976
1977 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1978 } else {
1979 ALOGW("Unsupported key type %d", keyType);
1980 rc = -1;
1981 }
1982
Kenny Root07438c82012-11-02 15:41:02 -07001983 if (rc) {
1984 return ::SYSTEM_ERROR;
1985 }
1986
Kenny Root655b9582013-04-04 08:37:42 -07001987 String8 name8(name);
1988 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001989
1990 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1991 free(data);
1992
Kenny Rootee8068b2013-10-07 09:49:15 -07001993 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001994 keyBlob.setFallback(isFallback);
1995
Kenny Root655b9582013-04-04 08:37:42 -07001996 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001997 }
1998
Kenny Rootf9119d62013-04-03 09:22:15 -07001999 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2000 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002001 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002002 pid_t spid = IPCThreadState::self()->getCallingPid();
2003 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002004 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002005 return ::PERMISSION_DENIED;
2006 }
Kenny Root07438c82012-11-02 15:41:02 -07002007
Kenny Root49468902013-03-19 13:41:33 -07002008 if (targetUid == -1) {
2009 targetUid = callingUid;
2010 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002011 return ::PERMISSION_DENIED;
2012 }
2013
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002014 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07002015 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002016 ALOGD("calling import in state: %d", state);
2017 return state;
2018 }
2019
2020 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002021 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002022
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002023 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002024 }
2025
Kenny Root07438c82012-11-02 15:41:02 -07002026 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2027 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002028 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002029 pid_t spid = IPCThreadState::self()->getCallingPid();
2030 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002031 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002032 return ::PERMISSION_DENIED;
2033 }
Kenny Root07438c82012-11-02 15:41:02 -07002034
Kenny Root07438c82012-11-02 15:41:02 -07002035 Blob keyBlob;
2036 String8 name8(name);
2037
Kenny Rootd38a0b02013-02-13 12:59:14 -08002038 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002039 int rc;
2040
Kenny Root655b9582013-04-04 08:37:42 -07002041 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002042 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002043 if (responseCode != ::NO_ERROR) {
2044 return responseCode;
2045 }
2046
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002047 const keymaster_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002048 if (device == NULL) {
2049 ALOGE("no keymaster device; cannot sign");
2050 return ::SYSTEM_ERROR;
2051 }
2052
2053 if (device->sign_data == NULL) {
2054 ALOGE("device doesn't implement signing");
2055 return ::SYSTEM_ERROR;
2056 }
2057
2058 keymaster_rsa_sign_params_t params;
2059 params.digest_type = DIGEST_NONE;
2060 params.padding_type = PADDING_NONE;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002061 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2062 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002063 if (rc) {
2064 ALOGW("device couldn't sign data");
2065 return ::SYSTEM_ERROR;
2066 }
2067
2068 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002069 }
2070
Kenny Root07438c82012-11-02 15:41:02 -07002071 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2072 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002073 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002074 pid_t spid = IPCThreadState::self()->getCallingPid();
2075 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002076 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002077 return ::PERMISSION_DENIED;
2078 }
Kenny Root70e3a862012-02-15 17:20:23 -08002079
Kenny Root655b9582013-04-04 08:37:42 -07002080 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002081 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002082 ALOGD("calling verify in state: %d", state);
2083 return state;
2084 }
Kenny Root70e3a862012-02-15 17:20:23 -08002085
Kenny Root07438c82012-11-02 15:41:02 -07002086 Blob keyBlob;
2087 String8 name8(name);
2088 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002089
Kenny Root655b9582013-04-04 08:37:42 -07002090 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002091 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002092 if (responseCode != ::NO_ERROR) {
2093 return responseCode;
2094 }
Kenny Root70e3a862012-02-15 17:20:23 -08002095
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002096 const keymaster_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002097 if (device == NULL) {
2098 return ::SYSTEM_ERROR;
2099 }
Kenny Root70e3a862012-02-15 17:20:23 -08002100
Kenny Root07438c82012-11-02 15:41:02 -07002101 if (device->verify_data == NULL) {
2102 return ::SYSTEM_ERROR;
2103 }
Kenny Root70e3a862012-02-15 17:20:23 -08002104
Kenny Root07438c82012-11-02 15:41:02 -07002105 keymaster_rsa_sign_params_t params;
2106 params.digest_type = DIGEST_NONE;
2107 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002108
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002109 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2110 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002111 if (rc) {
2112 return ::SYSTEM_ERROR;
2113 } else {
2114 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002115 }
2116 }
Kenny Root07438c82012-11-02 15:41:02 -07002117
2118 /*
2119 * TODO: The abstraction between things stored in hardware and regular blobs
2120 * of data stored on the filesystem should be moved down to keystore itself.
2121 * Unfortunately the Java code that calls this has naming conventions that it
2122 * knows about. Ideally keystore shouldn't be used to store random blobs of
2123 * data.
2124 *
2125 * Until that happens, it's necessary to have a separate "get_pubkey" and
2126 * "del_key" since the Java code doesn't really communicate what it's
2127 * intentions are.
2128 */
2129 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002130 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002131 pid_t spid = IPCThreadState::self()->getCallingPid();
2132 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002133 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002134 return ::PERMISSION_DENIED;
2135 }
Kenny Root07438c82012-11-02 15:41:02 -07002136
Kenny Root07438c82012-11-02 15:41:02 -07002137 Blob keyBlob;
2138 String8 name8(name);
2139
Kenny Rootd38a0b02013-02-13 12:59:14 -08002140 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002141
Kenny Root655b9582013-04-04 08:37:42 -07002142 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002143 TYPE_KEY_PAIR);
2144 if (responseCode != ::NO_ERROR) {
2145 return responseCode;
2146 }
2147
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002148 const keymaster_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002149 if (device == NULL) {
2150 return ::SYSTEM_ERROR;
2151 }
2152
2153 if (device->get_keypair_public == NULL) {
2154 ALOGE("device has no get_keypair_public implementation!");
2155 return ::SYSTEM_ERROR;
2156 }
2157
Kenny Root17208e02013-09-04 13:56:03 -07002158 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002159 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2160 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002161 if (rc) {
2162 return ::SYSTEM_ERROR;
2163 }
2164
2165 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002166 }
Kenny Root07438c82012-11-02 15:41:02 -07002167
Kenny Root49468902013-03-19 13:41:33 -07002168 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002169 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002170 pid_t spid = IPCThreadState::self()->getCallingPid();
2171 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002172 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002173 return ::PERMISSION_DENIED;
2174 }
Kenny Root07438c82012-11-02 15:41:02 -07002175
Kenny Root49468902013-03-19 13:41:33 -07002176 if (targetUid == -1) {
2177 targetUid = callingUid;
2178 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002179 return ::PERMISSION_DENIED;
2180 }
2181
Kenny Root07438c82012-11-02 15:41:02 -07002182 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002183 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01002184 return mKeyStore->del(filename.string(), ::TYPE_KEY_PAIR, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002185 }
2186
2187 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002188 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002189 pid_t spid = IPCThreadState::self()->getCallingPid();
2190 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002191 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002192 return ::PERMISSION_DENIED;
2193 }
Kenny Root07438c82012-11-02 15:41:02 -07002194
Kenny Root655b9582013-04-04 08:37:42 -07002195 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002196 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002197 ALOGD("calling grant in state: %d", state);
2198 return state;
2199 }
2200
2201 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002202 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002203
Kenny Root655b9582013-04-04 08:37:42 -07002204 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002205 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2206 }
2207
Kenny Root655b9582013-04-04 08:37:42 -07002208 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002209 return ::NO_ERROR;
2210 }
2211
2212 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002213 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002214 pid_t spid = IPCThreadState::self()->getCallingPid();
2215 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002216 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002217 return ::PERMISSION_DENIED;
2218 }
Kenny Root07438c82012-11-02 15:41:02 -07002219
Kenny Root655b9582013-04-04 08:37:42 -07002220 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002221 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002222 ALOGD("calling ungrant in state: %d", state);
2223 return state;
2224 }
2225
2226 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002227 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002228
Kenny Root655b9582013-04-04 08:37:42 -07002229 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002230 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2231 }
2232
Kenny Root655b9582013-04-04 08:37:42 -07002233 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002234 }
2235
2236 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002237 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002238 pid_t spid = IPCThreadState::self()->getCallingPid();
2239 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002240 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002241 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002242 }
Kenny Root07438c82012-11-02 15:41:02 -07002243
2244 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002245 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002246
Kenny Root655b9582013-04-04 08:37:42 -07002247 if (access(filename.string(), R_OK) == -1) {
2248 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002249 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002250 }
2251
Kenny Root655b9582013-04-04 08:37:42 -07002252 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002253 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002254 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002255 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002256 }
2257
2258 struct stat s;
2259 int ret = fstat(fd, &s);
2260 close(fd);
2261 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002262 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002263 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002264 }
2265
Kenny Root36a9e232013-02-04 14:24:15 -08002266 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002267 }
2268
Kenny Rootd53bc922013-03-21 14:10:15 -07002269 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2270 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002271 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002272 pid_t spid = IPCThreadState::self()->getCallingPid();
2273 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002274 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002275 return -1L;
2276 }
2277
Kenny Root655b9582013-04-04 08:37:42 -07002278 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002279 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002280 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002281 return state;
2282 }
2283
Kenny Rootd53bc922013-03-21 14:10:15 -07002284 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2285 srcUid = callingUid;
2286 } else if (!is_granted_to(callingUid, srcUid)) {
2287 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002288 return ::PERMISSION_DENIED;
2289 }
2290
Kenny Rootd53bc922013-03-21 14:10:15 -07002291 if (destUid == -1) {
2292 destUid = callingUid;
2293 }
2294
2295 if (srcUid != destUid) {
2296 if (static_cast<uid_t>(srcUid) != callingUid) {
2297 ALOGD("can only duplicate from caller to other or to same uid: "
2298 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2299 return ::PERMISSION_DENIED;
2300 }
2301
2302 if (!is_granted_to(callingUid, destUid)) {
2303 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2304 return ::PERMISSION_DENIED;
2305 }
2306 }
2307
2308 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002309 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002310
Kenny Rootd53bc922013-03-21 14:10:15 -07002311 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002312 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002313
Kenny Root655b9582013-04-04 08:37:42 -07002314 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2315 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002316 return ::SYSTEM_ERROR;
2317 }
2318
Kenny Rootd53bc922013-03-21 14:10:15 -07002319 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002320 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002321 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002322 if (responseCode != ::NO_ERROR) {
2323 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002324 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002325
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002326 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002327 }
2328
Kenny Root1b0e3932013-09-05 13:06:32 -07002329 int32_t is_hardware_backed(const String16& keyType) {
2330 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002331 }
2332
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002333 int32_t clear_uid(int64_t targetUid64) {
2334 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002335 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002336 pid_t spid = IPCThreadState::self()->getCallingPid();
2337 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002338 ALOGW("permission denied for %d: clear_uid", callingUid);
2339 return ::PERMISSION_DENIED;
2340 }
2341
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002342 if (targetUid64 == -1) {
2343 targetUid = callingUid;
Kenny Root007cb232014-07-30 16:59:42 -07002344 } else if (!is_self_or_system(callingUid, targetUid)) {
2345 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002346 return ::PERMISSION_DENIED;
2347 }
2348
Kenny Roota9bb5492013-04-01 16:29:11 -07002349 const keymaster_device_t* device = mKeyStore->getDevice();
2350 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002351 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002352 return ::SYSTEM_ERROR;
2353 }
2354
Robin Lee4b84fdc2014-09-24 11:56:57 +01002355 String8 prefix = String8::format("%u_", targetUid);
2356 Vector<String16> aliases;
2357 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002358 return ::SYSTEM_ERROR;
2359 }
2360
Robin Lee4b84fdc2014-09-24 11:56:57 +01002361 for (uint32_t i = 0; i < aliases.size(); i++) {
2362 String8 name8(aliases[i]);
2363 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2364 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002365 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002366 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002367 }
2368
Robin Lee4b84fdc2014-09-24 11:56:57 +01002369 int32_t reset_uid(int32_t targetUid) {
Robin Lee4e865752014-08-19 17:37:55 +01002370 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2371 pid_t spid = IPCThreadState::self()->getCallingPid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01002372
Robin Lee4e865752014-08-19 17:37:55 +01002373 if (!has_permission(callingUid, P_RESET_UID, spid)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01002374 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002375 return ::PERMISSION_DENIED;
2376 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002377 if (!is_self_or_system(callingUid, targetUid)) {
2378 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002379 return ::PERMISSION_DENIED;
2380 }
2381
Robin Lee4b84fdc2014-09-24 11:56:57 +01002382 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002383 }
2384
2385 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
2386 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2387 pid_t spid = IPCThreadState::self()->getCallingPid();
2388 if (!has_permission(callingUid, P_SYNC_UID, spid)) {
2389 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2390 return ::PERMISSION_DENIED;
2391 }
2392 if (callingUid != AID_SYSTEM) {
2393 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2394 return ::PERMISSION_DENIED;
2395 }
2396 if (sourceUid == targetUid) {
2397 return ::SYSTEM_ERROR;
2398 }
2399
2400 // Initialise user keystore with existing master key held in-memory
2401 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2402 }
2403
2404 int32_t password_uid(const String16& pw, int32_t targetUid) {
2405 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2406 pid_t spid = IPCThreadState::self()->getCallingPid();
2407 if (!has_permission(callingUid, P_PASSWORD_UID, spid)) {
2408 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2409 return ::PERMISSION_DENIED;
2410 }
2411 if (callingUid != AID_SYSTEM) {
2412 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2413 return ::PERMISSION_DENIED;
2414 }
2415
2416 const String8 password8(pw);
2417
2418 switch (mKeyStore->getState(targetUid)) {
2419 case ::STATE_UNINITIALIZED: {
2420 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2421 return mKeyStore->initializeUser(password8, targetUid);
2422 }
2423 case ::STATE_NO_ERROR: {
2424 // rewrite master key with new password.
2425 return mKeyStore->writeMasterKey(password8, targetUid);
2426 }
2427 case ::STATE_LOCKED: {
2428 // read master key, decrypt with password, initialize mMasterKey*.
2429 return mKeyStore->readMasterKey(password8, targetUid);
2430 }
2431 }
2432 return ::SYSTEM_ERROR;
2433 }
2434
Kenny Root07438c82012-11-02 15:41:02 -07002435private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002436 inline bool isKeystoreUnlocked(State state) {
2437 switch (state) {
2438 case ::STATE_NO_ERROR:
2439 return true;
2440 case ::STATE_UNINITIALIZED:
2441 case ::STATE_LOCKED:
2442 return false;
2443 }
2444 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002445 }
2446
Kenny Root1d448c02013-11-21 10:36:53 -08002447 bool isKeyTypeSupported(const keymaster_device_t* device, keymaster_keypair_t keyType) {
2448 const int32_t device_api = device->common.module->module_api_version;
2449 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2450 switch (keyType) {
2451 case TYPE_RSA:
2452 case TYPE_DSA:
2453 case TYPE_EC:
2454 return true;
2455 default:
2456 return false;
2457 }
2458 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2459 switch (keyType) {
2460 case TYPE_RSA:
2461 return true;
2462 case TYPE_DSA:
2463 return device->flags & KEYMASTER_SUPPORTS_DSA;
2464 case TYPE_EC:
2465 return device->flags & KEYMASTER_SUPPORTS_EC;
2466 default:
2467 return false;
2468 }
2469 } else {
2470 return keyType == TYPE_RSA;
2471 }
2472 }
2473
Kenny Root07438c82012-11-02 15:41:02 -07002474 ::KeyStore* mKeyStore;
2475};
2476
2477}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002478
2479int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002480 if (argc < 2) {
2481 ALOGE("A directory must be specified!");
2482 return 1;
2483 }
2484 if (chdir(argv[1]) == -1) {
2485 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2486 return 1;
2487 }
2488
2489 Entropy entropy;
2490 if (!entropy.open()) {
2491 return 1;
2492 }
Kenny Root70e3a862012-02-15 17:20:23 -08002493
2494 keymaster_device_t* dev;
2495 if (keymaster_device_initialize(&dev)) {
2496 ALOGE("keystore keymaster could not be initialized; exiting");
2497 return 1;
2498 }
2499
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002500 keymaster_device_t* fallback;
2501 if (fallback_keymaster_device_initialize(&fallback)) {
2502 ALOGE("software keymaster could not be initialized; exiting");
2503 return 1;
2504 }
2505
Riley Spahneaabae92014-06-30 12:39:52 -07002506 ks_is_selinux_enabled = is_selinux_enabled();
2507 if (ks_is_selinux_enabled) {
2508 union selinux_callback cb;
2509 cb.func_log = selinux_log_callback;
2510 selinux_set_callback(SELINUX_CB_LOG, cb);
2511 if (getcon(&tctx) != 0) {
2512 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2513 return -1;
2514 }
2515 } else {
2516 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2517 }
2518
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002519 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07002520 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002521 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2522 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2523 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2524 if (ret != android::OK) {
2525 ALOGE("Couldn't register binder service!");
2526 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002527 }
Kenny Root07438c82012-11-02 15:41:02 -07002528
2529 /*
2530 * We're the only thread in existence, so we're just going to process
2531 * Binder transaction as a single-threaded program.
2532 */
2533 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002534
2535 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002536 return 1;
2537}