blob: cf799f1f63f257f9fc213461c90ce94b693e4f22 [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
Shawn Willdena5bbf2f2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
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
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700106static int keymaster_device_initialize(keymaster0_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800107 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
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700116 rc = keymaster0_open(mod, dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800117 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
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700130static int fallback_keymaster_device_initialize(keymaster0_device_t** dev) {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800131 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
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700146static void keymaster_device_release(keymaster0_device_t* dev) {
147 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800148}
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) {
Kenny Roota91203b2012-02-15 15:00:46 -0800507 mBlob.length = valueLength;
508 memcpy(mBlob.value, value, valueLength);
509
510 mBlob.info = infoLength;
511 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700512
Kenny Root07438c82012-11-02 15:41:02 -0700513 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700514 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700515
Kenny Rootee8068b2013-10-07 09:49:15 -0700516 if (type == TYPE_MASTER_KEY) {
517 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
518 } else {
519 mBlob.flags = KEYSTORE_FLAG_NONE;
520 }
Kenny Roota91203b2012-02-15 15:00:46 -0800521 }
522
523 Blob(blob b) {
524 mBlob = b;
525 }
526
527 Blob() {}
528
Kenny Root51878182012-03-13 12:53:19 -0700529 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800530 return mBlob.value;
531 }
532
Kenny Root51878182012-03-13 12:53:19 -0700533 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800534 return mBlob.length;
535 }
536
Kenny Root51878182012-03-13 12:53:19 -0700537 const uint8_t* getInfo() const {
538 return mBlob.value + mBlob.length;
539 }
540
541 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800542 return mBlob.info;
543 }
544
Kenny Root822c3a92012-03-23 16:34:39 -0700545 uint8_t getVersion() const {
546 return mBlob.version;
547 }
548
Kenny Rootf9119d62013-04-03 09:22:15 -0700549 bool isEncrypted() const {
550 if (mBlob.version < 2) {
551 return true;
552 }
553
554 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
555 }
556
557 void setEncrypted(bool encrypted) {
558 if (encrypted) {
559 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
560 } else {
561 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
562 }
563 }
564
Kenny Root17208e02013-09-04 13:56:03 -0700565 bool isFallback() const {
566 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
567 }
568
569 void setFallback(bool fallback) {
570 if (fallback) {
571 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
572 } else {
573 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
574 }
575 }
576
Kenny Root822c3a92012-03-23 16:34:39 -0700577 void setVersion(uint8_t version) {
578 mBlob.version = version;
579 }
580
581 BlobType getType() const {
582 return BlobType(mBlob.type);
583 }
584
585 void setType(BlobType type) {
586 mBlob.type = uint8_t(type);
587 }
588
Kenny Rootf9119d62013-04-03 09:22:15 -0700589 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
590 ALOGV("writing blob %s", filename);
591 if (isEncrypted()) {
592 if (state != STATE_NO_ERROR) {
593 ALOGD("couldn't insert encrypted blob while not unlocked");
594 return LOCKED;
595 }
596
597 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
598 ALOGW("Could not read random data for: %s", filename);
599 return SYSTEM_ERROR;
600 }
Kenny Roota91203b2012-02-15 15:00:46 -0800601 }
602
603 // data includes the value and the value's length
604 size_t dataLength = mBlob.length + sizeof(mBlob.length);
605 // pad data to the AES_BLOCK_SIZE
606 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
607 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
608 // encrypted data includes the digest value
609 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
610 // move info after space for padding
611 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
612 // zero padding area
613 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
614
615 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800616
Kenny Rootf9119d62013-04-03 09:22:15 -0700617 if (isEncrypted()) {
618 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800619
Kenny Rootf9119d62013-04-03 09:22:15 -0700620 uint8_t vector[AES_BLOCK_SIZE];
621 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
622 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
623 aes_key, vector, AES_ENCRYPT);
624 }
625
Kenny Roota91203b2012-02-15 15:00:46 -0800626 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
627 size_t fileLength = encryptedLength + headerLength + mBlob.info;
628
629 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800630 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
631 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
632 if (out < 0) {
633 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800634 return SYSTEM_ERROR;
635 }
636 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
637 if (close(out) != 0) {
638 return SYSTEM_ERROR;
639 }
640 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800641 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800642 unlink(tmpFileName);
643 return SYSTEM_ERROR;
644 }
Kenny Root150ca932012-11-14 14:29:02 -0800645 if (rename(tmpFileName, filename) == -1) {
646 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
647 return SYSTEM_ERROR;
648 }
649 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800650 }
651
Kenny Rootf9119d62013-04-03 09:22:15 -0700652 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
653 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800654 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
655 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800656 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
657 }
658 // fileLength may be less than sizeof(mBlob) since the in
659 // memory version has extra padding to tolerate rounding up to
660 // the AES_BLOCK_SIZE
661 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
662 if (close(in) != 0) {
663 return SYSTEM_ERROR;
664 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700665
666 if (isEncrypted() && (state != STATE_NO_ERROR)) {
667 return LOCKED;
668 }
669
Kenny Roota91203b2012-02-15 15:00:46 -0800670 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
671 if (fileLength < headerLength) {
672 return VALUE_CORRUPTED;
673 }
674
675 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700676 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800677 return VALUE_CORRUPTED;
678 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700679
680 ssize_t digestedLength;
681 if (isEncrypted()) {
682 if (encryptedLength % AES_BLOCK_SIZE != 0) {
683 return VALUE_CORRUPTED;
684 }
685
686 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
687 mBlob.vector, AES_DECRYPT);
688 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
689 uint8_t computedDigest[MD5_DIGEST_LENGTH];
690 MD5(mBlob.digested, digestedLength, computedDigest);
691 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
692 return VALUE_CORRUPTED;
693 }
694 } else {
695 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800696 }
697
698 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
699 mBlob.length = ntohl(mBlob.length);
700 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
701 return VALUE_CORRUPTED;
702 }
703 if (mBlob.info != 0) {
704 // move info from after padding to after data
705 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
706 }
Kenny Root07438c82012-11-02 15:41:02 -0700707 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800708 }
709
710private:
711 struct blob mBlob;
712};
713
Kenny Root655b9582013-04-04 08:37:42 -0700714class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800715public:
Kenny Root655b9582013-04-04 08:37:42 -0700716 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
717 asprintf(&mUserDir, "user_%u", mUserId);
718 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
719 }
720
721 ~UserState() {
722 free(mUserDir);
723 free(mMasterKeyFile);
724 }
725
726 bool initialize() {
727 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
728 ALOGE("Could not create directory '%s'", mUserDir);
729 return false;
730 }
731
732 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800733 setState(STATE_LOCKED);
734 } else {
735 setState(STATE_UNINITIALIZED);
736 }
Kenny Root70e3a862012-02-15 17:20:23 -0800737
Kenny Root655b9582013-04-04 08:37:42 -0700738 return true;
739 }
740
741 uid_t getUserId() const {
742 return mUserId;
743 }
744
745 const char* getUserDirName() const {
746 return mUserDir;
747 }
748
749 const char* getMasterKeyFileName() const {
750 return mMasterKeyFile;
751 }
752
753 void setState(State state) {
754 mState = state;
755 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
756 mRetry = MAX_RETRY;
757 }
Kenny Roota91203b2012-02-15 15:00:46 -0800758 }
759
Kenny Root51878182012-03-13 12:53:19 -0700760 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800761 return mState;
762 }
763
Kenny Root51878182012-03-13 12:53:19 -0700764 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800765 return mRetry;
766 }
767
Kenny Root655b9582013-04-04 08:37:42 -0700768 void zeroizeMasterKeysInMemory() {
769 memset(mMasterKey, 0, sizeof(mMasterKey));
770 memset(mSalt, 0, sizeof(mSalt));
771 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
772 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800773 }
774
Kenny Root655b9582013-04-04 08:37:42 -0700775 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
776 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800777 return SYSTEM_ERROR;
778 }
Kenny Root655b9582013-04-04 08:37:42 -0700779 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800780 if (response != NO_ERROR) {
781 return response;
782 }
783 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700784 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800785 }
786
Robin Lee4e865752014-08-19 17:37:55 +0100787 ResponseCode copyMasterKey(UserState* src) {
788 if (mState != STATE_UNINITIALIZED) {
789 return ::SYSTEM_ERROR;
790 }
791 if (src->getState() != STATE_NO_ERROR) {
792 return ::SYSTEM_ERROR;
793 }
794 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
795 setupMasterKeys();
796 return ::NO_ERROR;
797 }
798
Kenny Root655b9582013-04-04 08:37:42 -0700799 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800800 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
801 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
802 AES_KEY passwordAesKey;
803 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700804 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700805 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800806 }
807
Kenny Root655b9582013-04-04 08:37:42 -0700808 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
809 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800810 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800811 return SYSTEM_ERROR;
812 }
813
814 // we read the raw blob to just to get the salt to generate
815 // the AES key, then we create the Blob to use with decryptBlob
816 blob rawBlob;
817 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
818 if (close(in) != 0) {
819 return SYSTEM_ERROR;
820 }
821 // find salt at EOF if present, otherwise we have an old file
822 uint8_t* salt;
823 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
824 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
825 } else {
826 salt = NULL;
827 }
828 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
829 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
830 AES_KEY passwordAesKey;
831 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
832 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700833 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
834 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800835 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700836 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800837 }
838 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
839 // if salt was missing, generate one and write a new master key file with the salt.
840 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700841 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800842 return SYSTEM_ERROR;
843 }
Kenny Root655b9582013-04-04 08:37:42 -0700844 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800845 }
846 if (response == NO_ERROR) {
847 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
848 setupMasterKeys();
849 }
850 return response;
851 }
852 if (mRetry <= 0) {
853 reset();
854 return UNINITIALIZED;
855 }
856 --mRetry;
857 switch (mRetry) {
858 case 0: return WRONG_PASSWORD_0;
859 case 1: return WRONG_PASSWORD_1;
860 case 2: return WRONG_PASSWORD_2;
861 case 3: return WRONG_PASSWORD_3;
862 default: return WRONG_PASSWORD_3;
863 }
864 }
865
Kenny Root655b9582013-04-04 08:37:42 -0700866 AES_KEY* getEncryptionKey() {
867 return &mMasterKeyEncryption;
868 }
869
870 AES_KEY* getDecryptionKey() {
871 return &mMasterKeyDecryption;
872 }
873
Kenny Roota91203b2012-02-15 15:00:46 -0800874 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700875 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800876 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700877 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800878 return false;
879 }
Kenny Root655b9582013-04-04 08:37:42 -0700880
881 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800882 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700883 // We only care about files.
884 if (file->d_type != DT_REG) {
885 continue;
886 }
887
888 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700889 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700890 continue;
891 }
892
893 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800894 }
895 closedir(dir);
896 return true;
897 }
898
Kenny Root655b9582013-04-04 08:37:42 -0700899private:
900 static const int MASTER_KEY_SIZE_BYTES = 16;
901 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
902
903 static const int MAX_RETRY = 4;
904 static const size_t SALT_SIZE = 16;
905
906 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
907 uint8_t* salt) {
908 size_t saltSize;
909 if (salt != NULL) {
910 saltSize = SALT_SIZE;
911 } else {
912 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
913 salt = (uint8_t*) "keystore";
914 // sizeof = 9, not strlen = 8
915 saltSize = sizeof("keystore");
916 }
917
918 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
919 saltSize, 8192, keySize, key);
920 }
921
922 bool generateSalt(Entropy* entropy) {
923 return entropy->generate_random_data(mSalt, sizeof(mSalt));
924 }
925
926 bool generateMasterKey(Entropy* entropy) {
927 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
928 return false;
929 }
930 if (!generateSalt(entropy)) {
931 return false;
932 }
933 return true;
934 }
935
936 void setupMasterKeys() {
937 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
938 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
939 setState(STATE_NO_ERROR);
940 }
941
942 uid_t mUserId;
943
944 char* mUserDir;
945 char* mMasterKeyFile;
946
947 State mState;
948 int8_t mRetry;
949
950 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
951 uint8_t mSalt[SALT_SIZE];
952
953 AES_KEY mMasterKeyEncryption;
954 AES_KEY mMasterKeyDecryption;
955};
956
957typedef struct {
958 uint32_t uid;
959 const uint8_t* filename;
960} grant_t;
961
962class KeyStore {
963public:
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700964 KeyStore(Entropy* entropy, keymaster0_device_t* device, keymaster0_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700965 : mEntropy(entropy)
966 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800967 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700968 {
969 memset(&mMetaData, '\0', sizeof(mMetaData));
970 }
971
972 ~KeyStore() {
973 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
974 it != mGrants.end(); it++) {
975 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700976 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800977 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700978
979 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
980 it != mMasterKeys.end(); it++) {
981 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700982 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800983 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700984 }
985
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700986 keymaster0_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700987 return mDevice;
988 }
989
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700990 keymaster0_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800991 return mFallbackDevice;
992 }
993
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700994 keymaster0_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800995 return blob.isFallback() ? mFallbackDevice: mDevice;
996 }
997
Kenny Root655b9582013-04-04 08:37:42 -0700998 ResponseCode initialize() {
999 readMetaData();
1000 if (upgradeKeystore()) {
1001 writeMetaData();
1002 }
1003
1004 return ::NO_ERROR;
1005 }
1006
1007 State getState(uid_t uid) {
1008 return getUserState(uid)->getState();
1009 }
1010
1011 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
1012 UserState* userState = getUserState(uid);
1013 return userState->initialize(pw, mEntropy);
1014 }
1015
Robin Lee4e865752014-08-19 17:37:55 +01001016 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
1017 UserState *userState = getUserState(uid);
1018 UserState *initState = getUserState(src);
1019 return userState->copyMasterKey(initState);
1020 }
1021
Kenny Root655b9582013-04-04 08:37:42 -07001022 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001023 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001024 return userState->writeMasterKey(pw, mEntropy);
1025 }
1026
1027 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001028 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001029 return userState->readMasterKey(pw, mEntropy);
1030 }
1031
1032 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001033 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001034 encode_key(encoded, keyName);
1035 return android::String8(encoded);
1036 }
1037
1038 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001039 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001040 encode_key(encoded, keyName);
1041 return android::String8::format("%u_%s", uid, encoded);
1042 }
1043
1044 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001045 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001046 encode_key(encoded, keyName);
1047 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1048 encoded);
1049 }
1050
1051 bool reset(uid_t uid) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001052 android::String8 prefix("");
1053 android::Vector<android::String16> aliases;
1054 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1055 return ::SYSTEM_ERROR;
1056 }
1057
Kenny Root655b9582013-04-04 08:37:42 -07001058 UserState* userState = getUserState(uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001059 for (uint32_t i = 0; i < aliases.size(); i++) {
1060 android::String8 filename(aliases[i]);
1061 filename = android::String8::format("%s/%s", userState->getUserDirName(),
1062 getKeyName(filename).string());
1063 del(filename, ::TYPE_ANY, uid);
1064 }
1065
Kenny Root655b9582013-04-04 08:37:42 -07001066 userState->zeroizeMasterKeysInMemory();
1067 userState->setState(STATE_UNINITIALIZED);
1068 return userState->reset();
1069 }
1070
1071 bool isEmpty(uid_t uid) const {
1072 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001073 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001074 return true;
1075 }
1076
1077 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001078 if (!dir) {
1079 return true;
1080 }
Kenny Root31e27462014-09-10 11:28:03 -07001081
Kenny Roota91203b2012-02-15 15:00:46 -08001082 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001083 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001084 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001085 // We only care about files.
1086 if (file->d_type != DT_REG) {
1087 continue;
1088 }
1089
1090 // Skip anything that starts with a "."
1091 if (file->d_name[0] == '.') {
1092 continue;
1093 }
1094
Kenny Root31e27462014-09-10 11:28:03 -07001095 result = false;
1096 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001097 }
1098 closedir(dir);
1099 return result;
1100 }
1101
Kenny Root655b9582013-04-04 08:37:42 -07001102 void lock(uid_t uid) {
1103 UserState* userState = getUserState(uid);
1104 userState->zeroizeMasterKeysInMemory();
1105 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001106 }
1107
Kenny Root655b9582013-04-04 08:37:42 -07001108 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1109 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001110 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1111 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001112 if (rc != NO_ERROR) {
1113 return rc;
1114 }
1115
1116 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001117 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001118 /* If we upgrade the key, we need to write it to disk again. Then
1119 * it must be read it again since the blob is encrypted each time
1120 * it's written.
1121 */
Kenny Root655b9582013-04-04 08:37:42 -07001122 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1123 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001124 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1125 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001126 return rc;
1127 }
1128 }
Kenny Root822c3a92012-03-23 16:34:39 -07001129 }
1130
Kenny Root17208e02013-09-04 13:56:03 -07001131 /*
1132 * This will upgrade software-backed keys to hardware-backed keys when
1133 * the HAL for the device supports the newer key types.
1134 */
1135 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1136 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1137 && keyBlob->isFallback()) {
1138 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1139 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1140
1141 // The HAL allowed the import, reget the key to have the "fresh"
1142 // version.
1143 if (imported == NO_ERROR) {
1144 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1145 }
1146 }
1147
Kenny Rootd53bc922013-03-21 14:10:15 -07001148 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001149 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1150 return KEY_NOT_FOUND;
1151 }
1152
1153 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001154 }
1155
Kenny Root655b9582013-04-04 08:37:42 -07001156 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1157 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001158 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1159 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001160 }
1161
Robin Lee4b84fdc2014-09-24 11:56:57 +01001162 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1163 Blob keyBlob;
1164 ResponseCode rc = get(filename, &keyBlob, type, uid);
1165 if (rc != ::NO_ERROR) {
1166 return rc;
1167 }
1168
1169 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1170 // A device doesn't have to implement delete_keypair.
1171 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1172 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1173 rc = ::SYSTEM_ERROR;
1174 }
1175 }
1176 }
1177 if (rc != ::NO_ERROR) {
1178 return rc;
1179 }
1180
1181 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1182 }
1183
1184 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1185 uid_t uid) {
1186
1187 UserState* userState = getUserState(uid);
1188 size_t n = prefix.length();
1189
1190 DIR* dir = opendir(userState->getUserDirName());
1191 if (!dir) {
1192 ALOGW("can't open directory for user: %s", strerror(errno));
1193 return ::SYSTEM_ERROR;
1194 }
1195
1196 struct dirent* file;
1197 while ((file = readdir(dir)) != NULL) {
1198 // We only care about files.
1199 if (file->d_type != DT_REG) {
1200 continue;
1201 }
1202
1203 // Skip anything that starts with a "."
1204 if (file->d_name[0] == '.') {
1205 continue;
1206 }
1207
1208 if (!strncmp(prefix.string(), file->d_name, n)) {
1209 const char* p = &file->d_name[n];
1210 size_t plen = strlen(p);
1211
1212 size_t extra = decode_key_length(p, plen);
1213 char *match = (char*) malloc(extra + 1);
1214 if (match != NULL) {
1215 decode_key(match, p, plen);
1216 matches->push(android::String16(match, extra));
1217 free(match);
1218 } else {
1219 ALOGW("could not allocate match of size %zd", extra);
1220 }
1221 }
1222 }
1223 closedir(dir);
1224 return ::NO_ERROR;
1225 }
1226
Kenny Root07438c82012-11-02 15:41:02 -07001227 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001228 const grant_t* existing = getGrant(filename, granteeUid);
1229 if (existing == NULL) {
1230 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001231 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001232 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001233 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001234 }
1235 }
1236
Kenny Root07438c82012-11-02 15:41:02 -07001237 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001238 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1239 it != mGrants.end(); it++) {
1240 grant_t* grant = *it;
1241 if (grant->uid == granteeUid
1242 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1243 mGrants.erase(it);
1244 return true;
1245 }
Kenny Root70e3a862012-02-15 17:20:23 -08001246 }
Kenny Root70e3a862012-02-15 17:20:23 -08001247 return false;
1248 }
1249
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001250 bool hasGrant(const char* filename, const uid_t uid) const {
1251 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001252 }
1253
Kenny Rootf9119d62013-04-03 09:22:15 -07001254 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1255 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001256 uint8_t* data;
1257 size_t dataLength;
1258 int rc;
1259
1260 if (mDevice->import_keypair == NULL) {
1261 ALOGE("Keymaster doesn't support import!");
1262 return SYSTEM_ERROR;
1263 }
1264
Kenny Root17208e02013-09-04 13:56:03 -07001265 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001266 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001267 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001268 /*
1269 * Maybe the device doesn't support this type of key. Try to use the
1270 * software fallback keymaster implementation. This is a little bit
1271 * lazier than checking the PKCS#8 key type, but the software
1272 * implementation will do that anyway.
1273 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001274 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001275 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001276
1277 if (rc) {
1278 ALOGE("Error while importing keypair: %d", rc);
1279 return SYSTEM_ERROR;
1280 }
Kenny Root822c3a92012-03-23 16:34:39 -07001281 }
1282
1283 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1284 free(data);
1285
Kenny Rootf9119d62013-04-03 09:22:15 -07001286 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001287 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001288
Kenny Root655b9582013-04-04 08:37:42 -07001289 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001290 }
1291
Kenny Root1b0e3932013-09-05 13:06:32 -07001292 bool isHardwareBacked(const android::String16& keyType) const {
1293 if (mDevice == NULL) {
1294 ALOGW("can't get keymaster device");
1295 return false;
1296 }
1297
1298 if (sRSAKeyType == keyType) {
1299 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1300 } else {
1301 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1302 && (mDevice->common.module->module_api_version
1303 >= KEYMASTER_MODULE_API_VERSION_0_2);
1304 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001305 }
1306
Kenny Root655b9582013-04-04 08:37:42 -07001307 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1308 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001309 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001310
1311 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1312 if (responseCode == NO_ERROR) {
1313 return responseCode;
1314 }
1315
1316 // If this is one of the legacy UID->UID mappings, use it.
1317 uid_t euid = get_keystore_euid(uid);
1318 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001319 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001320 responseCode = get(filepath8.string(), keyBlob, type, uid);
1321 if (responseCode == NO_ERROR) {
1322 return responseCode;
1323 }
1324 }
1325
1326 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001327 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001328 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001329 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001330 if (end[0] != '_' || end[1] == 0) {
1331 return KEY_NOT_FOUND;
1332 }
Kenny Root86b16e82013-09-09 11:15:54 -07001333 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1334 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001335 if (!hasGrant(filepath8.string(), uid)) {
1336 return responseCode;
1337 }
1338
1339 // It is a granted key. Try to load it.
1340 return get(filepath8.string(), keyBlob, type, uid);
1341 }
1342
1343 /**
1344 * Returns any existing UserState or creates it if it doesn't exist.
1345 */
1346 UserState* getUserState(uid_t uid) {
1347 uid_t userId = get_user_id(uid);
1348
1349 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1350 it != mMasterKeys.end(); it++) {
1351 UserState* state = *it;
1352 if (state->getUserId() == userId) {
1353 return state;
1354 }
1355 }
1356
1357 UserState* userState = new UserState(userId);
1358 if (!userState->initialize()) {
1359 /* There's not much we can do if initialization fails. Trying to
1360 * unlock the keystore for that user will fail as well, so any
1361 * subsequent request for this user will just return SYSTEM_ERROR.
1362 */
1363 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1364 }
1365 mMasterKeys.add(userState);
1366 return userState;
1367 }
1368
1369 /**
1370 * Returns NULL if the UserState doesn't already exist.
1371 */
1372 const UserState* getUserState(uid_t uid) const {
1373 uid_t userId = get_user_id(uid);
1374
1375 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1376 it != mMasterKeys.end(); it++) {
1377 UserState* state = *it;
1378 if (state->getUserId() == userId) {
1379 return state;
1380 }
1381 }
1382
1383 return NULL;
1384 }
1385
Kenny Roota91203b2012-02-15 15:00:46 -08001386private:
Kenny Root655b9582013-04-04 08:37:42 -07001387 static const char* sOldMasterKey;
1388 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001389 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001390 Entropy* mEntropy;
1391
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07001392 keymaster0_device_t* mDevice;
1393 keymaster0_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001394
Kenny Root655b9582013-04-04 08:37:42 -07001395 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001396
Kenny Root655b9582013-04-04 08:37:42 -07001397 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001398
Kenny Root655b9582013-04-04 08:37:42 -07001399 typedef struct {
1400 uint32_t version;
1401 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001402
Kenny Root655b9582013-04-04 08:37:42 -07001403 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001404
Kenny Root655b9582013-04-04 08:37:42 -07001405 const grant_t* getGrant(const char* filename, uid_t uid) const {
1406 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1407 it != mGrants.end(); it++) {
1408 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001409 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001410 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001411 return grant;
1412 }
1413 }
Kenny Root70e3a862012-02-15 17:20:23 -08001414 return NULL;
1415 }
1416
Kenny Root822c3a92012-03-23 16:34:39 -07001417 /**
1418 * Upgrade code. This will upgrade the key from the current version
1419 * to whatever is newest.
1420 */
Kenny Root655b9582013-04-04 08:37:42 -07001421 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1422 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001423 bool updated = false;
1424 uint8_t version = oldVersion;
1425
1426 /* From V0 -> V1: All old types were unknown */
1427 if (version == 0) {
1428 ALOGV("upgrading to version 1 and setting type %d", type);
1429
1430 blob->setType(type);
1431 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001432 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001433 }
1434 version = 1;
1435 updated = true;
1436 }
1437
Kenny Rootf9119d62013-04-03 09:22:15 -07001438 /* From V1 -> V2: All old keys were encrypted */
1439 if (version == 1) {
1440 ALOGV("upgrading to version 2");
1441
1442 blob->setEncrypted(true);
1443 version = 2;
1444 updated = true;
1445 }
1446
Kenny Root822c3a92012-03-23 16:34:39 -07001447 /*
1448 * If we've updated, set the key blob to the right version
1449 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001450 */
Kenny Root822c3a92012-03-23 16:34:39 -07001451 if (updated) {
1452 ALOGV("updated and writing file %s", filename);
1453 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001454 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001455
1456 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001457 }
1458
1459 /**
1460 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1461 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1462 * Then it overwrites the original blob with the new blob
1463 * format that is returned from the keymaster.
1464 */
Kenny Root655b9582013-04-04 08:37:42 -07001465 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001466 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1467 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1468 if (b.get() == NULL) {
1469 ALOGE("Problem instantiating BIO");
1470 return SYSTEM_ERROR;
1471 }
1472
1473 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1474 if (pkey.get() == NULL) {
1475 ALOGE("Couldn't read old PEM file");
1476 return SYSTEM_ERROR;
1477 }
1478
1479 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1480 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1481 if (len < 0) {
1482 ALOGE("Couldn't measure PKCS#8 length");
1483 return SYSTEM_ERROR;
1484 }
1485
Kenny Root70c98892013-02-07 09:10:36 -08001486 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1487 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001488 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1489 ALOGE("Couldn't convert to PKCS#8");
1490 return SYSTEM_ERROR;
1491 }
1492
Kenny Rootf9119d62013-04-03 09:22:15 -07001493 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1494 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001495 if (rc != NO_ERROR) {
1496 return rc;
1497 }
1498
Kenny Root655b9582013-04-04 08:37:42 -07001499 return get(filename, blob, TYPE_KEY_PAIR, uid);
1500 }
1501
1502 void readMetaData() {
1503 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1504 if (in < 0) {
1505 return;
1506 }
1507 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1508 if (fileLength != sizeof(mMetaData)) {
1509 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1510 sizeof(mMetaData));
1511 }
1512 close(in);
1513 }
1514
1515 void writeMetaData() {
1516 const char* tmpFileName = ".metadata.tmp";
1517 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1518 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1519 if (out < 0) {
1520 ALOGE("couldn't write metadata file: %s", strerror(errno));
1521 return;
1522 }
1523 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1524 if (fileLength != sizeof(mMetaData)) {
1525 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1526 sizeof(mMetaData));
1527 }
1528 close(out);
1529 rename(tmpFileName, sMetaDataFile);
1530 }
1531
1532 bool upgradeKeystore() {
1533 bool upgraded = false;
1534
1535 if (mMetaData.version == 0) {
1536 UserState* userState = getUserState(0);
1537
1538 // Initialize first so the directory is made.
1539 userState->initialize();
1540
1541 // Migrate the old .masterkey file to user 0.
1542 if (access(sOldMasterKey, R_OK) == 0) {
1543 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1544 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1545 return false;
1546 }
1547 }
1548
1549 // Initialize again in case we had a key.
1550 userState->initialize();
1551
1552 // Try to migrate existing keys.
1553 DIR* dir = opendir(".");
1554 if (!dir) {
1555 // Give up now; maybe we can upgrade later.
1556 ALOGE("couldn't open keystore's directory; something is wrong");
1557 return false;
1558 }
1559
1560 struct dirent* file;
1561 while ((file = readdir(dir)) != NULL) {
1562 // We only care about files.
1563 if (file->d_type != DT_REG) {
1564 continue;
1565 }
1566
1567 // Skip anything that starts with a "."
1568 if (file->d_name[0] == '.') {
1569 continue;
1570 }
1571
1572 // Find the current file's user.
1573 char* end;
1574 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1575 if (end[0] != '_' || end[1] == 0) {
1576 continue;
1577 }
1578 UserState* otherUser = getUserState(thisUid);
1579 if (otherUser->getUserId() != 0) {
1580 unlinkat(dirfd(dir), file->d_name, 0);
1581 }
1582
1583 // Rename the file into user directory.
1584 DIR* otherdir = opendir(otherUser->getUserDirName());
1585 if (otherdir == NULL) {
1586 ALOGW("couldn't open user directory for rename");
1587 continue;
1588 }
1589 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1590 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1591 }
1592 closedir(otherdir);
1593 }
1594 closedir(dir);
1595
1596 mMetaData.version = 1;
1597 upgraded = true;
1598 }
1599
1600 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001601 }
Kenny Roota91203b2012-02-15 15:00:46 -08001602};
1603
Kenny Root655b9582013-04-04 08:37:42 -07001604const char* KeyStore::sOldMasterKey = ".masterkey";
1605const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001606
Kenny Root1b0e3932013-09-05 13:06:32 -07001607const android::String16 KeyStore::sRSAKeyType("RSA");
1608
Kenny Root07438c82012-11-02 15:41:02 -07001609namespace android {
1610class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1611public:
1612 KeyStoreProxy(KeyStore* keyStore)
1613 : mKeyStore(keyStore)
1614 {
Kenny Roota91203b2012-02-15 15:00:46 -08001615 }
Kenny Roota91203b2012-02-15 15:00:46 -08001616
Kenny Root07438c82012-11-02 15:41:02 -07001617 void binderDied(const wp<IBinder>&) {
1618 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001619 }
Kenny Roota91203b2012-02-15 15:00:46 -08001620
Kenny Root07438c82012-11-02 15:41:02 -07001621 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001622 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001623 pid_t spid = IPCThreadState::self()->getCallingPid();
1624 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001625 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001626 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001627 }
Kenny Roota91203b2012-02-15 15:00:46 -08001628
Kenny Root655b9582013-04-04 08:37:42 -07001629 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001630 }
1631
Kenny Root07438c82012-11-02 15:41:02 -07001632 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001633 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001634 pid_t spid = IPCThreadState::self()->getCallingPid();
1635 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001636 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001637 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001638 }
Kenny Root07438c82012-11-02 15:41:02 -07001639
Kenny Root07438c82012-11-02 15:41:02 -07001640 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001641 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001642
Kenny Root655b9582013-04-04 08:37:42 -07001643 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001644 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001645 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001646 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001647 *item = NULL;
1648 *itemLength = 0;
1649 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001650 }
Kenny Roota91203b2012-02-15 15:00:46 -08001651
Kenny Root07438c82012-11-02 15:41:02 -07001652 *item = (uint8_t*) malloc(keyBlob.getLength());
1653 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1654 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001655
Kenny Root07438c82012-11-02 15:41:02 -07001656 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001657 }
1658
Kenny Rootf9119d62013-04-03 09:22:15 -07001659 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1660 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001661 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001662 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001663 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001664 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001665 return ::PERMISSION_DENIED;
1666 }
Kenny Root07438c82012-11-02 15:41:02 -07001667
Kenny Rootf9119d62013-04-03 09:22:15 -07001668 State state = mKeyStore->getState(callingUid);
1669 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1670 ALOGD("calling get in state: %d", state);
1671 return state;
1672 }
1673
Kenny Root49468902013-03-19 13:41:33 -07001674 if (targetUid == -1) {
1675 targetUid = callingUid;
1676 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001677 return ::PERMISSION_DENIED;
1678 }
1679
Kenny Root07438c82012-11-02 15:41:02 -07001680 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001681 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001682
1683 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001684 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1685
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001686 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001687 }
1688
Kenny Root49468902013-03-19 13:41:33 -07001689 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001690 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001691 pid_t spid = IPCThreadState::self()->getCallingPid();
1692 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001693 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001694 return ::PERMISSION_DENIED;
1695 }
Kenny Root70e3a862012-02-15 17:20:23 -08001696
Kenny Root49468902013-03-19 13:41:33 -07001697 if (targetUid == -1) {
1698 targetUid = callingUid;
1699 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001700 return ::PERMISSION_DENIED;
1701 }
1702
Kenny Root07438c82012-11-02 15:41:02 -07001703 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001704 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01001705 return mKeyStore->del(filename.string(), ::TYPE_GENERIC, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001706 }
1707
Kenny Root49468902013-03-19 13:41:33 -07001708 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001709 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001710 pid_t spid = IPCThreadState::self()->getCallingPid();
1711 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001712 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001713 return ::PERMISSION_DENIED;
1714 }
Kenny Root70e3a862012-02-15 17:20:23 -08001715
Kenny Root49468902013-03-19 13:41:33 -07001716 if (targetUid == -1) {
1717 targetUid = callingUid;
1718 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001719 return ::PERMISSION_DENIED;
1720 }
1721
Kenny Root07438c82012-11-02 15:41:02 -07001722 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001723 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001724
Kenny Root655b9582013-04-04 08:37:42 -07001725 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001726 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1727 }
1728 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001729 }
1730
Kenny Root49468902013-03-19 13:41:33 -07001731 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001732 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001733 pid_t spid = IPCThreadState::self()->getCallingPid();
1734 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001735 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001736 return ::PERMISSION_DENIED;
1737 }
Kenny Root70e3a862012-02-15 17:20:23 -08001738
Kenny Root49468902013-03-19 13:41:33 -07001739 if (targetUid == -1) {
1740 targetUid = callingUid;
1741 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001742 return ::PERMISSION_DENIED;
1743 }
1744
Kenny Root07438c82012-11-02 15:41:02 -07001745 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001746 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001747
Robin Lee4b84fdc2014-09-24 11:56:57 +01001748 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1749 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001750 }
Kenny Root07438c82012-11-02 15:41:02 -07001751 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001752 }
1753
Kenny Root07438c82012-11-02 15:41:02 -07001754 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001755 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001756 pid_t spid = IPCThreadState::self()->getCallingPid();
1757 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001758 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001759 return ::PERMISSION_DENIED;
1760 }
1761
Robin Lee4b84fdc2014-09-24 11:56:57 +01001762 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001763 }
1764
Kenny Root07438c82012-11-02 15:41:02 -07001765 /*
1766 * Here is the history. To improve the security, the parameters to generate the
1767 * master key has been changed. To make a seamless transition, we update the
1768 * file using the same password when the user unlock it for the first time. If
1769 * any thing goes wrong during the transition, the new file will not overwrite
1770 * the old one. This avoids permanent damages of the existing data.
1771 */
1772 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001773 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001774 pid_t spid = IPCThreadState::self()->getCallingPid();
1775 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001776 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001777 return ::PERMISSION_DENIED;
1778 }
Kenny Root70e3a862012-02-15 17:20:23 -08001779
Kenny Root07438c82012-11-02 15:41:02 -07001780 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001781
Kenny Root655b9582013-04-04 08:37:42 -07001782 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001783 case ::STATE_UNINITIALIZED: {
1784 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001785 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001786 }
1787 case ::STATE_NO_ERROR: {
1788 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001789 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001790 }
1791 case ::STATE_LOCKED: {
1792 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001793 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001794 }
1795 }
1796 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001797 }
1798
Kenny Root07438c82012-11-02 15:41:02 -07001799 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001800 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001801 pid_t spid = IPCThreadState::self()->getCallingPid();
1802 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001803 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001804 return ::PERMISSION_DENIED;
1805 }
Kenny Root70e3a862012-02-15 17:20:23 -08001806
Kenny Root655b9582013-04-04 08:37:42 -07001807 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001808 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001809 ALOGD("calling lock in state: %d", state);
1810 return state;
1811 }
1812
Kenny Root655b9582013-04-04 08:37:42 -07001813 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001814 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001815 }
1816
Kenny Root07438c82012-11-02 15:41:02 -07001817 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001818 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001819 pid_t spid = IPCThreadState::self()->getCallingPid();
1820 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001821 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001822 return ::PERMISSION_DENIED;
1823 }
1824
Kenny Root655b9582013-04-04 08:37:42 -07001825 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001826 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001827 ALOGD("calling unlock when not locked");
1828 return state;
1829 }
1830
1831 const String8 password8(pw);
1832 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001833 }
1834
Kenny Root07438c82012-11-02 15:41:02 -07001835 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001836 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001837 pid_t spid = IPCThreadState::self()->getCallingPid();
1838 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001839 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001840 return -1;
1841 }
Kenny Root70e3a862012-02-15 17:20:23 -08001842
Kenny Root655b9582013-04-04 08:37:42 -07001843 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001844 }
1845
Kenny Root96427ba2013-08-16 14:02:41 -07001846 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1847 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001848 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001849 pid_t spid = IPCThreadState::self()->getCallingPid();
1850 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001851 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001852 return ::PERMISSION_DENIED;
1853 }
Kenny Root70e3a862012-02-15 17:20:23 -08001854
Kenny Root49468902013-03-19 13:41:33 -07001855 if (targetUid == -1) {
1856 targetUid = callingUid;
1857 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001858 return ::PERMISSION_DENIED;
1859 }
1860
Kenny Root655b9582013-04-04 08:37:42 -07001861 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001862 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1863 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001864 return state;
1865 }
Kenny Root70e3a862012-02-15 17:20:23 -08001866
Kenny Root07438c82012-11-02 15:41:02 -07001867 uint8_t* data;
1868 size_t dataLength;
1869 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001870 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001871
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07001872 const keymaster0_device_t* device = mKeyStore->getDevice();
1873 const keymaster0_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001874 if (device == NULL) {
1875 return ::SYSTEM_ERROR;
1876 }
1877
1878 if (device->generate_keypair == NULL) {
1879 return ::SYSTEM_ERROR;
1880 }
1881
Kenny Root17208e02013-09-04 13:56:03 -07001882 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001883 keymaster_dsa_keygen_params_t dsa_params;
1884 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001885
Kenny Root96427ba2013-08-16 14:02:41 -07001886 if (keySize == -1) {
1887 keySize = DSA_DEFAULT_KEY_SIZE;
1888 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1889 || keySize > DSA_MAX_KEY_SIZE) {
1890 ALOGI("invalid key size %d", keySize);
1891 return ::SYSTEM_ERROR;
1892 }
1893 dsa_params.key_size = keySize;
1894
1895 if (args->size() == 3) {
1896 sp<KeystoreArg> gArg = args->itemAt(0);
1897 sp<KeystoreArg> pArg = args->itemAt(1);
1898 sp<KeystoreArg> qArg = args->itemAt(2);
1899
1900 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1901 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1902 dsa_params.generator_len = gArg->size();
1903
1904 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1905 dsa_params.prime_p_len = pArg->size();
1906
1907 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1908 dsa_params.prime_q_len = qArg->size();
1909 } else {
1910 ALOGI("not all DSA parameters were read");
1911 return ::SYSTEM_ERROR;
1912 }
1913 } else if (args->size() != 0) {
1914 ALOGI("DSA args must be 3");
1915 return ::SYSTEM_ERROR;
1916 }
1917
Kenny Root1d448c02013-11-21 10:36:53 -08001918 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001919 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1920 } else {
1921 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001922 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1923 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001924 }
1925 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001926 keymaster_ec_keygen_params_t ec_params;
1927 memset(&ec_params, '\0', sizeof(ec_params));
1928
1929 if (keySize == -1) {
1930 keySize = EC_DEFAULT_KEY_SIZE;
1931 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1932 ALOGI("invalid key size %d", keySize);
1933 return ::SYSTEM_ERROR;
1934 }
1935 ec_params.field_size = keySize;
1936
Kenny Root1d448c02013-11-21 10:36:53 -08001937 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001938 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1939 } else {
1940 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001941 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001942 }
Kenny Root96427ba2013-08-16 14:02:41 -07001943 } else if (keyType == EVP_PKEY_RSA) {
1944 keymaster_rsa_keygen_params_t rsa_params;
1945 memset(&rsa_params, '\0', sizeof(rsa_params));
1946 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1947
1948 if (keySize == -1) {
1949 keySize = RSA_DEFAULT_KEY_SIZE;
1950 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1951 ALOGI("invalid key size %d", keySize);
1952 return ::SYSTEM_ERROR;
1953 }
1954 rsa_params.modulus_size = keySize;
1955
1956 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001957 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001958 return ::SYSTEM_ERROR;
1959 } else if (args->size() == 1) {
1960 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1961 if (pubExpBlob != NULL) {
1962 Unique_BIGNUM pubExpBn(
1963 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1964 pubExpBlob->size(), NULL));
1965 if (pubExpBn.get() == NULL) {
1966 ALOGI("Could not convert public exponent to BN");
1967 return ::SYSTEM_ERROR;
1968 }
1969 unsigned long pubExp = BN_get_word(pubExpBn.get());
1970 if (pubExp == 0xFFFFFFFFL) {
1971 ALOGI("cannot represent public exponent as a long value");
1972 return ::SYSTEM_ERROR;
1973 }
1974 rsa_params.public_exponent = pubExp;
1975 }
1976 }
1977
1978 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1979 } else {
1980 ALOGW("Unsupported key type %d", keyType);
1981 rc = -1;
1982 }
1983
Kenny Root07438c82012-11-02 15:41:02 -07001984 if (rc) {
1985 return ::SYSTEM_ERROR;
1986 }
1987
Kenny Root655b9582013-04-04 08:37:42 -07001988 String8 name8(name);
1989 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001990
1991 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1992 free(data);
1993
Kenny Rootee8068b2013-10-07 09:49:15 -07001994 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001995 keyBlob.setFallback(isFallback);
1996
Kenny Root655b9582013-04-04 08:37:42 -07001997 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001998 }
1999
Kenny Rootf9119d62013-04-03 09:22:15 -07002000 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2001 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002002 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002003 pid_t spid = IPCThreadState::self()->getCallingPid();
2004 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002005 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002006 return ::PERMISSION_DENIED;
2007 }
Kenny Root07438c82012-11-02 15:41:02 -07002008
Kenny Root49468902013-03-19 13:41:33 -07002009 if (targetUid == -1) {
2010 targetUid = callingUid;
2011 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002012 return ::PERMISSION_DENIED;
2013 }
2014
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002015 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07002016 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002017 ALOGD("calling import in state: %d", state);
2018 return state;
2019 }
2020
2021 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002022 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002023
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002024 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002025 }
2026
Kenny Root07438c82012-11-02 15:41:02 -07002027 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2028 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002029 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002030 pid_t spid = IPCThreadState::self()->getCallingPid();
2031 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002032 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002033 return ::PERMISSION_DENIED;
2034 }
Kenny Root07438c82012-11-02 15:41:02 -07002035
Kenny Root07438c82012-11-02 15:41:02 -07002036 Blob keyBlob;
2037 String8 name8(name);
2038
Kenny Rootd38a0b02013-02-13 12:59:14 -08002039 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002040 int rc;
2041
Kenny Root655b9582013-04-04 08:37:42 -07002042 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002043 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002044 if (responseCode != ::NO_ERROR) {
2045 return responseCode;
2046 }
2047
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07002048 const keymaster0_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002049 if (device == NULL) {
2050 ALOGE("no keymaster device; cannot sign");
2051 return ::SYSTEM_ERROR;
2052 }
2053
2054 if (device->sign_data == NULL) {
2055 ALOGE("device doesn't implement signing");
2056 return ::SYSTEM_ERROR;
2057 }
2058
2059 keymaster_rsa_sign_params_t params;
2060 params.digest_type = DIGEST_NONE;
2061 params.padding_type = PADDING_NONE;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002062 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2063 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002064 if (rc) {
2065 ALOGW("device couldn't sign data");
2066 return ::SYSTEM_ERROR;
2067 }
2068
2069 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002070 }
2071
Kenny Root07438c82012-11-02 15:41:02 -07002072 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2073 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002074 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002075 pid_t spid = IPCThreadState::self()->getCallingPid();
2076 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002077 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002078 return ::PERMISSION_DENIED;
2079 }
Kenny Root70e3a862012-02-15 17:20:23 -08002080
Kenny Root655b9582013-04-04 08:37:42 -07002081 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002082 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002083 ALOGD("calling verify in state: %d", state);
2084 return state;
2085 }
Kenny Root70e3a862012-02-15 17:20:23 -08002086
Kenny Root07438c82012-11-02 15:41:02 -07002087 Blob keyBlob;
2088 String8 name8(name);
2089 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002090
Kenny Root655b9582013-04-04 08:37:42 -07002091 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002092 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002093 if (responseCode != ::NO_ERROR) {
2094 return responseCode;
2095 }
Kenny Root70e3a862012-02-15 17:20:23 -08002096
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07002097 const keymaster0_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002098 if (device == NULL) {
2099 return ::SYSTEM_ERROR;
2100 }
Kenny Root70e3a862012-02-15 17:20:23 -08002101
Kenny Root07438c82012-11-02 15:41:02 -07002102 if (device->verify_data == NULL) {
2103 return ::SYSTEM_ERROR;
2104 }
Kenny Root70e3a862012-02-15 17:20:23 -08002105
Kenny Root07438c82012-11-02 15:41:02 -07002106 keymaster_rsa_sign_params_t params;
2107 params.digest_type = DIGEST_NONE;
2108 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002109
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002110 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2111 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002112 if (rc) {
2113 return ::SYSTEM_ERROR;
2114 } else {
2115 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002116 }
2117 }
Kenny Root07438c82012-11-02 15:41:02 -07002118
2119 /*
2120 * TODO: The abstraction between things stored in hardware and regular blobs
2121 * of data stored on the filesystem should be moved down to keystore itself.
2122 * Unfortunately the Java code that calls this has naming conventions that it
2123 * knows about. Ideally keystore shouldn't be used to store random blobs of
2124 * data.
2125 *
2126 * Until that happens, it's necessary to have a separate "get_pubkey" and
2127 * "del_key" since the Java code doesn't really communicate what it's
2128 * intentions are.
2129 */
2130 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002131 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002132 pid_t spid = IPCThreadState::self()->getCallingPid();
2133 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002134 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002135 return ::PERMISSION_DENIED;
2136 }
Kenny Root07438c82012-11-02 15:41:02 -07002137
Kenny Root07438c82012-11-02 15:41:02 -07002138 Blob keyBlob;
2139 String8 name8(name);
2140
Kenny Rootd38a0b02013-02-13 12:59:14 -08002141 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002142
Kenny Root655b9582013-04-04 08:37:42 -07002143 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002144 TYPE_KEY_PAIR);
2145 if (responseCode != ::NO_ERROR) {
2146 return responseCode;
2147 }
2148
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07002149 const keymaster0_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002150 if (device == NULL) {
2151 return ::SYSTEM_ERROR;
2152 }
2153
2154 if (device->get_keypair_public == NULL) {
2155 ALOGE("device has no get_keypair_public implementation!");
2156 return ::SYSTEM_ERROR;
2157 }
2158
Kenny Root17208e02013-09-04 13:56:03 -07002159 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002160 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2161 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002162 if (rc) {
2163 return ::SYSTEM_ERROR;
2164 }
2165
2166 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002167 }
Kenny Root07438c82012-11-02 15:41:02 -07002168
Kenny Root49468902013-03-19 13:41:33 -07002169 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002170 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002171 pid_t spid = IPCThreadState::self()->getCallingPid();
2172 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002173 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002174 return ::PERMISSION_DENIED;
2175 }
Kenny Root07438c82012-11-02 15:41:02 -07002176
Kenny Root49468902013-03-19 13:41:33 -07002177 if (targetUid == -1) {
2178 targetUid = callingUid;
2179 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002180 return ::PERMISSION_DENIED;
2181 }
2182
Kenny Root07438c82012-11-02 15:41:02 -07002183 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002184 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01002185 return mKeyStore->del(filename.string(), ::TYPE_KEY_PAIR, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002186 }
2187
2188 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002189 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002190 pid_t spid = IPCThreadState::self()->getCallingPid();
2191 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002192 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002193 return ::PERMISSION_DENIED;
2194 }
Kenny Root07438c82012-11-02 15:41:02 -07002195
Kenny Root655b9582013-04-04 08:37:42 -07002196 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002197 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002198 ALOGD("calling grant in state: %d", state);
2199 return state;
2200 }
2201
2202 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002203 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002204
Kenny Root655b9582013-04-04 08:37:42 -07002205 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002206 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2207 }
2208
Kenny Root655b9582013-04-04 08:37:42 -07002209 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002210 return ::NO_ERROR;
2211 }
2212
2213 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002214 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002215 pid_t spid = IPCThreadState::self()->getCallingPid();
2216 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002217 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002218 return ::PERMISSION_DENIED;
2219 }
Kenny Root07438c82012-11-02 15:41:02 -07002220
Kenny Root655b9582013-04-04 08:37:42 -07002221 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002222 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002223 ALOGD("calling ungrant in state: %d", state);
2224 return state;
2225 }
2226
2227 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002228 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002229
Kenny Root655b9582013-04-04 08:37:42 -07002230 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002231 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2232 }
2233
Kenny Root655b9582013-04-04 08:37:42 -07002234 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002235 }
2236
2237 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002238 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002239 pid_t spid = IPCThreadState::self()->getCallingPid();
2240 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002241 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002242 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002243 }
Kenny Root07438c82012-11-02 15:41:02 -07002244
2245 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002246 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002247
Kenny Root655b9582013-04-04 08:37:42 -07002248 if (access(filename.string(), R_OK) == -1) {
2249 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002250 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002251 }
2252
Kenny Root655b9582013-04-04 08:37:42 -07002253 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002254 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002255 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002256 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002257 }
2258
2259 struct stat s;
2260 int ret = fstat(fd, &s);
2261 close(fd);
2262 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002263 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002264 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002265 }
2266
Kenny Root36a9e232013-02-04 14:24:15 -08002267 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002268 }
2269
Kenny Rootd53bc922013-03-21 14:10:15 -07002270 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2271 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002272 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002273 pid_t spid = IPCThreadState::self()->getCallingPid();
2274 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002275 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002276 return -1L;
2277 }
2278
Kenny Root655b9582013-04-04 08:37:42 -07002279 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002280 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002281 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002282 return state;
2283 }
2284
Kenny Rootd53bc922013-03-21 14:10:15 -07002285 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2286 srcUid = callingUid;
2287 } else if (!is_granted_to(callingUid, srcUid)) {
2288 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002289 return ::PERMISSION_DENIED;
2290 }
2291
Kenny Rootd53bc922013-03-21 14:10:15 -07002292 if (destUid == -1) {
2293 destUid = callingUid;
2294 }
2295
2296 if (srcUid != destUid) {
2297 if (static_cast<uid_t>(srcUid) != callingUid) {
2298 ALOGD("can only duplicate from caller to other or to same uid: "
2299 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2300 return ::PERMISSION_DENIED;
2301 }
2302
2303 if (!is_granted_to(callingUid, destUid)) {
2304 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2305 return ::PERMISSION_DENIED;
2306 }
2307 }
2308
2309 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002310 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002311
Kenny Rootd53bc922013-03-21 14:10:15 -07002312 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002313 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002314
Kenny Root655b9582013-04-04 08:37:42 -07002315 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2316 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002317 return ::SYSTEM_ERROR;
2318 }
2319
Kenny Rootd53bc922013-03-21 14:10:15 -07002320 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002321 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002322 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002323 if (responseCode != ::NO_ERROR) {
2324 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002325 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002326
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002327 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002328 }
2329
Kenny Root1b0e3932013-09-05 13:06:32 -07002330 int32_t is_hardware_backed(const String16& keyType) {
2331 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002332 }
2333
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002334 int32_t clear_uid(int64_t targetUid64) {
2335 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002336 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002337 pid_t spid = IPCThreadState::self()->getCallingPid();
2338 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002339 ALOGW("permission denied for %d: clear_uid", callingUid);
2340 return ::PERMISSION_DENIED;
2341 }
2342
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002343 if (targetUid64 == -1) {
2344 targetUid = callingUid;
Kenny Root007cb232014-07-30 16:59:42 -07002345 } else if (!is_self_or_system(callingUid, targetUid)) {
2346 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002347 return ::PERMISSION_DENIED;
2348 }
2349
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07002350 const keymaster0_device_t* device = mKeyStore->getDevice();
Kenny Roota9bb5492013-04-01 16:29:11 -07002351 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002352 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002353 return ::SYSTEM_ERROR;
2354 }
2355
Robin Lee4b84fdc2014-09-24 11:56:57 +01002356 String8 prefix = String8::format("%u_", targetUid);
2357 Vector<String16> aliases;
2358 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002359 return ::SYSTEM_ERROR;
2360 }
2361
Robin Lee4b84fdc2014-09-24 11:56:57 +01002362 for (uint32_t i = 0; i < aliases.size(); i++) {
2363 String8 name8(aliases[i]);
2364 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2365 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002366 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002367 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002368 }
2369
Robin Lee4b84fdc2014-09-24 11:56:57 +01002370 int32_t reset_uid(int32_t targetUid) {
Robin Lee4e865752014-08-19 17:37:55 +01002371 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2372 pid_t spid = IPCThreadState::self()->getCallingPid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01002373
Robin Lee4e865752014-08-19 17:37:55 +01002374 if (!has_permission(callingUid, P_RESET_UID, spid)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01002375 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002376 return ::PERMISSION_DENIED;
2377 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002378 if (!is_self_or_system(callingUid, targetUid)) {
2379 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002380 return ::PERMISSION_DENIED;
2381 }
2382
Robin Lee4b84fdc2014-09-24 11:56:57 +01002383 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002384 }
2385
2386 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
2387 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2388 pid_t spid = IPCThreadState::self()->getCallingPid();
2389 if (!has_permission(callingUid, P_SYNC_UID, spid)) {
2390 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2391 return ::PERMISSION_DENIED;
2392 }
2393 if (callingUid != AID_SYSTEM) {
2394 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2395 return ::PERMISSION_DENIED;
2396 }
2397 if (sourceUid == targetUid) {
2398 return ::SYSTEM_ERROR;
2399 }
2400
2401 // Initialise user keystore with existing master key held in-memory
2402 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2403 }
2404
2405 int32_t password_uid(const String16& pw, int32_t targetUid) {
2406 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2407 pid_t spid = IPCThreadState::self()->getCallingPid();
2408 if (!has_permission(callingUid, P_PASSWORD_UID, spid)) {
2409 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2410 return ::PERMISSION_DENIED;
2411 }
2412 if (callingUid != AID_SYSTEM) {
2413 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2414 return ::PERMISSION_DENIED;
2415 }
2416
2417 const String8 password8(pw);
2418
2419 switch (mKeyStore->getState(targetUid)) {
2420 case ::STATE_UNINITIALIZED: {
2421 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2422 return mKeyStore->initializeUser(password8, targetUid);
2423 }
2424 case ::STATE_NO_ERROR: {
2425 // rewrite master key with new password.
2426 return mKeyStore->writeMasterKey(password8, targetUid);
2427 }
2428 case ::STATE_LOCKED: {
2429 // read master key, decrypt with password, initialize mMasterKey*.
2430 return mKeyStore->readMasterKey(password8, targetUid);
2431 }
2432 }
2433 return ::SYSTEM_ERROR;
2434 }
2435
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002436 int32_t addRngEntropy(const uint8_t* /*data*/, size_t /*dataLength*/) {
2437 return KM_ERROR_UNIMPLEMENTED;
2438 }
2439
2440 int32_t generateKey(const String16& /*name*/, const KeymasterArguments& /*params*/,
2441 int /*uid*/, int /*flags*/, KeyCharacteristics* /*outCharacteristics*/) {
2442 return KM_ERROR_UNIMPLEMENTED;
2443 }
2444
2445 int32_t getKeyCharacteristics(const String16& /*name*/,
2446 const keymaster_blob_t& /*clientId*/,
2447 const keymaster_blob_t& /*appData*/,
2448 KeyCharacteristics* /*outCharacteristics*/) {
2449 return KM_ERROR_UNIMPLEMENTED;
2450 }
2451
2452 int32_t importKey(const String16& /*name*/, const KeymasterArguments& /*params*/,
2453 keymaster_key_format_t /*format*/, const uint8_t* /*keyData*/,
2454 size_t /*keyLength*/, int /*uid*/, int /*flags*/,
2455 KeyCharacteristics* /*outCharacteristics*/) {
2456 return KM_ERROR_UNIMPLEMENTED;
2457 }
2458
2459 void exportKey(const String16& /*name*/, keymaster_key_format_t /*format*/,
2460 const keymaster_blob_t& /*clientId*/,
2461 const keymaster_blob_t& /*appData*/, ExportResult* result) {
2462 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2463 }
2464
2465 void begin(const sp<IBinder>& /*appToken*/, const String16& /*name*/,
2466 keymaster_purpose_t /*purpose*/, bool /*pruneable*/,
2467 const KeymasterArguments& /*params*/, KeymasterArguments* /*outParams*/,
2468 OperationResult* result) {
2469 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2470 }
2471
2472 void update(const sp<IBinder>& /*token*/, const KeymasterArguments& /*params*/,
2473 uint8_t* /*data*/, size_t /*dataLength*/, OperationResult* result) {
2474 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2475 }
2476
2477 void finish(const sp<IBinder>& /*token*/, const KeymasterArguments& /*args*/,
2478 uint8_t* /*signature*/, size_t /*signatureLength*/, OperationResult* result) {
2479 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2480 }
2481
2482 int32_t abort(const sp<IBinder>& /*token*/) {
2483 return KM_ERROR_UNIMPLEMENTED;
2484 }
2485
Kenny Root07438c82012-11-02 15:41:02 -07002486private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002487 inline bool isKeystoreUnlocked(State state) {
2488 switch (state) {
2489 case ::STATE_NO_ERROR:
2490 return true;
2491 case ::STATE_UNINITIALIZED:
2492 case ::STATE_LOCKED:
2493 return false;
2494 }
2495 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002496 }
2497
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07002498 bool isKeyTypeSupported(const keymaster0_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002499 const int32_t device_api = device->common.module->module_api_version;
2500 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2501 switch (keyType) {
2502 case TYPE_RSA:
2503 case TYPE_DSA:
2504 case TYPE_EC:
2505 return true;
2506 default:
2507 return false;
2508 }
2509 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2510 switch (keyType) {
2511 case TYPE_RSA:
2512 return true;
2513 case TYPE_DSA:
2514 return device->flags & KEYMASTER_SUPPORTS_DSA;
2515 case TYPE_EC:
2516 return device->flags & KEYMASTER_SUPPORTS_EC;
2517 default:
2518 return false;
2519 }
2520 } else {
2521 return keyType == TYPE_RSA;
2522 }
2523 }
2524
Kenny Root07438c82012-11-02 15:41:02 -07002525 ::KeyStore* mKeyStore;
2526};
2527
2528}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002529
2530int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002531 if (argc < 2) {
2532 ALOGE("A directory must be specified!");
2533 return 1;
2534 }
2535 if (chdir(argv[1]) == -1) {
2536 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2537 return 1;
2538 }
2539
2540 Entropy entropy;
2541 if (!entropy.open()) {
2542 return 1;
2543 }
Kenny Root70e3a862012-02-15 17:20:23 -08002544
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07002545 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08002546 if (keymaster_device_initialize(&dev)) {
2547 ALOGE("keystore keymaster could not be initialized; exiting");
2548 return 1;
2549 }
2550
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07002551 keymaster0_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002552 if (fallback_keymaster_device_initialize(&fallback)) {
2553 ALOGE("software keymaster could not be initialized; exiting");
2554 return 1;
2555 }
2556
Riley Spahneaabae92014-06-30 12:39:52 -07002557 ks_is_selinux_enabled = is_selinux_enabled();
2558 if (ks_is_selinux_enabled) {
2559 union selinux_callback cb;
2560 cb.func_log = selinux_log_callback;
2561 selinux_set_callback(SELINUX_CB_LOG, cb);
2562 if (getcon(&tctx) != 0) {
2563 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2564 return -1;
2565 }
2566 } else {
2567 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2568 }
2569
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002570 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07002571 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002572 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2573 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2574 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2575 if (ret != android::OK) {
2576 ALOGE("Couldn't register binder service!");
2577 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002578 }
Kenny Root07438c82012-11-02 15:41:02 -07002579
2580 /*
2581 * We're the only thread in existence, so we're just going to process
2582 * Binder transaction as a single-threaded program.
2583 */
2584 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002585
2586 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002587 return 1;
2588}