blob: 4075acf547b4e4c49fef7562fc3c536b0cf72332 [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Kenny Root70e3a862012-02-15 17:20:23 -080044#include <hardware/keymaster.h>
45
Kenny Root17208e02013-09-04 13:56:03 -070046#include <keymaster/softkeymaster.h>
47
Kenny Root26cfc082013-09-11 14:38:56 -070048#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070049#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070050#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080051
Kenny Root07438c82012-11-02 15:41:02 -070052#include <keystore/IKeystoreService.h>
53#include <binder/IPCThreadState.h>
54#include <binder/IServiceManager.h>
55
Kenny Roota91203b2012-02-15 15:00:46 -080056#include <cutils/log.h>
57#include <cutils/sockets.h>
58#include <private/android_filesystem_config.h>
59
Kenny Root07438c82012-11-02 15:41:02 -070060#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080061
Riley Spahneaabae92014-06-30 12:39:52 -070062#include <selinux/android.h>
63
Kenny Root96427ba2013-08-16 14:02:41 -070064#include "defaults.h"
65
Kenny Roota91203b2012-02-15 15:00:46 -080066/* KeyStore is a secured storage for key-value pairs. In this implementation,
67 * each file stores one key-value pair. Keys are encoded in file names, and
68 * values are encrypted with checksums. The encryption key is protected by a
69 * user-defined password. To keep things simple, buffers are always larger than
70 * the maximum space we needed, so boundary checks on buffers are omitted. */
71
72#define KEY_SIZE ((NAME_MAX - 15) / 2)
73#define VALUE_SIZE 32768
74#define PASSWORD_SIZE VALUE_SIZE
75
Kenny Root822c3a92012-03-23 16:34:39 -070076
Kenny Root96427ba2013-08-16 14:02:41 -070077struct BIGNUM_Delete {
78 void operator()(BIGNUM* p) const {
79 BN_free(p);
80 }
81};
82typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
83
Kenny Root822c3a92012-03-23 16:34:39 -070084struct BIO_Delete {
85 void operator()(BIO* p) const {
86 BIO_free(p);
87 }
88};
89typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
90
91struct EVP_PKEY_Delete {
92 void operator()(EVP_PKEY* p) const {
93 EVP_PKEY_free(p);
94 }
95};
96typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
97
98struct PKCS8_PRIV_KEY_INFO_Delete {
99 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
100 PKCS8_PRIV_KEY_INFO_free(p);
101 }
102};
103typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
104
105
Kenny Root70e3a862012-02-15 17:20:23 -0800106static int keymaster_device_initialize(keymaster_device_t** dev) {
107 int rc;
108
109 const hw_module_t* mod;
110 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
111 if (rc) {
112 ALOGE("could not find any keystore module");
113 goto out;
114 }
115
116 rc = keymaster_open(mod, dev);
117 if (rc) {
118 ALOGE("could not open keymaster device in %s (%s)",
119 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
120 goto out;
121 }
122
123 return 0;
124
125out:
126 *dev = NULL;
127 return rc;
128}
129
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800130static int fallback_keymaster_device_initialize(keymaster_device_t** dev) {
131 int rc;
132 rc = openssl_open(reinterpret_cast<hw_module_t*>(&softkeymaster_module),
133 KEYSTORE_KEYMASTER,
134 reinterpret_cast<hw_device_t**>(dev));
135 if (rc) {
136 ALOGE("could not open softkeymaster device (%s)",
137 strerror(-rc));
138 goto out;
139 }
140 return 0;
141out:
142 *dev = NULL;
143 return rc;
144}
145
Kenny Root70e3a862012-02-15 17:20:23 -0800146static void keymaster_device_release(keymaster_device_t* dev) {
147 keymaster_close(dev);
148}
149
Kenny Root07438c82012-11-02 15:41:02 -0700150/***************
151 * PERMISSIONS *
152 ***************/
153
154/* Here are the permissions, actions, users, and the main function. */
155typedef enum {
Robin Lee4e865752014-08-19 17:37:55 +0100156 P_TEST = 1 << 0,
157 P_GET = 1 << 1,
158 P_INSERT = 1 << 2,
159 P_DELETE = 1 << 3,
160 P_EXIST = 1 << 4,
161 P_SAW = 1 << 5,
162 P_RESET = 1 << 6,
163 P_PASSWORD = 1 << 7,
164 P_LOCK = 1 << 8,
165 P_UNLOCK = 1 << 9,
166 P_ZERO = 1 << 10,
167 P_SIGN = 1 << 11,
168 P_VERIFY = 1 << 12,
169 P_GRANT = 1 << 13,
170 P_DUPLICATE = 1 << 14,
171 P_CLEAR_UID = 1 << 15,
172 P_RESET_UID = 1 << 16,
173 P_SYNC_UID = 1 << 17,
174 P_PASSWORD_UID = 1 << 18,
Kenny Root07438c82012-11-02 15:41:02 -0700175} perm_t;
176
177static struct user_euid {
178 uid_t uid;
179 uid_t euid;
180} user_euids[] = {
181 {AID_VPN, AID_SYSTEM},
182 {AID_WIFI, AID_SYSTEM},
183 {AID_ROOT, AID_SYSTEM},
184};
185
Riley Spahneaabae92014-06-30 12:39:52 -0700186/* perm_labels associcated with keystore_key SELinux class verbs. */
187const char *perm_labels[] = {
188 "test",
189 "get",
190 "insert",
191 "delete",
192 "exist",
193 "saw",
194 "reset",
195 "password",
196 "lock",
197 "unlock",
198 "zero",
199 "sign",
200 "verify",
201 "grant",
202 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100203 "clear_uid",
204 "reset_uid",
205 "sync_uid",
206 "password_uid",
Riley Spahneaabae92014-06-30 12:39:52 -0700207};
208
Kenny Root07438c82012-11-02 15:41:02 -0700209static struct user_perm {
210 uid_t uid;
211 perm_t perms;
212} user_perms[] = {
213 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
214 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
215 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
216 {AID_ROOT, static_cast<perm_t>(P_GET) },
217};
218
219static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
220 | P_VERIFY);
221
Riley Spahneaabae92014-06-30 12:39:52 -0700222static char *tctx;
223static int ks_is_selinux_enabled;
224
225static const char *get_perm_label(perm_t perm) {
226 unsigned int index = ffs(perm);
227 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
228 return perm_labels[index - 1];
229 } else {
230 ALOGE("Keystore: Failed to retrieve permission label.\n");
231 abort();
232 }
233}
234
Kenny Root655b9582013-04-04 08:37:42 -0700235/**
236 * Returns the app ID (in the Android multi-user sense) for the current
237 * UNIX UID.
238 */
239static uid_t get_app_id(uid_t uid) {
240 return uid % AID_USER;
241}
242
243/**
244 * Returns the user ID (in the Android multi-user sense) for the current
245 * UNIX UID.
246 */
247static uid_t get_user_id(uid_t uid) {
248 return uid / AID_USER;
249}
250
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700251static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700252 if (!ks_is_selinux_enabled) {
253 return true;
254 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000255
Riley Spahneaabae92014-06-30 12:39:52 -0700256 char *sctx = NULL;
257 const char *selinux_class = "keystore_key";
258 const char *str_perm = get_perm_label(perm);
259
260 if (!str_perm) {
261 return false;
262 }
263
264 if (getpidcon(spid, &sctx) != 0) {
265 ALOGE("SELinux: Failed to get source pid context.\n");
266 return false;
267 }
268
269 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
270 NULL) == 0;
271 freecon(sctx);
272 return allowed;
273}
274
275static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700276 // All system users are equivalent for multi-user support.
277 if (get_app_id(uid) == AID_SYSTEM) {
278 uid = AID_SYSTEM;
279 }
280
Kenny Root07438c82012-11-02 15:41:02 -0700281 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
282 struct user_perm user = user_perms[i];
283 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700284 return (user.perms & perm) &&
285 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700286 }
287 }
288
Riley Spahneaabae92014-06-30 12:39:52 -0700289 return (DEFAULT_PERMS & perm) &&
290 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700291}
292
Kenny Root49468902013-03-19 13:41:33 -0700293/**
294 * Returns the UID that the callingUid should act as. This is here for
295 * legacy support of the WiFi and VPN systems and should be removed
296 * when WiFi can operate in its own namespace.
297 */
Kenny Root07438c82012-11-02 15:41:02 -0700298static uid_t get_keystore_euid(uid_t uid) {
299 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
300 struct user_euid user = user_euids[i];
301 if (user.uid == uid) {
302 return user.euid;
303 }
304 }
305
306 return uid;
307}
308
Kenny Root49468902013-03-19 13:41:33 -0700309/**
310 * Returns true if the callingUid is allowed to interact in the targetUid's
311 * namespace.
312 */
313static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
314 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
315 struct user_euid user = user_euids[i];
316 if (user.euid == callingUid && user.uid == targetUid) {
317 return true;
318 }
319 }
320
321 return false;
322}
323
Kenny Root007cb232014-07-30 16:59:42 -0700324/**
325 * Allow the system to perform some privileged tasks that have to do with
326 * system maintenance. This should not be used for any function that uses
327 * the keys in any way (e.g., signing).
328 */
329static bool is_self_or_system(uid_t callingUid, uid_t targetUid) {
330 return callingUid == targetUid || callingUid == AID_SYSTEM;
331}
332
Kenny Roota91203b2012-02-15 15:00:46 -0800333/* Here is the encoding of keys. This is necessary in order to allow arbitrary
334 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
335 * into two bytes. The first byte is one of [+-.] which represents the first
336 * two bits of the character. The second byte encodes the rest of the bits into
337 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
338 * that Base64 cannot be used here due to the need of prefix match on keys. */
339
Kenny Root655b9582013-04-04 08:37:42 -0700340static size_t encode_key_length(const android::String8& keyName) {
341 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
342 size_t length = keyName.length();
343 for (int i = length; i > 0; --i, ++in) {
344 if (*in < '0' || *in > '~') {
345 ++length;
346 }
347 }
348 return length;
349}
350
Kenny Root07438c82012-11-02 15:41:02 -0700351static int encode_key(char* out, const android::String8& keyName) {
352 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
353 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800354 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700355 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800356 *out = '+' + (*in >> 6);
357 *++out = '0' + (*in & 0x3F);
358 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700359 } else {
360 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800361 }
362 }
363 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800364 return length;
365}
366
Kenny Root07438c82012-11-02 15:41:02 -0700367/*
368 * Converts from the "escaped" format on disk to actual name.
369 * This will be smaller than the input string.
370 *
371 * Characters that should combine with the next at the end will be truncated.
372 */
373static size_t decode_key_length(const char* in, size_t length) {
374 size_t outLength = 0;
375
376 for (const char* end = in + length; in < end; in++) {
377 /* This combines with the next character. */
378 if (*in < '0' || *in > '~') {
379 continue;
380 }
381
382 outLength++;
383 }
384 return outLength;
385}
386
387static void decode_key(char* out, const char* in, size_t length) {
388 for (const char* end = in + length; in < end; in++) {
389 if (*in < '0' || *in > '~') {
390 /* Truncate combining characters at the end. */
391 if (in + 1 >= end) {
392 break;
393 }
394
395 *out = (*in++ - '+') << 6;
396 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800397 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700398 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800399 }
400 }
401 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800402}
403
404static size_t readFully(int fd, uint8_t* data, size_t size) {
405 size_t remaining = size;
406 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800407 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800408 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800409 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800410 }
411 data += n;
412 remaining -= n;
413 }
414 return size;
415}
416
417static size_t writeFully(int fd, uint8_t* data, size_t size) {
418 size_t remaining = size;
419 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800420 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
421 if (n < 0) {
422 ALOGW("write failed: %s", strerror(errno));
423 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800424 }
425 data += n;
426 remaining -= n;
427 }
428 return size;
429}
430
431class Entropy {
432public:
433 Entropy() : mRandom(-1) {}
434 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800435 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800436 close(mRandom);
437 }
438 }
439
440 bool open() {
441 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800442 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
443 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800444 ALOGE("open: %s: %s", randomDevice, strerror(errno));
445 return false;
446 }
447 return true;
448 }
449
Kenny Root51878182012-03-13 12:53:19 -0700450 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800451 return (readFully(mRandom, data, size) == size);
452 }
453
454private:
455 int mRandom;
456};
457
458/* Here is the file format. There are two parts in blob.value, the secret and
459 * the description. The secret is stored in ciphertext, and its original size
460 * can be found in blob.length. The description is stored after the secret in
461 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700462 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700463 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800464 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
465 * and decryptBlob(). Thus they should not be accessed from outside. */
466
Kenny Root822c3a92012-03-23 16:34:39 -0700467/* ** Note to future implementors of encryption: **
468 * Currently this is the construction:
469 * metadata || Enc(MD5(data) || data)
470 *
471 * This should be the construction used for encrypting if re-implementing:
472 *
473 * Derive independent keys for encryption and MAC:
474 * Kenc = AES_encrypt(masterKey, "Encrypt")
475 * Kmac = AES_encrypt(masterKey, "MAC")
476 *
477 * Store this:
478 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
479 * HMAC(Kmac, metadata || Enc(data))
480 */
Kenny Roota91203b2012-02-15 15:00:46 -0800481struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700482 uint8_t version;
483 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700484 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800485 uint8_t info;
486 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700487 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800488 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700489 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800490 int32_t length; // in network byte order when encrypted
491 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
492};
493
Kenny Root822c3a92012-03-23 16:34:39 -0700494typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700495 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700496 TYPE_GENERIC = 1,
497 TYPE_MASTER_KEY = 2,
498 TYPE_KEY_PAIR = 3,
499} BlobType;
500
Kenny Rootf9119d62013-04-03 09:22:15 -0700501static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700502
Kenny Roota91203b2012-02-15 15:00:46 -0800503class Blob {
504public:
Kenny Root07438c82012-11-02 15:41:02 -0700505 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
506 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800507 memset(&mBlob, 0, sizeof(mBlob));
Kenny Roota91203b2012-02-15 15:00:46 -0800508 mBlob.length = valueLength;
509 memcpy(mBlob.value, value, valueLength);
510
511 mBlob.info = infoLength;
512 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700513
Kenny Root07438c82012-11-02 15:41:02 -0700514 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700515 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700516
Kenny Rootee8068b2013-10-07 09:49:15 -0700517 if (type == TYPE_MASTER_KEY) {
518 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
519 } else {
520 mBlob.flags = KEYSTORE_FLAG_NONE;
521 }
Kenny Roota91203b2012-02-15 15:00:46 -0800522 }
523
524 Blob(blob b) {
525 mBlob = b;
526 }
527
Alex Klyubin1773b442015-02-20 12:33:33 -0800528 Blob() {
529 memset(&mBlob, 0, sizeof(mBlob));
530 }
Kenny Roota91203b2012-02-15 15:00:46 -0800531
Kenny Root51878182012-03-13 12:53:19 -0700532 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800533 return mBlob.value;
534 }
535
Kenny Root51878182012-03-13 12:53:19 -0700536 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800537 return mBlob.length;
538 }
539
Kenny Root51878182012-03-13 12:53:19 -0700540 const uint8_t* getInfo() const {
541 return mBlob.value + mBlob.length;
542 }
543
544 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800545 return mBlob.info;
546 }
547
Kenny Root822c3a92012-03-23 16:34:39 -0700548 uint8_t getVersion() const {
549 return mBlob.version;
550 }
551
Kenny Rootf9119d62013-04-03 09:22:15 -0700552 bool isEncrypted() const {
553 if (mBlob.version < 2) {
554 return true;
555 }
556
557 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
558 }
559
560 void setEncrypted(bool encrypted) {
561 if (encrypted) {
562 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
563 } else {
564 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
565 }
566 }
567
Kenny Root17208e02013-09-04 13:56:03 -0700568 bool isFallback() const {
569 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
570 }
571
572 void setFallback(bool fallback) {
573 if (fallback) {
574 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
575 } else {
576 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
577 }
578 }
579
Kenny Root822c3a92012-03-23 16:34:39 -0700580 void setVersion(uint8_t version) {
581 mBlob.version = version;
582 }
583
584 BlobType getType() const {
585 return BlobType(mBlob.type);
586 }
587
588 void setType(BlobType type) {
589 mBlob.type = uint8_t(type);
590 }
591
Kenny Rootf9119d62013-04-03 09:22:15 -0700592 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
593 ALOGV("writing blob %s", filename);
594 if (isEncrypted()) {
595 if (state != STATE_NO_ERROR) {
596 ALOGD("couldn't insert encrypted blob while not unlocked");
597 return LOCKED;
598 }
599
600 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
601 ALOGW("Could not read random data for: %s", filename);
602 return SYSTEM_ERROR;
603 }
Kenny Roota91203b2012-02-15 15:00:46 -0800604 }
605
606 // data includes the value and the value's length
607 size_t dataLength = mBlob.length + sizeof(mBlob.length);
608 // pad data to the AES_BLOCK_SIZE
609 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
610 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
611 // encrypted data includes the digest value
612 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
613 // move info after space for padding
614 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
615 // zero padding area
616 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
617
618 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800619
Kenny Rootf9119d62013-04-03 09:22:15 -0700620 if (isEncrypted()) {
621 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800622
Kenny Rootf9119d62013-04-03 09:22:15 -0700623 uint8_t vector[AES_BLOCK_SIZE];
624 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
625 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
626 aes_key, vector, AES_ENCRYPT);
627 }
628
Kenny Roota91203b2012-02-15 15:00:46 -0800629 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
630 size_t fileLength = encryptedLength + headerLength + mBlob.info;
631
632 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800633 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
634 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
635 if (out < 0) {
636 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800637 return SYSTEM_ERROR;
638 }
639 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
640 if (close(out) != 0) {
641 return SYSTEM_ERROR;
642 }
643 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800644 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800645 unlink(tmpFileName);
646 return SYSTEM_ERROR;
647 }
Kenny Root150ca932012-11-14 14:29:02 -0800648 if (rename(tmpFileName, filename) == -1) {
649 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
650 return SYSTEM_ERROR;
651 }
652 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800653 }
654
Kenny Rootf9119d62013-04-03 09:22:15 -0700655 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
656 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800657 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
658 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800659 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
660 }
661 // fileLength may be less than sizeof(mBlob) since the in
662 // memory version has extra padding to tolerate rounding up to
663 // the AES_BLOCK_SIZE
664 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
665 if (close(in) != 0) {
666 return SYSTEM_ERROR;
667 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700668
669 if (isEncrypted() && (state != STATE_NO_ERROR)) {
670 return LOCKED;
671 }
672
Kenny Roota91203b2012-02-15 15:00:46 -0800673 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
674 if (fileLength < headerLength) {
675 return VALUE_CORRUPTED;
676 }
677
678 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700679 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800680 return VALUE_CORRUPTED;
681 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700682
683 ssize_t digestedLength;
684 if (isEncrypted()) {
685 if (encryptedLength % AES_BLOCK_SIZE != 0) {
686 return VALUE_CORRUPTED;
687 }
688
689 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
690 mBlob.vector, AES_DECRYPT);
691 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
692 uint8_t computedDigest[MD5_DIGEST_LENGTH];
693 MD5(mBlob.digested, digestedLength, computedDigest);
694 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
695 return VALUE_CORRUPTED;
696 }
697 } else {
698 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800699 }
700
701 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
702 mBlob.length = ntohl(mBlob.length);
703 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
704 return VALUE_CORRUPTED;
705 }
706 if (mBlob.info != 0) {
707 // move info from after padding to after data
708 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
709 }
Kenny Root07438c82012-11-02 15:41:02 -0700710 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800711 }
712
713private:
714 struct blob mBlob;
715};
716
Kenny Root655b9582013-04-04 08:37:42 -0700717class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800718public:
Kenny Root655b9582013-04-04 08:37:42 -0700719 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
720 asprintf(&mUserDir, "user_%u", mUserId);
721 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
722 }
723
724 ~UserState() {
725 free(mUserDir);
726 free(mMasterKeyFile);
727 }
728
729 bool initialize() {
730 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
731 ALOGE("Could not create directory '%s'", mUserDir);
732 return false;
733 }
734
735 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800736 setState(STATE_LOCKED);
737 } else {
738 setState(STATE_UNINITIALIZED);
739 }
Kenny Root70e3a862012-02-15 17:20:23 -0800740
Kenny Root655b9582013-04-04 08:37:42 -0700741 return true;
742 }
743
744 uid_t getUserId() const {
745 return mUserId;
746 }
747
748 const char* getUserDirName() const {
749 return mUserDir;
750 }
751
752 const char* getMasterKeyFileName() const {
753 return mMasterKeyFile;
754 }
755
756 void setState(State state) {
757 mState = state;
758 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
759 mRetry = MAX_RETRY;
760 }
Kenny Roota91203b2012-02-15 15:00:46 -0800761 }
762
Kenny Root51878182012-03-13 12:53:19 -0700763 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800764 return mState;
765 }
766
Kenny Root51878182012-03-13 12:53:19 -0700767 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800768 return mRetry;
769 }
770
Kenny Root655b9582013-04-04 08:37:42 -0700771 void zeroizeMasterKeysInMemory() {
772 memset(mMasterKey, 0, sizeof(mMasterKey));
773 memset(mSalt, 0, sizeof(mSalt));
774 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
775 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800776 }
777
Kenny Root655b9582013-04-04 08:37:42 -0700778 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
779 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800780 return SYSTEM_ERROR;
781 }
Kenny Root655b9582013-04-04 08:37:42 -0700782 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800783 if (response != NO_ERROR) {
784 return response;
785 }
786 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700787 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800788 }
789
Robin Lee4e865752014-08-19 17:37:55 +0100790 ResponseCode copyMasterKey(UserState* src) {
791 if (mState != STATE_UNINITIALIZED) {
792 return ::SYSTEM_ERROR;
793 }
794 if (src->getState() != STATE_NO_ERROR) {
795 return ::SYSTEM_ERROR;
796 }
797 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
798 setupMasterKeys();
799 return ::NO_ERROR;
800 }
801
Kenny Root655b9582013-04-04 08:37:42 -0700802 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800803 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
804 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
805 AES_KEY passwordAesKey;
806 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700807 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700808 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800809 }
810
Kenny Root655b9582013-04-04 08:37:42 -0700811 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
812 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800813 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800814 return SYSTEM_ERROR;
815 }
816
817 // we read the raw blob to just to get the salt to generate
818 // the AES key, then we create the Blob to use with decryptBlob
819 blob rawBlob;
820 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
821 if (close(in) != 0) {
822 return SYSTEM_ERROR;
823 }
824 // find salt at EOF if present, otherwise we have an old file
825 uint8_t* salt;
826 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
827 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
828 } else {
829 salt = NULL;
830 }
831 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
832 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
833 AES_KEY passwordAesKey;
834 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
835 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700836 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
837 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800838 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700839 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800840 }
841 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
842 // if salt was missing, generate one and write a new master key file with the salt.
843 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700844 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800845 return SYSTEM_ERROR;
846 }
Kenny Root655b9582013-04-04 08:37:42 -0700847 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800848 }
849 if (response == NO_ERROR) {
850 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
851 setupMasterKeys();
852 }
853 return response;
854 }
855 if (mRetry <= 0) {
856 reset();
857 return UNINITIALIZED;
858 }
859 --mRetry;
860 switch (mRetry) {
861 case 0: return WRONG_PASSWORD_0;
862 case 1: return WRONG_PASSWORD_1;
863 case 2: return WRONG_PASSWORD_2;
864 case 3: return WRONG_PASSWORD_3;
865 default: return WRONG_PASSWORD_3;
866 }
867 }
868
Kenny Root655b9582013-04-04 08:37:42 -0700869 AES_KEY* getEncryptionKey() {
870 return &mMasterKeyEncryption;
871 }
872
873 AES_KEY* getDecryptionKey() {
874 return &mMasterKeyDecryption;
875 }
876
Kenny Roota91203b2012-02-15 15:00:46 -0800877 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700878 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800879 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700880 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800881 return false;
882 }
Kenny Root655b9582013-04-04 08:37:42 -0700883
884 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800885 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700886 // We only care about files.
887 if (file->d_type != DT_REG) {
888 continue;
889 }
890
891 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700892 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700893 continue;
894 }
895
896 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800897 }
898 closedir(dir);
899 return true;
900 }
901
Kenny Root655b9582013-04-04 08:37:42 -0700902private:
903 static const int MASTER_KEY_SIZE_BYTES = 16;
904 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
905
906 static const int MAX_RETRY = 4;
907 static const size_t SALT_SIZE = 16;
908
909 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
910 uint8_t* salt) {
911 size_t saltSize;
912 if (salt != NULL) {
913 saltSize = SALT_SIZE;
914 } else {
915 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
916 salt = (uint8_t*) "keystore";
917 // sizeof = 9, not strlen = 8
918 saltSize = sizeof("keystore");
919 }
920
921 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
922 saltSize, 8192, keySize, key);
923 }
924
925 bool generateSalt(Entropy* entropy) {
926 return entropy->generate_random_data(mSalt, sizeof(mSalt));
927 }
928
929 bool generateMasterKey(Entropy* entropy) {
930 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
931 return false;
932 }
933 if (!generateSalt(entropy)) {
934 return false;
935 }
936 return true;
937 }
938
939 void setupMasterKeys() {
940 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
941 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
942 setState(STATE_NO_ERROR);
943 }
944
945 uid_t mUserId;
946
947 char* mUserDir;
948 char* mMasterKeyFile;
949
950 State mState;
951 int8_t mRetry;
952
953 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
954 uint8_t mSalt[SALT_SIZE];
955
956 AES_KEY mMasterKeyEncryption;
957 AES_KEY mMasterKeyDecryption;
958};
959
960typedef struct {
961 uint32_t uid;
962 const uint8_t* filename;
963} grant_t;
964
965class KeyStore {
966public:
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800967 KeyStore(Entropy* entropy, keymaster_device_t* device, keymaster_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700968 : mEntropy(entropy)
969 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800970 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700971 {
972 memset(&mMetaData, '\0', sizeof(mMetaData));
973 }
974
975 ~KeyStore() {
976 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
977 it != mGrants.end(); it++) {
978 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700979 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800980 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700981
982 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
983 it != mMasterKeys.end(); it++) {
984 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700985 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800986 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700987 }
988
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800989 keymaster_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700990 return mDevice;
991 }
992
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800993 keymaster_device_t *getFallbackDevice() const {
994 return mFallbackDevice;
995 }
996
997 keymaster_device_t *getDeviceForBlob(const Blob& blob) const {
998 return blob.isFallback() ? mFallbackDevice: mDevice;
999 }
1000
Kenny Root655b9582013-04-04 08:37:42 -07001001 ResponseCode initialize() {
1002 readMetaData();
1003 if (upgradeKeystore()) {
1004 writeMetaData();
1005 }
1006
1007 return ::NO_ERROR;
1008 }
1009
1010 State getState(uid_t uid) {
1011 return getUserState(uid)->getState();
1012 }
1013
1014 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
1015 UserState* userState = getUserState(uid);
1016 return userState->initialize(pw, mEntropy);
1017 }
1018
Robin Lee4e865752014-08-19 17:37:55 +01001019 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
1020 UserState *userState = getUserState(uid);
1021 UserState *initState = getUserState(src);
1022 return userState->copyMasterKey(initState);
1023 }
1024
Kenny Root655b9582013-04-04 08:37:42 -07001025 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001026 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001027 return userState->writeMasterKey(pw, mEntropy);
1028 }
1029
1030 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001031 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001032 return userState->readMasterKey(pw, mEntropy);
1033 }
1034
1035 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001036 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001037 encode_key(encoded, keyName);
1038 return android::String8(encoded);
1039 }
1040
1041 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001042 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001043 encode_key(encoded, keyName);
1044 return android::String8::format("%u_%s", uid, encoded);
1045 }
1046
1047 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001048 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001049 encode_key(encoded, keyName);
1050 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1051 encoded);
1052 }
1053
1054 bool reset(uid_t uid) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001055 android::String8 prefix("");
1056 android::Vector<android::String16> aliases;
1057 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1058 return ::SYSTEM_ERROR;
1059 }
1060
Kenny Root655b9582013-04-04 08:37:42 -07001061 UserState* userState = getUserState(uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001062 for (uint32_t i = 0; i < aliases.size(); i++) {
1063 android::String8 filename(aliases[i]);
1064 filename = android::String8::format("%s/%s", userState->getUserDirName(),
1065 getKeyName(filename).string());
1066 del(filename, ::TYPE_ANY, uid);
1067 }
1068
Kenny Root655b9582013-04-04 08:37:42 -07001069 userState->zeroizeMasterKeysInMemory();
1070 userState->setState(STATE_UNINITIALIZED);
1071 return userState->reset();
1072 }
1073
1074 bool isEmpty(uid_t uid) const {
1075 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001076 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001077 return true;
1078 }
1079
1080 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001081 if (!dir) {
1082 return true;
1083 }
Kenny Root31e27462014-09-10 11:28:03 -07001084
Kenny Roota91203b2012-02-15 15:00:46 -08001085 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001086 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001087 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001088 // We only care about files.
1089 if (file->d_type != DT_REG) {
1090 continue;
1091 }
1092
1093 // Skip anything that starts with a "."
1094 if (file->d_name[0] == '.') {
1095 continue;
1096 }
1097
Kenny Root31e27462014-09-10 11:28:03 -07001098 result = false;
1099 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001100 }
1101 closedir(dir);
1102 return result;
1103 }
1104
Kenny Root655b9582013-04-04 08:37:42 -07001105 void lock(uid_t uid) {
1106 UserState* userState = getUserState(uid);
1107 userState->zeroizeMasterKeysInMemory();
1108 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001109 }
1110
Kenny Root655b9582013-04-04 08:37:42 -07001111 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1112 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001113 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1114 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001115 if (rc != NO_ERROR) {
1116 return rc;
1117 }
1118
1119 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001120 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001121 /* If we upgrade the key, we need to write it to disk again. Then
1122 * it must be read it again since the blob is encrypted each time
1123 * it's written.
1124 */
Kenny Root655b9582013-04-04 08:37:42 -07001125 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1126 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001127 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1128 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001129 return rc;
1130 }
1131 }
Kenny Root822c3a92012-03-23 16:34:39 -07001132 }
1133
Kenny Root17208e02013-09-04 13:56:03 -07001134 /*
1135 * This will upgrade software-backed keys to hardware-backed keys when
1136 * the HAL for the device supports the newer key types.
1137 */
1138 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1139 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1140 && keyBlob->isFallback()) {
1141 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1142 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1143
1144 // The HAL allowed the import, reget the key to have the "fresh"
1145 // version.
1146 if (imported == NO_ERROR) {
1147 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1148 }
1149 }
1150
Kenny Rootd53bc922013-03-21 14:10:15 -07001151 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001152 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1153 return KEY_NOT_FOUND;
1154 }
1155
1156 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001157 }
1158
Kenny Root655b9582013-04-04 08:37:42 -07001159 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1160 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001161 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1162 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001163 }
1164
Robin Lee4b84fdc2014-09-24 11:56:57 +01001165 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1166 Blob keyBlob;
1167 ResponseCode rc = get(filename, &keyBlob, type, uid);
1168 if (rc != ::NO_ERROR) {
1169 return rc;
1170 }
1171
1172 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1173 // A device doesn't have to implement delete_keypair.
1174 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1175 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1176 rc = ::SYSTEM_ERROR;
1177 }
1178 }
1179 }
1180 if (rc != ::NO_ERROR) {
1181 return rc;
1182 }
1183
1184 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1185 }
1186
1187 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1188 uid_t uid) {
1189
1190 UserState* userState = getUserState(uid);
1191 size_t n = prefix.length();
1192
1193 DIR* dir = opendir(userState->getUserDirName());
1194 if (!dir) {
1195 ALOGW("can't open directory for user: %s", strerror(errno));
1196 return ::SYSTEM_ERROR;
1197 }
1198
1199 struct dirent* file;
1200 while ((file = readdir(dir)) != NULL) {
1201 // We only care about files.
1202 if (file->d_type != DT_REG) {
1203 continue;
1204 }
1205
1206 // Skip anything that starts with a "."
1207 if (file->d_name[0] == '.') {
1208 continue;
1209 }
1210
1211 if (!strncmp(prefix.string(), file->d_name, n)) {
1212 const char* p = &file->d_name[n];
1213 size_t plen = strlen(p);
1214
1215 size_t extra = decode_key_length(p, plen);
1216 char *match = (char*) malloc(extra + 1);
1217 if (match != NULL) {
1218 decode_key(match, p, plen);
1219 matches->push(android::String16(match, extra));
1220 free(match);
1221 } else {
1222 ALOGW("could not allocate match of size %zd", extra);
1223 }
1224 }
1225 }
1226 closedir(dir);
1227 return ::NO_ERROR;
1228 }
1229
Kenny Root07438c82012-11-02 15:41:02 -07001230 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001231 const grant_t* existing = getGrant(filename, granteeUid);
1232 if (existing == NULL) {
1233 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001234 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001235 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001236 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001237 }
1238 }
1239
Kenny Root07438c82012-11-02 15:41:02 -07001240 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001241 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1242 it != mGrants.end(); it++) {
1243 grant_t* grant = *it;
1244 if (grant->uid == granteeUid
1245 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1246 mGrants.erase(it);
1247 return true;
1248 }
Kenny Root70e3a862012-02-15 17:20:23 -08001249 }
Kenny Root70e3a862012-02-15 17:20:23 -08001250 return false;
1251 }
1252
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001253 bool hasGrant(const char* filename, const uid_t uid) const {
1254 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001255 }
1256
Kenny Rootf9119d62013-04-03 09:22:15 -07001257 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1258 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001259 uint8_t* data;
1260 size_t dataLength;
1261 int rc;
1262
1263 if (mDevice->import_keypair == NULL) {
1264 ALOGE("Keymaster doesn't support import!");
1265 return SYSTEM_ERROR;
1266 }
1267
Kenny Root17208e02013-09-04 13:56:03 -07001268 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001269 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001270 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001271 /*
1272 * Maybe the device doesn't support this type of key. Try to use the
1273 * software fallback keymaster implementation. This is a little bit
1274 * lazier than checking the PKCS#8 key type, but the software
1275 * implementation will do that anyway.
1276 */
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001277 rc = mFallbackDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001278 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001279
1280 if (rc) {
1281 ALOGE("Error while importing keypair: %d", rc);
1282 return SYSTEM_ERROR;
1283 }
Kenny Root822c3a92012-03-23 16:34:39 -07001284 }
1285
1286 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1287 free(data);
1288
Kenny Rootf9119d62013-04-03 09:22:15 -07001289 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001290 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001291
Kenny Root655b9582013-04-04 08:37:42 -07001292 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001293 }
1294
Kenny Root1b0e3932013-09-05 13:06:32 -07001295 bool isHardwareBacked(const android::String16& keyType) const {
1296 if (mDevice == NULL) {
1297 ALOGW("can't get keymaster device");
1298 return false;
1299 }
1300
1301 if (sRSAKeyType == keyType) {
1302 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1303 } else {
1304 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1305 && (mDevice->common.module->module_api_version
1306 >= KEYMASTER_MODULE_API_VERSION_0_2);
1307 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001308 }
1309
Kenny Root655b9582013-04-04 08:37:42 -07001310 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1311 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001312 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001313
1314 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1315 if (responseCode == NO_ERROR) {
1316 return responseCode;
1317 }
1318
1319 // If this is one of the legacy UID->UID mappings, use it.
1320 uid_t euid = get_keystore_euid(uid);
1321 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001322 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001323 responseCode = get(filepath8.string(), keyBlob, type, uid);
1324 if (responseCode == NO_ERROR) {
1325 return responseCode;
1326 }
1327 }
1328
1329 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001330 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001331 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001332 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001333 if (end[0] != '_' || end[1] == 0) {
1334 return KEY_NOT_FOUND;
1335 }
Kenny Root86b16e82013-09-09 11:15:54 -07001336 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1337 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001338 if (!hasGrant(filepath8.string(), uid)) {
1339 return responseCode;
1340 }
1341
1342 // It is a granted key. Try to load it.
1343 return get(filepath8.string(), keyBlob, type, uid);
1344 }
1345
1346 /**
1347 * Returns any existing UserState or creates it if it doesn't exist.
1348 */
1349 UserState* getUserState(uid_t uid) {
1350 uid_t userId = get_user_id(uid);
1351
1352 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1353 it != mMasterKeys.end(); it++) {
1354 UserState* state = *it;
1355 if (state->getUserId() == userId) {
1356 return state;
1357 }
1358 }
1359
1360 UserState* userState = new UserState(userId);
1361 if (!userState->initialize()) {
1362 /* There's not much we can do if initialization fails. Trying to
1363 * unlock the keystore for that user will fail as well, so any
1364 * subsequent request for this user will just return SYSTEM_ERROR.
1365 */
1366 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1367 }
1368 mMasterKeys.add(userState);
1369 return userState;
1370 }
1371
1372 /**
1373 * Returns NULL if the UserState doesn't already exist.
1374 */
1375 const UserState* getUserState(uid_t uid) const {
1376 uid_t userId = get_user_id(uid);
1377
1378 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1379 it != mMasterKeys.end(); it++) {
1380 UserState* state = *it;
1381 if (state->getUserId() == userId) {
1382 return state;
1383 }
1384 }
1385
1386 return NULL;
1387 }
1388
Kenny Roota91203b2012-02-15 15:00:46 -08001389private:
Kenny Root655b9582013-04-04 08:37:42 -07001390 static const char* sOldMasterKey;
1391 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001392 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001393 Entropy* mEntropy;
1394
Kenny Root70e3a862012-02-15 17:20:23 -08001395 keymaster_device_t* mDevice;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001396 keymaster_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001397
Kenny Root655b9582013-04-04 08:37:42 -07001398 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001399
Kenny Root655b9582013-04-04 08:37:42 -07001400 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001401
Kenny Root655b9582013-04-04 08:37:42 -07001402 typedef struct {
1403 uint32_t version;
1404 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001405
Kenny Root655b9582013-04-04 08:37:42 -07001406 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001407
Kenny Root655b9582013-04-04 08:37:42 -07001408 const grant_t* getGrant(const char* filename, uid_t uid) const {
1409 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1410 it != mGrants.end(); it++) {
1411 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001412 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001413 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001414 return grant;
1415 }
1416 }
Kenny Root70e3a862012-02-15 17:20:23 -08001417 return NULL;
1418 }
1419
Kenny Root822c3a92012-03-23 16:34:39 -07001420 /**
1421 * Upgrade code. This will upgrade the key from the current version
1422 * to whatever is newest.
1423 */
Kenny Root655b9582013-04-04 08:37:42 -07001424 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1425 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001426 bool updated = false;
1427 uint8_t version = oldVersion;
1428
1429 /* From V0 -> V1: All old types were unknown */
1430 if (version == 0) {
1431 ALOGV("upgrading to version 1 and setting type %d", type);
1432
1433 blob->setType(type);
1434 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001435 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001436 }
1437 version = 1;
1438 updated = true;
1439 }
1440
Kenny Rootf9119d62013-04-03 09:22:15 -07001441 /* From V1 -> V2: All old keys were encrypted */
1442 if (version == 1) {
1443 ALOGV("upgrading to version 2");
1444
1445 blob->setEncrypted(true);
1446 version = 2;
1447 updated = true;
1448 }
1449
Kenny Root822c3a92012-03-23 16:34:39 -07001450 /*
1451 * If we've updated, set the key blob to the right version
1452 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001453 */
Kenny Root822c3a92012-03-23 16:34:39 -07001454 if (updated) {
1455 ALOGV("updated and writing file %s", filename);
1456 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001457 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001458
1459 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001460 }
1461
1462 /**
1463 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1464 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1465 * Then it overwrites the original blob with the new blob
1466 * format that is returned from the keymaster.
1467 */
Kenny Root655b9582013-04-04 08:37:42 -07001468 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001469 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1470 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1471 if (b.get() == NULL) {
1472 ALOGE("Problem instantiating BIO");
1473 return SYSTEM_ERROR;
1474 }
1475
1476 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1477 if (pkey.get() == NULL) {
1478 ALOGE("Couldn't read old PEM file");
1479 return SYSTEM_ERROR;
1480 }
1481
1482 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1483 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1484 if (len < 0) {
1485 ALOGE("Couldn't measure PKCS#8 length");
1486 return SYSTEM_ERROR;
1487 }
1488
Kenny Root70c98892013-02-07 09:10:36 -08001489 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1490 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001491 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1492 ALOGE("Couldn't convert to PKCS#8");
1493 return SYSTEM_ERROR;
1494 }
1495
Kenny Rootf9119d62013-04-03 09:22:15 -07001496 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1497 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001498 if (rc != NO_ERROR) {
1499 return rc;
1500 }
1501
Kenny Root655b9582013-04-04 08:37:42 -07001502 return get(filename, blob, TYPE_KEY_PAIR, uid);
1503 }
1504
1505 void readMetaData() {
1506 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1507 if (in < 0) {
1508 return;
1509 }
1510 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1511 if (fileLength != sizeof(mMetaData)) {
1512 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1513 sizeof(mMetaData));
1514 }
1515 close(in);
1516 }
1517
1518 void writeMetaData() {
1519 const char* tmpFileName = ".metadata.tmp";
1520 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1521 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1522 if (out < 0) {
1523 ALOGE("couldn't write metadata file: %s", strerror(errno));
1524 return;
1525 }
1526 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1527 if (fileLength != sizeof(mMetaData)) {
1528 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1529 sizeof(mMetaData));
1530 }
1531 close(out);
1532 rename(tmpFileName, sMetaDataFile);
1533 }
1534
1535 bool upgradeKeystore() {
1536 bool upgraded = false;
1537
1538 if (mMetaData.version == 0) {
1539 UserState* userState = getUserState(0);
1540
1541 // Initialize first so the directory is made.
1542 userState->initialize();
1543
1544 // Migrate the old .masterkey file to user 0.
1545 if (access(sOldMasterKey, R_OK) == 0) {
1546 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1547 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1548 return false;
1549 }
1550 }
1551
1552 // Initialize again in case we had a key.
1553 userState->initialize();
1554
1555 // Try to migrate existing keys.
1556 DIR* dir = opendir(".");
1557 if (!dir) {
1558 // Give up now; maybe we can upgrade later.
1559 ALOGE("couldn't open keystore's directory; something is wrong");
1560 return false;
1561 }
1562
1563 struct dirent* file;
1564 while ((file = readdir(dir)) != NULL) {
1565 // We only care about files.
1566 if (file->d_type != DT_REG) {
1567 continue;
1568 }
1569
1570 // Skip anything that starts with a "."
1571 if (file->d_name[0] == '.') {
1572 continue;
1573 }
1574
1575 // Find the current file's user.
1576 char* end;
1577 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1578 if (end[0] != '_' || end[1] == 0) {
1579 continue;
1580 }
1581 UserState* otherUser = getUserState(thisUid);
1582 if (otherUser->getUserId() != 0) {
1583 unlinkat(dirfd(dir), file->d_name, 0);
1584 }
1585
1586 // Rename the file into user directory.
1587 DIR* otherdir = opendir(otherUser->getUserDirName());
1588 if (otherdir == NULL) {
1589 ALOGW("couldn't open user directory for rename");
1590 continue;
1591 }
1592 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1593 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1594 }
1595 closedir(otherdir);
1596 }
1597 closedir(dir);
1598
1599 mMetaData.version = 1;
1600 upgraded = true;
1601 }
1602
1603 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001604 }
Kenny Roota91203b2012-02-15 15:00:46 -08001605};
1606
Kenny Root655b9582013-04-04 08:37:42 -07001607const char* KeyStore::sOldMasterKey = ".masterkey";
1608const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001609
Kenny Root1b0e3932013-09-05 13:06:32 -07001610const android::String16 KeyStore::sRSAKeyType("RSA");
1611
Kenny Root07438c82012-11-02 15:41:02 -07001612namespace android {
1613class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1614public:
1615 KeyStoreProxy(KeyStore* keyStore)
1616 : mKeyStore(keyStore)
1617 {
Kenny Roota91203b2012-02-15 15:00:46 -08001618 }
Kenny Roota91203b2012-02-15 15:00:46 -08001619
Kenny Root07438c82012-11-02 15:41:02 -07001620 void binderDied(const wp<IBinder>&) {
1621 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001622 }
Kenny Roota91203b2012-02-15 15:00:46 -08001623
Kenny Root07438c82012-11-02 15:41:02 -07001624 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001625 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001626 pid_t spid = IPCThreadState::self()->getCallingPid();
1627 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001628 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001629 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001630 }
Kenny Roota91203b2012-02-15 15:00:46 -08001631
Kenny Root655b9582013-04-04 08:37:42 -07001632 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001633 }
1634
Kenny Root07438c82012-11-02 15:41:02 -07001635 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001636 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001637 pid_t spid = IPCThreadState::self()->getCallingPid();
1638 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001639 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001640 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001641 }
Kenny Root07438c82012-11-02 15:41:02 -07001642
Kenny Root07438c82012-11-02 15:41:02 -07001643 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001644 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001645
Kenny Root655b9582013-04-04 08:37:42 -07001646 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001647 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001648 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001649 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001650 *item = NULL;
1651 *itemLength = 0;
1652 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001653 }
Kenny Roota91203b2012-02-15 15:00:46 -08001654
Kenny Root07438c82012-11-02 15:41:02 -07001655 *item = (uint8_t*) malloc(keyBlob.getLength());
1656 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1657 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001658
Kenny Root07438c82012-11-02 15:41:02 -07001659 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001660 }
1661
Kenny Rootf9119d62013-04-03 09:22:15 -07001662 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1663 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001664 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001665 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001666 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001667 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001668 return ::PERMISSION_DENIED;
1669 }
Kenny Root07438c82012-11-02 15:41:02 -07001670
Kenny Rootf9119d62013-04-03 09:22:15 -07001671 State state = mKeyStore->getState(callingUid);
1672 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1673 ALOGD("calling get in state: %d", state);
1674 return state;
1675 }
1676
Kenny Root49468902013-03-19 13:41:33 -07001677 if (targetUid == -1) {
1678 targetUid = callingUid;
1679 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001680 return ::PERMISSION_DENIED;
1681 }
1682
Kenny Root07438c82012-11-02 15:41:02 -07001683 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001684 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001685
1686 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001687 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1688
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001689 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001690 }
1691
Kenny Root49468902013-03-19 13:41:33 -07001692 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001693 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001694 pid_t spid = IPCThreadState::self()->getCallingPid();
1695 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001696 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001697 return ::PERMISSION_DENIED;
1698 }
Kenny Root70e3a862012-02-15 17:20:23 -08001699
Kenny Root49468902013-03-19 13:41:33 -07001700 if (targetUid == -1) {
1701 targetUid = callingUid;
1702 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001703 return ::PERMISSION_DENIED;
1704 }
1705
Kenny Root07438c82012-11-02 15:41:02 -07001706 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001707 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01001708 return mKeyStore->del(filename.string(), ::TYPE_GENERIC, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001709 }
1710
Kenny Root49468902013-03-19 13:41:33 -07001711 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001712 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001713 pid_t spid = IPCThreadState::self()->getCallingPid();
1714 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001715 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001716 return ::PERMISSION_DENIED;
1717 }
Kenny Root70e3a862012-02-15 17:20:23 -08001718
Kenny Root49468902013-03-19 13:41:33 -07001719 if (targetUid == -1) {
1720 targetUid = callingUid;
1721 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001722 return ::PERMISSION_DENIED;
1723 }
1724
Kenny Root07438c82012-11-02 15:41:02 -07001725 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001726 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001727
Kenny Root655b9582013-04-04 08:37:42 -07001728 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001729 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1730 }
1731 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001732 }
1733
Kenny Root49468902013-03-19 13:41:33 -07001734 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001735 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001736 pid_t spid = IPCThreadState::self()->getCallingPid();
1737 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001738 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001739 return ::PERMISSION_DENIED;
1740 }
Kenny Root70e3a862012-02-15 17:20:23 -08001741
Kenny Root49468902013-03-19 13:41:33 -07001742 if (targetUid == -1) {
1743 targetUid = callingUid;
1744 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001745 return ::PERMISSION_DENIED;
1746 }
1747
Kenny Root07438c82012-11-02 15:41:02 -07001748 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001749 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001750
Robin Lee4b84fdc2014-09-24 11:56:57 +01001751 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1752 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001753 }
Kenny Root07438c82012-11-02 15:41:02 -07001754 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001755 }
1756
Kenny Root07438c82012-11-02 15:41:02 -07001757 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001758 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001759 pid_t spid = IPCThreadState::self()->getCallingPid();
1760 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001761 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001762 return ::PERMISSION_DENIED;
1763 }
1764
Robin Lee4b84fdc2014-09-24 11:56:57 +01001765 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001766 }
1767
Kenny Root07438c82012-11-02 15:41:02 -07001768 /*
1769 * Here is the history. To improve the security, the parameters to generate the
1770 * master key has been changed. To make a seamless transition, we update the
1771 * file using the same password when the user unlock it for the first time. If
1772 * any thing goes wrong during the transition, the new file will not overwrite
1773 * the old one. This avoids permanent damages of the existing data.
1774 */
1775 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001776 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001777 pid_t spid = IPCThreadState::self()->getCallingPid();
1778 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001779 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001780 return ::PERMISSION_DENIED;
1781 }
Kenny Root70e3a862012-02-15 17:20:23 -08001782
Kenny Root07438c82012-11-02 15:41:02 -07001783 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001784
Kenny Root655b9582013-04-04 08:37:42 -07001785 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001786 case ::STATE_UNINITIALIZED: {
1787 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001788 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001789 }
1790 case ::STATE_NO_ERROR: {
1791 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001792 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001793 }
1794 case ::STATE_LOCKED: {
1795 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001796 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001797 }
1798 }
1799 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001800 }
1801
Kenny Root07438c82012-11-02 15:41:02 -07001802 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001803 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001804 pid_t spid = IPCThreadState::self()->getCallingPid();
1805 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001806 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001807 return ::PERMISSION_DENIED;
1808 }
Kenny Root70e3a862012-02-15 17:20:23 -08001809
Kenny Root655b9582013-04-04 08:37:42 -07001810 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001811 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001812 ALOGD("calling lock in state: %d", state);
1813 return state;
1814 }
1815
Kenny Root655b9582013-04-04 08:37:42 -07001816 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001817 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001818 }
1819
Kenny Root07438c82012-11-02 15:41:02 -07001820 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001821 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001822 pid_t spid = IPCThreadState::self()->getCallingPid();
1823 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001824 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001825 return ::PERMISSION_DENIED;
1826 }
1827
Kenny Root655b9582013-04-04 08:37:42 -07001828 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001829 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001830 ALOGD("calling unlock when not locked");
1831 return state;
1832 }
1833
1834 const String8 password8(pw);
1835 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001836 }
1837
Kenny Root07438c82012-11-02 15:41:02 -07001838 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001839 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001840 pid_t spid = IPCThreadState::self()->getCallingPid();
1841 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001842 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001843 return -1;
1844 }
Kenny Root70e3a862012-02-15 17:20:23 -08001845
Kenny Root655b9582013-04-04 08:37:42 -07001846 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001847 }
1848
Kenny Root96427ba2013-08-16 14:02:41 -07001849 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1850 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001851 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001852 pid_t spid = IPCThreadState::self()->getCallingPid();
1853 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001854 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001855 return ::PERMISSION_DENIED;
1856 }
Kenny Root70e3a862012-02-15 17:20:23 -08001857
Kenny Root49468902013-03-19 13:41:33 -07001858 if (targetUid == -1) {
1859 targetUid = callingUid;
1860 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001861 return ::PERMISSION_DENIED;
1862 }
1863
Kenny Root655b9582013-04-04 08:37:42 -07001864 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001865 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1866 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001867 return state;
1868 }
Kenny Root70e3a862012-02-15 17:20:23 -08001869
Kenny Root07438c82012-11-02 15:41:02 -07001870 uint8_t* data;
1871 size_t dataLength;
1872 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001873 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001874
1875 const keymaster_device_t* device = mKeyStore->getDevice();
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001876 const keymaster_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001877 if (device == NULL) {
1878 return ::SYSTEM_ERROR;
1879 }
1880
1881 if (device->generate_keypair == NULL) {
1882 return ::SYSTEM_ERROR;
1883 }
1884
Kenny Root17208e02013-09-04 13:56:03 -07001885 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001886 keymaster_dsa_keygen_params_t dsa_params;
1887 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001888
Kenny Root96427ba2013-08-16 14:02:41 -07001889 if (keySize == -1) {
1890 keySize = DSA_DEFAULT_KEY_SIZE;
1891 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1892 || keySize > DSA_MAX_KEY_SIZE) {
1893 ALOGI("invalid key size %d", keySize);
1894 return ::SYSTEM_ERROR;
1895 }
1896 dsa_params.key_size = keySize;
1897
1898 if (args->size() == 3) {
1899 sp<KeystoreArg> gArg = args->itemAt(0);
1900 sp<KeystoreArg> pArg = args->itemAt(1);
1901 sp<KeystoreArg> qArg = args->itemAt(2);
1902
1903 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1904 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1905 dsa_params.generator_len = gArg->size();
1906
1907 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1908 dsa_params.prime_p_len = pArg->size();
1909
1910 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1911 dsa_params.prime_q_len = qArg->size();
1912 } else {
1913 ALOGI("not all DSA parameters were read");
1914 return ::SYSTEM_ERROR;
1915 }
1916 } else if (args->size() != 0) {
1917 ALOGI("DSA args must be 3");
1918 return ::SYSTEM_ERROR;
1919 }
1920
Kenny Root1d448c02013-11-21 10:36:53 -08001921 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001922 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1923 } else {
1924 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001925 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1926 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001927 }
1928 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001929 keymaster_ec_keygen_params_t ec_params;
1930 memset(&ec_params, '\0', sizeof(ec_params));
1931
1932 if (keySize == -1) {
1933 keySize = EC_DEFAULT_KEY_SIZE;
1934 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1935 ALOGI("invalid key size %d", keySize);
1936 return ::SYSTEM_ERROR;
1937 }
1938 ec_params.field_size = keySize;
1939
Kenny Root1d448c02013-11-21 10:36:53 -08001940 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001941 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1942 } else {
1943 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001944 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001945 }
Kenny Root96427ba2013-08-16 14:02:41 -07001946 } else if (keyType == EVP_PKEY_RSA) {
1947 keymaster_rsa_keygen_params_t rsa_params;
1948 memset(&rsa_params, '\0', sizeof(rsa_params));
1949 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1950
1951 if (keySize == -1) {
1952 keySize = RSA_DEFAULT_KEY_SIZE;
1953 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1954 ALOGI("invalid key size %d", keySize);
1955 return ::SYSTEM_ERROR;
1956 }
1957 rsa_params.modulus_size = keySize;
1958
1959 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001960 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001961 return ::SYSTEM_ERROR;
1962 } else if (args->size() == 1) {
1963 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1964 if (pubExpBlob != NULL) {
1965 Unique_BIGNUM pubExpBn(
1966 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1967 pubExpBlob->size(), NULL));
1968 if (pubExpBn.get() == NULL) {
1969 ALOGI("Could not convert public exponent to BN");
1970 return ::SYSTEM_ERROR;
1971 }
1972 unsigned long pubExp = BN_get_word(pubExpBn.get());
1973 if (pubExp == 0xFFFFFFFFL) {
1974 ALOGI("cannot represent public exponent as a long value");
1975 return ::SYSTEM_ERROR;
1976 }
1977 rsa_params.public_exponent = pubExp;
1978 }
1979 }
1980
1981 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1982 } else {
1983 ALOGW("Unsupported key type %d", keyType);
1984 rc = -1;
1985 }
1986
Kenny Root07438c82012-11-02 15:41:02 -07001987 if (rc) {
1988 return ::SYSTEM_ERROR;
1989 }
1990
Kenny Root655b9582013-04-04 08:37:42 -07001991 String8 name8(name);
1992 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001993
1994 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1995 free(data);
1996
Kenny Rootee8068b2013-10-07 09:49:15 -07001997 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001998 keyBlob.setFallback(isFallback);
1999
Kenny Root655b9582013-04-04 08:37:42 -07002000 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08002001 }
2002
Kenny Rootf9119d62013-04-03 09:22:15 -07002003 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2004 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002005 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002006 pid_t spid = IPCThreadState::self()->getCallingPid();
2007 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002008 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002009 return ::PERMISSION_DENIED;
2010 }
Kenny Root07438c82012-11-02 15:41:02 -07002011
Kenny Root49468902013-03-19 13:41:33 -07002012 if (targetUid == -1) {
2013 targetUid = callingUid;
2014 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002015 return ::PERMISSION_DENIED;
2016 }
2017
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002018 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07002019 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002020 ALOGD("calling import in state: %d", state);
2021 return state;
2022 }
2023
2024 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002025 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002026
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002027 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002028 }
2029
Kenny Root07438c82012-11-02 15:41:02 -07002030 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2031 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002032 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002033 pid_t spid = IPCThreadState::self()->getCallingPid();
2034 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002035 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002036 return ::PERMISSION_DENIED;
2037 }
Kenny Root07438c82012-11-02 15:41:02 -07002038
Kenny Root07438c82012-11-02 15:41:02 -07002039 Blob keyBlob;
2040 String8 name8(name);
2041
Kenny Rootd38a0b02013-02-13 12:59:14 -08002042 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002043 int rc;
2044
Kenny Root655b9582013-04-04 08:37:42 -07002045 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002046 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002047 if (responseCode != ::NO_ERROR) {
2048 return responseCode;
2049 }
2050
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002051 const keymaster_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002052 if (device == NULL) {
2053 ALOGE("no keymaster device; cannot sign");
2054 return ::SYSTEM_ERROR;
2055 }
2056
2057 if (device->sign_data == NULL) {
2058 ALOGE("device doesn't implement signing");
2059 return ::SYSTEM_ERROR;
2060 }
2061
2062 keymaster_rsa_sign_params_t params;
2063 params.digest_type = DIGEST_NONE;
2064 params.padding_type = PADDING_NONE;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002065 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2066 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002067 if (rc) {
2068 ALOGW("device couldn't sign data");
2069 return ::SYSTEM_ERROR;
2070 }
2071
2072 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002073 }
2074
Kenny Root07438c82012-11-02 15:41:02 -07002075 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2076 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002077 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002078 pid_t spid = IPCThreadState::self()->getCallingPid();
2079 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002080 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002081 return ::PERMISSION_DENIED;
2082 }
Kenny Root70e3a862012-02-15 17:20:23 -08002083
Kenny Root655b9582013-04-04 08:37:42 -07002084 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002085 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002086 ALOGD("calling verify in state: %d", state);
2087 return state;
2088 }
Kenny Root70e3a862012-02-15 17:20:23 -08002089
Kenny Root07438c82012-11-02 15:41:02 -07002090 Blob keyBlob;
2091 String8 name8(name);
2092 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002093
Kenny Root655b9582013-04-04 08:37:42 -07002094 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002095 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002096 if (responseCode != ::NO_ERROR) {
2097 return responseCode;
2098 }
Kenny Root70e3a862012-02-15 17:20:23 -08002099
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002100 const keymaster_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002101 if (device == NULL) {
2102 return ::SYSTEM_ERROR;
2103 }
Kenny Root70e3a862012-02-15 17:20:23 -08002104
Kenny Root07438c82012-11-02 15:41:02 -07002105 if (device->verify_data == NULL) {
2106 return ::SYSTEM_ERROR;
2107 }
Kenny Root70e3a862012-02-15 17:20:23 -08002108
Kenny Root07438c82012-11-02 15:41:02 -07002109 keymaster_rsa_sign_params_t params;
2110 params.digest_type = DIGEST_NONE;
2111 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002112
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002113 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2114 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002115 if (rc) {
2116 return ::SYSTEM_ERROR;
2117 } else {
2118 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002119 }
2120 }
Kenny Root07438c82012-11-02 15:41:02 -07002121
2122 /*
2123 * TODO: The abstraction between things stored in hardware and regular blobs
2124 * of data stored on the filesystem should be moved down to keystore itself.
2125 * Unfortunately the Java code that calls this has naming conventions that it
2126 * knows about. Ideally keystore shouldn't be used to store random blobs of
2127 * data.
2128 *
2129 * Until that happens, it's necessary to have a separate "get_pubkey" and
2130 * "del_key" since the Java code doesn't really communicate what it's
2131 * intentions are.
2132 */
2133 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002134 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002135 pid_t spid = IPCThreadState::self()->getCallingPid();
2136 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002137 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002138 return ::PERMISSION_DENIED;
2139 }
Kenny Root07438c82012-11-02 15:41:02 -07002140
Kenny Root07438c82012-11-02 15:41:02 -07002141 Blob keyBlob;
2142 String8 name8(name);
2143
Kenny Rootd38a0b02013-02-13 12:59:14 -08002144 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002145
Kenny Root655b9582013-04-04 08:37:42 -07002146 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002147 TYPE_KEY_PAIR);
2148 if (responseCode != ::NO_ERROR) {
2149 return responseCode;
2150 }
2151
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002152 const keymaster_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002153 if (device == NULL) {
2154 return ::SYSTEM_ERROR;
2155 }
2156
2157 if (device->get_keypair_public == NULL) {
2158 ALOGE("device has no get_keypair_public implementation!");
2159 return ::SYSTEM_ERROR;
2160 }
2161
Kenny Root17208e02013-09-04 13:56:03 -07002162 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002163 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2164 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002165 if (rc) {
2166 return ::SYSTEM_ERROR;
2167 }
2168
2169 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002170 }
Kenny Root07438c82012-11-02 15:41:02 -07002171
Kenny Root49468902013-03-19 13:41:33 -07002172 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002173 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002174 pid_t spid = IPCThreadState::self()->getCallingPid();
2175 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002176 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002177 return ::PERMISSION_DENIED;
2178 }
Kenny Root07438c82012-11-02 15:41:02 -07002179
Kenny Root49468902013-03-19 13:41:33 -07002180 if (targetUid == -1) {
2181 targetUid = callingUid;
2182 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002183 return ::PERMISSION_DENIED;
2184 }
2185
Kenny Root07438c82012-11-02 15:41:02 -07002186 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002187 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01002188 return mKeyStore->del(filename.string(), ::TYPE_KEY_PAIR, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002189 }
2190
2191 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002192 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002193 pid_t spid = IPCThreadState::self()->getCallingPid();
2194 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002195 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002196 return ::PERMISSION_DENIED;
2197 }
Kenny Root07438c82012-11-02 15:41:02 -07002198
Kenny Root655b9582013-04-04 08:37:42 -07002199 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002200 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002201 ALOGD("calling grant in state: %d", state);
2202 return state;
2203 }
2204
2205 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002206 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002207
Kenny Root655b9582013-04-04 08:37:42 -07002208 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002209 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2210 }
2211
Kenny Root655b9582013-04-04 08:37:42 -07002212 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002213 return ::NO_ERROR;
2214 }
2215
2216 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002217 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002218 pid_t spid = IPCThreadState::self()->getCallingPid();
2219 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002220 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002221 return ::PERMISSION_DENIED;
2222 }
Kenny Root07438c82012-11-02 15:41:02 -07002223
Kenny Root655b9582013-04-04 08:37:42 -07002224 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002225 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002226 ALOGD("calling ungrant in state: %d", state);
2227 return state;
2228 }
2229
2230 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002231 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002232
Kenny Root655b9582013-04-04 08:37:42 -07002233 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002234 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2235 }
2236
Kenny Root655b9582013-04-04 08:37:42 -07002237 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002238 }
2239
2240 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002241 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002242 pid_t spid = IPCThreadState::self()->getCallingPid();
2243 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002244 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002245 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002246 }
Kenny Root07438c82012-11-02 15:41:02 -07002247
2248 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002249 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002250
Kenny Root655b9582013-04-04 08:37:42 -07002251 if (access(filename.string(), R_OK) == -1) {
2252 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002253 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002254 }
2255
Kenny Root655b9582013-04-04 08:37:42 -07002256 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002257 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002258 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002259 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002260 }
2261
2262 struct stat s;
2263 int ret = fstat(fd, &s);
2264 close(fd);
2265 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002266 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002267 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002268 }
2269
Kenny Root36a9e232013-02-04 14:24:15 -08002270 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002271 }
2272
Kenny Rootd53bc922013-03-21 14:10:15 -07002273 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2274 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002275 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002276 pid_t spid = IPCThreadState::self()->getCallingPid();
2277 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002278 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002279 return -1L;
2280 }
2281
Kenny Root655b9582013-04-04 08:37:42 -07002282 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002283 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002284 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002285 return state;
2286 }
2287
Kenny Rootd53bc922013-03-21 14:10:15 -07002288 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2289 srcUid = callingUid;
2290 } else if (!is_granted_to(callingUid, srcUid)) {
2291 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002292 return ::PERMISSION_DENIED;
2293 }
2294
Kenny Rootd53bc922013-03-21 14:10:15 -07002295 if (destUid == -1) {
2296 destUid = callingUid;
2297 }
2298
2299 if (srcUid != destUid) {
2300 if (static_cast<uid_t>(srcUid) != callingUid) {
2301 ALOGD("can only duplicate from caller to other or to same uid: "
2302 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2303 return ::PERMISSION_DENIED;
2304 }
2305
2306 if (!is_granted_to(callingUid, destUid)) {
2307 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2308 return ::PERMISSION_DENIED;
2309 }
2310 }
2311
2312 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002313 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002314
Kenny Rootd53bc922013-03-21 14:10:15 -07002315 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002316 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002317
Kenny Root655b9582013-04-04 08:37:42 -07002318 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2319 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002320 return ::SYSTEM_ERROR;
2321 }
2322
Kenny Rootd53bc922013-03-21 14:10:15 -07002323 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002324 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002325 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002326 if (responseCode != ::NO_ERROR) {
2327 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002328 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002329
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002330 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002331 }
2332
Kenny Root1b0e3932013-09-05 13:06:32 -07002333 int32_t is_hardware_backed(const String16& keyType) {
2334 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002335 }
2336
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002337 int32_t clear_uid(int64_t targetUid64) {
2338 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002339 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002340 pid_t spid = IPCThreadState::self()->getCallingPid();
2341 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002342 ALOGW("permission denied for %d: clear_uid", callingUid);
2343 return ::PERMISSION_DENIED;
2344 }
2345
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002346 if (targetUid64 == -1) {
2347 targetUid = callingUid;
Kenny Root007cb232014-07-30 16:59:42 -07002348 } else if (!is_self_or_system(callingUid, targetUid)) {
2349 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002350 return ::PERMISSION_DENIED;
2351 }
2352
Kenny Roota9bb5492013-04-01 16:29:11 -07002353 const keymaster_device_t* device = mKeyStore->getDevice();
2354 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002355 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002356 return ::SYSTEM_ERROR;
2357 }
2358
Robin Lee4b84fdc2014-09-24 11:56:57 +01002359 String8 prefix = String8::format("%u_", targetUid);
2360 Vector<String16> aliases;
2361 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002362 return ::SYSTEM_ERROR;
2363 }
2364
Robin Lee4b84fdc2014-09-24 11:56:57 +01002365 for (uint32_t i = 0; i < aliases.size(); i++) {
2366 String8 name8(aliases[i]);
2367 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2368 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002369 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002370 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002371 }
2372
Robin Lee4b84fdc2014-09-24 11:56:57 +01002373 int32_t reset_uid(int32_t targetUid) {
Robin Lee4e865752014-08-19 17:37:55 +01002374 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2375 pid_t spid = IPCThreadState::self()->getCallingPid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01002376
Robin Lee4e865752014-08-19 17:37:55 +01002377 if (!has_permission(callingUid, P_RESET_UID, spid)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01002378 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002379 return ::PERMISSION_DENIED;
2380 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002381 if (!is_self_or_system(callingUid, targetUid)) {
2382 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002383 return ::PERMISSION_DENIED;
2384 }
2385
Robin Lee4b84fdc2014-09-24 11:56:57 +01002386 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002387 }
2388
2389 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
2390 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2391 pid_t spid = IPCThreadState::self()->getCallingPid();
2392 if (!has_permission(callingUid, P_SYNC_UID, spid)) {
2393 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2394 return ::PERMISSION_DENIED;
2395 }
2396 if (callingUid != AID_SYSTEM) {
2397 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2398 return ::PERMISSION_DENIED;
2399 }
2400 if (sourceUid == targetUid) {
2401 return ::SYSTEM_ERROR;
2402 }
2403
2404 // Initialise user keystore with existing master key held in-memory
2405 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2406 }
2407
2408 int32_t password_uid(const String16& pw, int32_t targetUid) {
2409 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2410 pid_t spid = IPCThreadState::self()->getCallingPid();
2411 if (!has_permission(callingUid, P_PASSWORD_UID, spid)) {
2412 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2413 return ::PERMISSION_DENIED;
2414 }
2415 if (callingUid != AID_SYSTEM) {
2416 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2417 return ::PERMISSION_DENIED;
2418 }
2419
2420 const String8 password8(pw);
2421
2422 switch (mKeyStore->getState(targetUid)) {
2423 case ::STATE_UNINITIALIZED: {
2424 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2425 return mKeyStore->initializeUser(password8, targetUid);
2426 }
2427 case ::STATE_NO_ERROR: {
2428 // rewrite master key with new password.
2429 return mKeyStore->writeMasterKey(password8, targetUid);
2430 }
2431 case ::STATE_LOCKED: {
2432 // read master key, decrypt with password, initialize mMasterKey*.
2433 return mKeyStore->readMasterKey(password8, targetUid);
2434 }
2435 }
2436 return ::SYSTEM_ERROR;
2437 }
2438
Kenny Root07438c82012-11-02 15:41:02 -07002439private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002440 inline bool isKeystoreUnlocked(State state) {
2441 switch (state) {
2442 case ::STATE_NO_ERROR:
2443 return true;
2444 case ::STATE_UNINITIALIZED:
2445 case ::STATE_LOCKED:
2446 return false;
2447 }
2448 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002449 }
2450
Kenny Root1d448c02013-11-21 10:36:53 -08002451 bool isKeyTypeSupported(const keymaster_device_t* device, keymaster_keypair_t keyType) {
2452 const int32_t device_api = device->common.module->module_api_version;
2453 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2454 switch (keyType) {
2455 case TYPE_RSA:
2456 case TYPE_DSA:
2457 case TYPE_EC:
2458 return true;
2459 default:
2460 return false;
2461 }
2462 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2463 switch (keyType) {
2464 case TYPE_RSA:
2465 return true;
2466 case TYPE_DSA:
2467 return device->flags & KEYMASTER_SUPPORTS_DSA;
2468 case TYPE_EC:
2469 return device->flags & KEYMASTER_SUPPORTS_EC;
2470 default:
2471 return false;
2472 }
2473 } else {
2474 return keyType == TYPE_RSA;
2475 }
2476 }
2477
Kenny Root07438c82012-11-02 15:41:02 -07002478 ::KeyStore* mKeyStore;
2479};
2480
2481}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002482
2483int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002484 if (argc < 2) {
2485 ALOGE("A directory must be specified!");
2486 return 1;
2487 }
2488 if (chdir(argv[1]) == -1) {
2489 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2490 return 1;
2491 }
2492
2493 Entropy entropy;
2494 if (!entropy.open()) {
2495 return 1;
2496 }
Kenny Root70e3a862012-02-15 17:20:23 -08002497
2498 keymaster_device_t* dev;
2499 if (keymaster_device_initialize(&dev)) {
2500 ALOGE("keystore keymaster could not be initialized; exiting");
2501 return 1;
2502 }
2503
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002504 keymaster_device_t* fallback;
2505 if (fallback_keymaster_device_initialize(&fallback)) {
2506 ALOGE("software keymaster could not be initialized; exiting");
2507 return 1;
2508 }
2509
Riley Spahneaabae92014-06-30 12:39:52 -07002510 ks_is_selinux_enabled = is_selinux_enabled();
2511 if (ks_is_selinux_enabled) {
2512 union selinux_callback cb;
2513 cb.func_log = selinux_log_callback;
2514 selinux_set_callback(SELINUX_CB_LOG, cb);
2515 if (getcon(&tctx) != 0) {
2516 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2517 return -1;
2518 }
2519 } else {
2520 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2521 }
2522
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002523 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07002524 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002525 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2526 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2527 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2528 if (ret != android::OK) {
2529 ALOGE("Couldn't register binder service!");
2530 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002531 }
Kenny Root07438c82012-11-02 15:41:02 -07002532
2533 /*
2534 * We're the only thread in existence, so we're just going to process
2535 * Binder transaction as a single-threaded program.
2536 */
2537 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002538
2539 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002540 return 1;
2541}