blob: c17eacc7310c1203989232b0ec464515a8bf6696 [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>
Chad Brubaker919cb2a2015-02-05 21:58:25 -080047#include <keymaster/soft_keymaster_device.h>
Kenny Root17208e02013-09-04 13:56:03 -070048
Kenny Root26cfc082013-09-11 14:38:56 -070049#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070050#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080052
Kenny Root07438c82012-11-02 15:41:02 -070053#include <keystore/IKeystoreService.h>
54#include <binder/IPCThreadState.h>
55#include <binder/IServiceManager.h>
56
Kenny Roota91203b2012-02-15 15:00:46 -080057#include <cutils/log.h>
58#include <cutils/sockets.h>
59#include <private/android_filesystem_config.h>
60
Kenny Root07438c82012-11-02 15:41:02 -070061#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080062
Riley Spahneaabae92014-06-30 12:39:52 -070063#include <selinux/android.h>
64
Kenny Root96427ba2013-08-16 14:02:41 -070065#include "defaults.h"
66
Kenny Roota91203b2012-02-15 15:00:46 -080067/* KeyStore is a secured storage for key-value pairs. In this implementation,
68 * each file stores one key-value pair. Keys are encoded in file names, and
69 * values are encrypted with checksums. The encryption key is protected by a
70 * user-defined password. To keep things simple, buffers are always larger than
71 * the maximum space we needed, so boundary checks on buffers are omitted. */
72
73#define KEY_SIZE ((NAME_MAX - 15) / 2)
74#define VALUE_SIZE 32768
75#define PASSWORD_SIZE VALUE_SIZE
76
Kenny Root822c3a92012-03-23 16:34:39 -070077
Kenny Root96427ba2013-08-16 14:02:41 -070078struct BIGNUM_Delete {
79 void operator()(BIGNUM* p) const {
80 BN_free(p);
81 }
82};
83typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
84
Kenny Root822c3a92012-03-23 16:34:39 -070085struct BIO_Delete {
86 void operator()(BIO* p) const {
87 BIO_free(p);
88 }
89};
90typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
91
92struct EVP_PKEY_Delete {
93 void operator()(EVP_PKEY* p) const {
94 EVP_PKEY_free(p);
95 }
96};
97typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
98
99struct PKCS8_PRIV_KEY_INFO_Delete {
100 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
101 PKCS8_PRIV_KEY_INFO_free(p);
102 }
103};
104typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
105
106
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700107static int keymaster_device_initialize(keymaster0_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800108 int rc;
109
110 const hw_module_t* mod;
111 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
112 if (rc) {
113 ALOGE("could not find any keystore module");
114 goto out;
115 }
116
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700117 rc = keymaster0_open(mod, dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800118 if (rc) {
119 ALOGE("could not open keymaster device in %s (%s)",
120 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
121 goto out;
122 }
123
124 return 0;
125
126out:
127 *dev = NULL;
128 return rc;
129}
130
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800131static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
132 keymaster::SoftKeymasterDevice* softkeymaster =
133 new keymaster::SoftKeymasterDevice();
134 // SoftKeymasterDevice is designed to make this cast safe.
135 *dev = reinterpret_cast<keymaster1_device_t*>(softkeymaster);
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800136 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800137}
138
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700139static void keymaster_device_release(keymaster0_device_t* dev) {
140 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800141}
142
Kenny Root07438c82012-11-02 15:41:02 -0700143/***************
144 * PERMISSIONS *
145 ***************/
146
147/* Here are the permissions, actions, users, and the main function. */
148typedef enum {
Robin Lee4e865752014-08-19 17:37:55 +0100149 P_TEST = 1 << 0,
150 P_GET = 1 << 1,
151 P_INSERT = 1 << 2,
152 P_DELETE = 1 << 3,
153 P_EXIST = 1 << 4,
154 P_SAW = 1 << 5,
155 P_RESET = 1 << 6,
156 P_PASSWORD = 1 << 7,
157 P_LOCK = 1 << 8,
158 P_UNLOCK = 1 << 9,
159 P_ZERO = 1 << 10,
160 P_SIGN = 1 << 11,
161 P_VERIFY = 1 << 12,
162 P_GRANT = 1 << 13,
163 P_DUPLICATE = 1 << 14,
164 P_CLEAR_UID = 1 << 15,
165 P_RESET_UID = 1 << 16,
166 P_SYNC_UID = 1 << 17,
167 P_PASSWORD_UID = 1 << 18,
Kenny Root07438c82012-11-02 15:41:02 -0700168} perm_t;
169
170static struct user_euid {
171 uid_t uid;
172 uid_t euid;
173} user_euids[] = {
174 {AID_VPN, AID_SYSTEM},
175 {AID_WIFI, AID_SYSTEM},
176 {AID_ROOT, AID_SYSTEM},
177};
178
Riley Spahneaabae92014-06-30 12:39:52 -0700179/* perm_labels associcated with keystore_key SELinux class verbs. */
180const char *perm_labels[] = {
181 "test",
182 "get",
183 "insert",
184 "delete",
185 "exist",
186 "saw",
187 "reset",
188 "password",
189 "lock",
190 "unlock",
191 "zero",
192 "sign",
193 "verify",
194 "grant",
195 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100196 "clear_uid",
197 "reset_uid",
198 "sync_uid",
199 "password_uid",
Riley Spahneaabae92014-06-30 12:39:52 -0700200};
201
Kenny Root07438c82012-11-02 15:41:02 -0700202static struct user_perm {
203 uid_t uid;
204 perm_t perms;
205} user_perms[] = {
206 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
207 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
208 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
209 {AID_ROOT, static_cast<perm_t>(P_GET) },
210};
211
212static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
213 | P_VERIFY);
214
Riley Spahneaabae92014-06-30 12:39:52 -0700215static char *tctx;
216static int ks_is_selinux_enabled;
217
218static const char *get_perm_label(perm_t perm) {
219 unsigned int index = ffs(perm);
220 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
221 return perm_labels[index - 1];
222 } else {
223 ALOGE("Keystore: Failed to retrieve permission label.\n");
224 abort();
225 }
226}
227
Kenny Root655b9582013-04-04 08:37:42 -0700228/**
229 * Returns the app ID (in the Android multi-user sense) for the current
230 * UNIX UID.
231 */
232static uid_t get_app_id(uid_t uid) {
233 return uid % AID_USER;
234}
235
236/**
237 * Returns the user ID (in the Android multi-user sense) for the current
238 * UNIX UID.
239 */
240static uid_t get_user_id(uid_t uid) {
241 return uid / AID_USER;
242}
243
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700244static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700245 if (!ks_is_selinux_enabled) {
246 return true;
247 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000248
Riley Spahneaabae92014-06-30 12:39:52 -0700249 char *sctx = NULL;
250 const char *selinux_class = "keystore_key";
251 const char *str_perm = get_perm_label(perm);
252
253 if (!str_perm) {
254 return false;
255 }
256
257 if (getpidcon(spid, &sctx) != 0) {
258 ALOGE("SELinux: Failed to get source pid context.\n");
259 return false;
260 }
261
262 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
263 NULL) == 0;
264 freecon(sctx);
265 return allowed;
266}
267
268static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700269 // All system users are equivalent for multi-user support.
270 if (get_app_id(uid) == AID_SYSTEM) {
271 uid = AID_SYSTEM;
272 }
273
Kenny Root07438c82012-11-02 15:41:02 -0700274 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
275 struct user_perm user = user_perms[i];
276 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700277 return (user.perms & perm) &&
278 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700279 }
280 }
281
Riley Spahneaabae92014-06-30 12:39:52 -0700282 return (DEFAULT_PERMS & perm) &&
283 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700284}
285
Kenny Root49468902013-03-19 13:41:33 -0700286/**
287 * Returns the UID that the callingUid should act as. This is here for
288 * legacy support of the WiFi and VPN systems and should be removed
289 * when WiFi can operate in its own namespace.
290 */
Kenny Root07438c82012-11-02 15:41:02 -0700291static uid_t get_keystore_euid(uid_t uid) {
292 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
293 struct user_euid user = user_euids[i];
294 if (user.uid == uid) {
295 return user.euid;
296 }
297 }
298
299 return uid;
300}
301
Kenny Root49468902013-03-19 13:41:33 -0700302/**
303 * Returns true if the callingUid is allowed to interact in the targetUid's
304 * namespace.
305 */
306static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
307 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
308 struct user_euid user = user_euids[i];
309 if (user.euid == callingUid && user.uid == targetUid) {
310 return true;
311 }
312 }
313
314 return false;
315}
316
Kenny Root007cb232014-07-30 16:59:42 -0700317/**
318 * Allow the system to perform some privileged tasks that have to do with
319 * system maintenance. This should not be used for any function that uses
320 * the keys in any way (e.g., signing).
321 */
322static bool is_self_or_system(uid_t callingUid, uid_t targetUid) {
323 return callingUid == targetUid || callingUid == AID_SYSTEM;
324}
325
Kenny Roota91203b2012-02-15 15:00:46 -0800326/* Here is the encoding of keys. This is necessary in order to allow arbitrary
327 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
328 * into two bytes. The first byte is one of [+-.] which represents the first
329 * two bits of the character. The second byte encodes the rest of the bits into
330 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
331 * that Base64 cannot be used here due to the need of prefix match on keys. */
332
Kenny Root655b9582013-04-04 08:37:42 -0700333static size_t encode_key_length(const android::String8& keyName) {
334 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
335 size_t length = keyName.length();
336 for (int i = length; i > 0; --i, ++in) {
337 if (*in < '0' || *in > '~') {
338 ++length;
339 }
340 }
341 return length;
342}
343
Kenny Root07438c82012-11-02 15:41:02 -0700344static int encode_key(char* out, const android::String8& keyName) {
345 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
346 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800347 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700348 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800349 *out = '+' + (*in >> 6);
350 *++out = '0' + (*in & 0x3F);
351 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700352 } else {
353 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800354 }
355 }
356 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800357 return length;
358}
359
Kenny Root07438c82012-11-02 15:41:02 -0700360/*
361 * Converts from the "escaped" format on disk to actual name.
362 * This will be smaller than the input string.
363 *
364 * Characters that should combine with the next at the end will be truncated.
365 */
366static size_t decode_key_length(const char* in, size_t length) {
367 size_t outLength = 0;
368
369 for (const char* end = in + length; in < end; in++) {
370 /* This combines with the next character. */
371 if (*in < '0' || *in > '~') {
372 continue;
373 }
374
375 outLength++;
376 }
377 return outLength;
378}
379
380static void decode_key(char* out, const char* in, size_t length) {
381 for (const char* end = in + length; in < end; in++) {
382 if (*in < '0' || *in > '~') {
383 /* Truncate combining characters at the end. */
384 if (in + 1 >= end) {
385 break;
386 }
387
388 *out = (*in++ - '+') << 6;
389 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800390 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700391 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800392 }
393 }
394 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800395}
396
397static size_t readFully(int fd, uint8_t* data, size_t size) {
398 size_t remaining = size;
399 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800400 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800401 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800402 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800403 }
404 data += n;
405 remaining -= n;
406 }
407 return size;
408}
409
410static size_t writeFully(int fd, uint8_t* data, size_t size) {
411 size_t remaining = size;
412 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800413 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
414 if (n < 0) {
415 ALOGW("write failed: %s", strerror(errno));
416 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800417 }
418 data += n;
419 remaining -= n;
420 }
421 return size;
422}
423
424class Entropy {
425public:
426 Entropy() : mRandom(-1) {}
427 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800428 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800429 close(mRandom);
430 }
431 }
432
433 bool open() {
434 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800435 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
436 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800437 ALOGE("open: %s: %s", randomDevice, strerror(errno));
438 return false;
439 }
440 return true;
441 }
442
Kenny Root51878182012-03-13 12:53:19 -0700443 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800444 return (readFully(mRandom, data, size) == size);
445 }
446
447private:
448 int mRandom;
449};
450
451/* Here is the file format. There are two parts in blob.value, the secret and
452 * the description. The secret is stored in ciphertext, and its original size
453 * can be found in blob.length. The description is stored after the secret in
454 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700455 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700456 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800457 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
458 * and decryptBlob(). Thus they should not be accessed from outside. */
459
Kenny Root822c3a92012-03-23 16:34:39 -0700460/* ** Note to future implementors of encryption: **
461 * Currently this is the construction:
462 * metadata || Enc(MD5(data) || data)
463 *
464 * This should be the construction used for encrypting if re-implementing:
465 *
466 * Derive independent keys for encryption and MAC:
467 * Kenc = AES_encrypt(masterKey, "Encrypt")
468 * Kmac = AES_encrypt(masterKey, "MAC")
469 *
470 * Store this:
471 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
472 * HMAC(Kmac, metadata || Enc(data))
473 */
Kenny Roota91203b2012-02-15 15:00:46 -0800474struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700475 uint8_t version;
476 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700477 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800478 uint8_t info;
479 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700480 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800481 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700482 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800483 int32_t length; // in network byte order when encrypted
484 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
485};
486
Kenny Root822c3a92012-03-23 16:34:39 -0700487typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700488 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700489 TYPE_GENERIC = 1,
490 TYPE_MASTER_KEY = 2,
491 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800492 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700493} BlobType;
494
Kenny Rootf9119d62013-04-03 09:22:15 -0700495static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700496
Kenny Roota91203b2012-02-15 15:00:46 -0800497class Blob {
498public:
Kenny Root07438c82012-11-02 15:41:02 -0700499 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
500 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800501 mBlob.length = valueLength;
502 memcpy(mBlob.value, value, valueLength);
503
504 mBlob.info = infoLength;
505 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700506
Kenny Root07438c82012-11-02 15:41:02 -0700507 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700508 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700509
Kenny Rootee8068b2013-10-07 09:49:15 -0700510 if (type == TYPE_MASTER_KEY) {
511 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
512 } else {
513 mBlob.flags = KEYSTORE_FLAG_NONE;
514 }
Kenny Roota91203b2012-02-15 15:00:46 -0800515 }
516
517 Blob(blob b) {
518 mBlob = b;
519 }
520
521 Blob() {}
522
Kenny Root51878182012-03-13 12:53:19 -0700523 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800524 return mBlob.value;
525 }
526
Kenny Root51878182012-03-13 12:53:19 -0700527 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800528 return mBlob.length;
529 }
530
Kenny Root51878182012-03-13 12:53:19 -0700531 const uint8_t* getInfo() const {
532 return mBlob.value + mBlob.length;
533 }
534
535 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800536 return mBlob.info;
537 }
538
Kenny Root822c3a92012-03-23 16:34:39 -0700539 uint8_t getVersion() const {
540 return mBlob.version;
541 }
542
Kenny Rootf9119d62013-04-03 09:22:15 -0700543 bool isEncrypted() const {
544 if (mBlob.version < 2) {
545 return true;
546 }
547
548 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
549 }
550
551 void setEncrypted(bool encrypted) {
552 if (encrypted) {
553 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
554 } else {
555 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
556 }
557 }
558
Kenny Root17208e02013-09-04 13:56:03 -0700559 bool isFallback() const {
560 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
561 }
562
563 void setFallback(bool fallback) {
564 if (fallback) {
565 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
566 } else {
567 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
568 }
569 }
570
Kenny Root822c3a92012-03-23 16:34:39 -0700571 void setVersion(uint8_t version) {
572 mBlob.version = version;
573 }
574
575 BlobType getType() const {
576 return BlobType(mBlob.type);
577 }
578
579 void setType(BlobType type) {
580 mBlob.type = uint8_t(type);
581 }
582
Kenny Rootf9119d62013-04-03 09:22:15 -0700583 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
584 ALOGV("writing blob %s", filename);
585 if (isEncrypted()) {
586 if (state != STATE_NO_ERROR) {
587 ALOGD("couldn't insert encrypted blob while not unlocked");
588 return LOCKED;
589 }
590
591 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
592 ALOGW("Could not read random data for: %s", filename);
593 return SYSTEM_ERROR;
594 }
Kenny Roota91203b2012-02-15 15:00:46 -0800595 }
596
597 // data includes the value and the value's length
598 size_t dataLength = mBlob.length + sizeof(mBlob.length);
599 // pad data to the AES_BLOCK_SIZE
600 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
601 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
602 // encrypted data includes the digest value
603 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
604 // move info after space for padding
605 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
606 // zero padding area
607 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
608
609 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800610
Kenny Rootf9119d62013-04-03 09:22:15 -0700611 if (isEncrypted()) {
612 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800613
Kenny Rootf9119d62013-04-03 09:22:15 -0700614 uint8_t vector[AES_BLOCK_SIZE];
615 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
616 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
617 aes_key, vector, AES_ENCRYPT);
618 }
619
Kenny Roota91203b2012-02-15 15:00:46 -0800620 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
621 size_t fileLength = encryptedLength + headerLength + mBlob.info;
622
623 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800624 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
625 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
626 if (out < 0) {
627 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800628 return SYSTEM_ERROR;
629 }
630 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
631 if (close(out) != 0) {
632 return SYSTEM_ERROR;
633 }
634 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800635 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800636 unlink(tmpFileName);
637 return SYSTEM_ERROR;
638 }
Kenny Root150ca932012-11-14 14:29:02 -0800639 if (rename(tmpFileName, filename) == -1) {
640 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
641 return SYSTEM_ERROR;
642 }
643 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800644 }
645
Kenny Rootf9119d62013-04-03 09:22:15 -0700646 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
647 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800648 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
649 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800650 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
651 }
652 // fileLength may be less than sizeof(mBlob) since the in
653 // memory version has extra padding to tolerate rounding up to
654 // the AES_BLOCK_SIZE
655 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
656 if (close(in) != 0) {
657 return SYSTEM_ERROR;
658 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700659
660 if (isEncrypted() && (state != STATE_NO_ERROR)) {
661 return LOCKED;
662 }
663
Kenny Roota91203b2012-02-15 15:00:46 -0800664 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
665 if (fileLength < headerLength) {
666 return VALUE_CORRUPTED;
667 }
668
669 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700670 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800671 return VALUE_CORRUPTED;
672 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700673
674 ssize_t digestedLength;
675 if (isEncrypted()) {
676 if (encryptedLength % AES_BLOCK_SIZE != 0) {
677 return VALUE_CORRUPTED;
678 }
679
680 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
681 mBlob.vector, AES_DECRYPT);
682 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
683 uint8_t computedDigest[MD5_DIGEST_LENGTH];
684 MD5(mBlob.digested, digestedLength, computedDigest);
685 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
686 return VALUE_CORRUPTED;
687 }
688 } else {
689 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800690 }
691
692 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
693 mBlob.length = ntohl(mBlob.length);
694 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
695 return VALUE_CORRUPTED;
696 }
697 if (mBlob.info != 0) {
698 // move info from after padding to after data
699 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
700 }
Kenny Root07438c82012-11-02 15:41:02 -0700701 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800702 }
703
704private:
705 struct blob mBlob;
706};
707
Kenny Root655b9582013-04-04 08:37:42 -0700708class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800709public:
Kenny Root655b9582013-04-04 08:37:42 -0700710 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
711 asprintf(&mUserDir, "user_%u", mUserId);
712 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
713 }
714
715 ~UserState() {
716 free(mUserDir);
717 free(mMasterKeyFile);
718 }
719
720 bool initialize() {
721 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
722 ALOGE("Could not create directory '%s'", mUserDir);
723 return false;
724 }
725
726 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800727 setState(STATE_LOCKED);
728 } else {
729 setState(STATE_UNINITIALIZED);
730 }
Kenny Root70e3a862012-02-15 17:20:23 -0800731
Kenny Root655b9582013-04-04 08:37:42 -0700732 return true;
733 }
734
735 uid_t getUserId() const {
736 return mUserId;
737 }
738
739 const char* getUserDirName() const {
740 return mUserDir;
741 }
742
743 const char* getMasterKeyFileName() const {
744 return mMasterKeyFile;
745 }
746
747 void setState(State state) {
748 mState = state;
749 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
750 mRetry = MAX_RETRY;
751 }
Kenny Roota91203b2012-02-15 15:00:46 -0800752 }
753
Kenny Root51878182012-03-13 12:53:19 -0700754 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800755 return mState;
756 }
757
Kenny Root51878182012-03-13 12:53:19 -0700758 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800759 return mRetry;
760 }
761
Kenny Root655b9582013-04-04 08:37:42 -0700762 void zeroizeMasterKeysInMemory() {
763 memset(mMasterKey, 0, sizeof(mMasterKey));
764 memset(mSalt, 0, sizeof(mSalt));
765 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
766 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800767 }
768
Kenny Root655b9582013-04-04 08:37:42 -0700769 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
770 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800771 return SYSTEM_ERROR;
772 }
Kenny Root655b9582013-04-04 08:37:42 -0700773 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800774 if (response != NO_ERROR) {
775 return response;
776 }
777 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700778 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800779 }
780
Robin Lee4e865752014-08-19 17:37:55 +0100781 ResponseCode copyMasterKey(UserState* src) {
782 if (mState != STATE_UNINITIALIZED) {
783 return ::SYSTEM_ERROR;
784 }
785 if (src->getState() != STATE_NO_ERROR) {
786 return ::SYSTEM_ERROR;
787 }
788 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
789 setupMasterKeys();
790 return ::NO_ERROR;
791 }
792
Kenny Root655b9582013-04-04 08:37:42 -0700793 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800794 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
795 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
796 AES_KEY passwordAesKey;
797 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700798 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700799 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800800 }
801
Kenny Root655b9582013-04-04 08:37:42 -0700802 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
803 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800804 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800805 return SYSTEM_ERROR;
806 }
807
808 // we read the raw blob to just to get the salt to generate
809 // the AES key, then we create the Blob to use with decryptBlob
810 blob rawBlob;
811 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
812 if (close(in) != 0) {
813 return SYSTEM_ERROR;
814 }
815 // find salt at EOF if present, otherwise we have an old file
816 uint8_t* salt;
817 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
818 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
819 } else {
820 salt = NULL;
821 }
822 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
823 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
824 AES_KEY passwordAesKey;
825 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
826 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700827 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
828 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800829 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700830 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800831 }
832 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
833 // if salt was missing, generate one and write a new master key file with the salt.
834 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700835 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800836 return SYSTEM_ERROR;
837 }
Kenny Root655b9582013-04-04 08:37:42 -0700838 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800839 }
840 if (response == NO_ERROR) {
841 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
842 setupMasterKeys();
843 }
844 return response;
845 }
846 if (mRetry <= 0) {
847 reset();
848 return UNINITIALIZED;
849 }
850 --mRetry;
851 switch (mRetry) {
852 case 0: return WRONG_PASSWORD_0;
853 case 1: return WRONG_PASSWORD_1;
854 case 2: return WRONG_PASSWORD_2;
855 case 3: return WRONG_PASSWORD_3;
856 default: return WRONG_PASSWORD_3;
857 }
858 }
859
Kenny Root655b9582013-04-04 08:37:42 -0700860 AES_KEY* getEncryptionKey() {
861 return &mMasterKeyEncryption;
862 }
863
864 AES_KEY* getDecryptionKey() {
865 return &mMasterKeyDecryption;
866 }
867
Kenny Roota91203b2012-02-15 15:00:46 -0800868 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700869 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800870 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700871 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800872 return false;
873 }
Kenny Root655b9582013-04-04 08:37:42 -0700874
875 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800876 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700877 // We only care about files.
878 if (file->d_type != DT_REG) {
879 continue;
880 }
881
882 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700883 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700884 continue;
885 }
886
887 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800888 }
889 closedir(dir);
890 return true;
891 }
892
Kenny Root655b9582013-04-04 08:37:42 -0700893private:
894 static const int MASTER_KEY_SIZE_BYTES = 16;
895 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
896
897 static const int MAX_RETRY = 4;
898 static const size_t SALT_SIZE = 16;
899
900 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
901 uint8_t* salt) {
902 size_t saltSize;
903 if (salt != NULL) {
904 saltSize = SALT_SIZE;
905 } else {
906 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
907 salt = (uint8_t*) "keystore";
908 // sizeof = 9, not strlen = 8
909 saltSize = sizeof("keystore");
910 }
911
912 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
913 saltSize, 8192, keySize, key);
914 }
915
916 bool generateSalt(Entropy* entropy) {
917 return entropy->generate_random_data(mSalt, sizeof(mSalt));
918 }
919
920 bool generateMasterKey(Entropy* entropy) {
921 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
922 return false;
923 }
924 if (!generateSalt(entropy)) {
925 return false;
926 }
927 return true;
928 }
929
930 void setupMasterKeys() {
931 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
932 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
933 setState(STATE_NO_ERROR);
934 }
935
936 uid_t mUserId;
937
938 char* mUserDir;
939 char* mMasterKeyFile;
940
941 State mState;
942 int8_t mRetry;
943
944 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
945 uint8_t mSalt[SALT_SIZE];
946
947 AES_KEY mMasterKeyEncryption;
948 AES_KEY mMasterKeyDecryption;
949};
950
951typedef struct {
952 uint32_t uid;
953 const uint8_t* filename;
954} grant_t;
955
956class KeyStore {
957public:
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800958 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700959 : mEntropy(entropy)
960 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800961 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700962 {
963 memset(&mMetaData, '\0', sizeof(mMetaData));
964 }
965
966 ~KeyStore() {
967 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
968 it != mGrants.end(); it++) {
969 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700970 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800971 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700972
973 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
974 it != mMasterKeys.end(); it++) {
975 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700976 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800977 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700978 }
979
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800980 /**
981 * Depending on the hardware keymaster version is this may return a
982 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
983 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
984 * be guarded by a check on the device's version.
985 */
986 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700987 return mDevice;
988 }
989
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800990 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800991 return mFallbackDevice;
992 }
993
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800994 keymaster1_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 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001177 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1178 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1179 if (dev->delete_key) {
1180 keymaster_key_blob_t blob;
1181 blob.key_material = keyBlob.getValue();
1182 blob.key_material_size = keyBlob.getLength();
1183 dev->delete_key(dev, &blob);
1184 }
1185 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001186 if (rc != ::NO_ERROR) {
1187 return rc;
1188 }
1189
1190 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1191 }
1192
1193 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1194 uid_t uid) {
1195
1196 UserState* userState = getUserState(uid);
1197 size_t n = prefix.length();
1198
1199 DIR* dir = opendir(userState->getUserDirName());
1200 if (!dir) {
1201 ALOGW("can't open directory for user: %s", strerror(errno));
1202 return ::SYSTEM_ERROR;
1203 }
1204
1205 struct dirent* file;
1206 while ((file = readdir(dir)) != NULL) {
1207 // We only care about files.
1208 if (file->d_type != DT_REG) {
1209 continue;
1210 }
1211
1212 // Skip anything that starts with a "."
1213 if (file->d_name[0] == '.') {
1214 continue;
1215 }
1216
1217 if (!strncmp(prefix.string(), file->d_name, n)) {
1218 const char* p = &file->d_name[n];
1219 size_t plen = strlen(p);
1220
1221 size_t extra = decode_key_length(p, plen);
1222 char *match = (char*) malloc(extra + 1);
1223 if (match != NULL) {
1224 decode_key(match, p, plen);
1225 matches->push(android::String16(match, extra));
1226 free(match);
1227 } else {
1228 ALOGW("could not allocate match of size %zd", extra);
1229 }
1230 }
1231 }
1232 closedir(dir);
1233 return ::NO_ERROR;
1234 }
1235
Kenny Root07438c82012-11-02 15:41:02 -07001236 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001237 const grant_t* existing = getGrant(filename, granteeUid);
1238 if (existing == NULL) {
1239 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001240 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001241 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001242 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001243 }
1244 }
1245
Kenny Root07438c82012-11-02 15:41:02 -07001246 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001247 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1248 it != mGrants.end(); it++) {
1249 grant_t* grant = *it;
1250 if (grant->uid == granteeUid
1251 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1252 mGrants.erase(it);
1253 return true;
1254 }
Kenny Root70e3a862012-02-15 17:20:23 -08001255 }
Kenny Root70e3a862012-02-15 17:20:23 -08001256 return false;
1257 }
1258
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001259 bool hasGrant(const char* filename, const uid_t uid) const {
1260 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001261 }
1262
Kenny Rootf9119d62013-04-03 09:22:15 -07001263 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1264 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001265 uint8_t* data;
1266 size_t dataLength;
1267 int rc;
1268
1269 if (mDevice->import_keypair == NULL) {
1270 ALOGE("Keymaster doesn't support import!");
1271 return SYSTEM_ERROR;
1272 }
1273
Kenny Root17208e02013-09-04 13:56:03 -07001274 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001275 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001276 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001277 /*
1278 * Maybe the device doesn't support this type of key. Try to use the
1279 * software fallback keymaster implementation. This is a little bit
1280 * lazier than checking the PKCS#8 key type, but the software
1281 * implementation will do that anyway.
1282 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001283 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001284 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001285
1286 if (rc) {
1287 ALOGE("Error while importing keypair: %d", rc);
1288 return SYSTEM_ERROR;
1289 }
Kenny Root822c3a92012-03-23 16:34:39 -07001290 }
1291
1292 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1293 free(data);
1294
Kenny Rootf9119d62013-04-03 09:22:15 -07001295 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001296 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001297
Kenny Root655b9582013-04-04 08:37:42 -07001298 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001299 }
1300
Kenny Root1b0e3932013-09-05 13:06:32 -07001301 bool isHardwareBacked(const android::String16& keyType) const {
1302 if (mDevice == NULL) {
1303 ALOGW("can't get keymaster device");
1304 return false;
1305 }
1306
1307 if (sRSAKeyType == keyType) {
1308 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1309 } else {
1310 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1311 && (mDevice->common.module->module_api_version
1312 >= KEYMASTER_MODULE_API_VERSION_0_2);
1313 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001314 }
1315
Kenny Root655b9582013-04-04 08:37:42 -07001316 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1317 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001318 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001319
1320 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1321 if (responseCode == NO_ERROR) {
1322 return responseCode;
1323 }
1324
1325 // If this is one of the legacy UID->UID mappings, use it.
1326 uid_t euid = get_keystore_euid(uid);
1327 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001328 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001329 responseCode = get(filepath8.string(), keyBlob, type, uid);
1330 if (responseCode == NO_ERROR) {
1331 return responseCode;
1332 }
1333 }
1334
1335 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001336 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001337 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001338 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001339 if (end[0] != '_' || end[1] == 0) {
1340 return KEY_NOT_FOUND;
1341 }
Kenny Root86b16e82013-09-09 11:15:54 -07001342 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1343 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001344 if (!hasGrant(filepath8.string(), uid)) {
1345 return responseCode;
1346 }
1347
1348 // It is a granted key. Try to load it.
1349 return get(filepath8.string(), keyBlob, type, uid);
1350 }
1351
1352 /**
1353 * Returns any existing UserState or creates it if it doesn't exist.
1354 */
1355 UserState* getUserState(uid_t uid) {
1356 uid_t userId = get_user_id(uid);
1357
1358 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1359 it != mMasterKeys.end(); it++) {
1360 UserState* state = *it;
1361 if (state->getUserId() == userId) {
1362 return state;
1363 }
1364 }
1365
1366 UserState* userState = new UserState(userId);
1367 if (!userState->initialize()) {
1368 /* There's not much we can do if initialization fails. Trying to
1369 * unlock the keystore for that user will fail as well, so any
1370 * subsequent request for this user will just return SYSTEM_ERROR.
1371 */
1372 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1373 }
1374 mMasterKeys.add(userState);
1375 return userState;
1376 }
1377
1378 /**
1379 * Returns NULL if the UserState doesn't already exist.
1380 */
1381 const UserState* getUserState(uid_t uid) const {
1382 uid_t userId = get_user_id(uid);
1383
1384 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1385 it != mMasterKeys.end(); it++) {
1386 UserState* state = *it;
1387 if (state->getUserId() == userId) {
1388 return state;
1389 }
1390 }
1391
1392 return NULL;
1393 }
1394
Kenny Roota91203b2012-02-15 15:00:46 -08001395private:
Kenny Root655b9582013-04-04 08:37:42 -07001396 static const char* sOldMasterKey;
1397 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001398 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001399 Entropy* mEntropy;
1400
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001401 keymaster1_device_t* mDevice;
1402 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001403
Kenny Root655b9582013-04-04 08:37:42 -07001404 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001405
Kenny Root655b9582013-04-04 08:37:42 -07001406 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001407
Kenny Root655b9582013-04-04 08:37:42 -07001408 typedef struct {
1409 uint32_t version;
1410 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001411
Kenny Root655b9582013-04-04 08:37:42 -07001412 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001413
Kenny Root655b9582013-04-04 08:37:42 -07001414 const grant_t* getGrant(const char* filename, uid_t uid) const {
1415 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1416 it != mGrants.end(); it++) {
1417 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001418 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001419 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001420 return grant;
1421 }
1422 }
Kenny Root70e3a862012-02-15 17:20:23 -08001423 return NULL;
1424 }
1425
Kenny Root822c3a92012-03-23 16:34:39 -07001426 /**
1427 * Upgrade code. This will upgrade the key from the current version
1428 * to whatever is newest.
1429 */
Kenny Root655b9582013-04-04 08:37:42 -07001430 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1431 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001432 bool updated = false;
1433 uint8_t version = oldVersion;
1434
1435 /* From V0 -> V1: All old types were unknown */
1436 if (version == 0) {
1437 ALOGV("upgrading to version 1 and setting type %d", type);
1438
1439 blob->setType(type);
1440 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001441 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001442 }
1443 version = 1;
1444 updated = true;
1445 }
1446
Kenny Rootf9119d62013-04-03 09:22:15 -07001447 /* From V1 -> V2: All old keys were encrypted */
1448 if (version == 1) {
1449 ALOGV("upgrading to version 2");
1450
1451 blob->setEncrypted(true);
1452 version = 2;
1453 updated = true;
1454 }
1455
Kenny Root822c3a92012-03-23 16:34:39 -07001456 /*
1457 * If we've updated, set the key blob to the right version
1458 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001459 */
Kenny Root822c3a92012-03-23 16:34:39 -07001460 if (updated) {
1461 ALOGV("updated and writing file %s", filename);
1462 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001463 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001464
1465 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001466 }
1467
1468 /**
1469 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1470 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1471 * Then it overwrites the original blob with the new blob
1472 * format that is returned from the keymaster.
1473 */
Kenny Root655b9582013-04-04 08:37:42 -07001474 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001475 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1476 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1477 if (b.get() == NULL) {
1478 ALOGE("Problem instantiating BIO");
1479 return SYSTEM_ERROR;
1480 }
1481
1482 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1483 if (pkey.get() == NULL) {
1484 ALOGE("Couldn't read old PEM file");
1485 return SYSTEM_ERROR;
1486 }
1487
1488 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1489 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1490 if (len < 0) {
1491 ALOGE("Couldn't measure PKCS#8 length");
1492 return SYSTEM_ERROR;
1493 }
1494
Kenny Root70c98892013-02-07 09:10:36 -08001495 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1496 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001497 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1498 ALOGE("Couldn't convert to PKCS#8");
1499 return SYSTEM_ERROR;
1500 }
1501
Kenny Rootf9119d62013-04-03 09:22:15 -07001502 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1503 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001504 if (rc != NO_ERROR) {
1505 return rc;
1506 }
1507
Kenny Root655b9582013-04-04 08:37:42 -07001508 return get(filename, blob, TYPE_KEY_PAIR, uid);
1509 }
1510
1511 void readMetaData() {
1512 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1513 if (in < 0) {
1514 return;
1515 }
1516 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1517 if (fileLength != sizeof(mMetaData)) {
1518 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1519 sizeof(mMetaData));
1520 }
1521 close(in);
1522 }
1523
1524 void writeMetaData() {
1525 const char* tmpFileName = ".metadata.tmp";
1526 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1527 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1528 if (out < 0) {
1529 ALOGE("couldn't write metadata file: %s", strerror(errno));
1530 return;
1531 }
1532 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1533 if (fileLength != sizeof(mMetaData)) {
1534 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1535 sizeof(mMetaData));
1536 }
1537 close(out);
1538 rename(tmpFileName, sMetaDataFile);
1539 }
1540
1541 bool upgradeKeystore() {
1542 bool upgraded = false;
1543
1544 if (mMetaData.version == 0) {
1545 UserState* userState = getUserState(0);
1546
1547 // Initialize first so the directory is made.
1548 userState->initialize();
1549
1550 // Migrate the old .masterkey file to user 0.
1551 if (access(sOldMasterKey, R_OK) == 0) {
1552 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1553 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1554 return false;
1555 }
1556 }
1557
1558 // Initialize again in case we had a key.
1559 userState->initialize();
1560
1561 // Try to migrate existing keys.
1562 DIR* dir = opendir(".");
1563 if (!dir) {
1564 // Give up now; maybe we can upgrade later.
1565 ALOGE("couldn't open keystore's directory; something is wrong");
1566 return false;
1567 }
1568
1569 struct dirent* file;
1570 while ((file = readdir(dir)) != NULL) {
1571 // We only care about files.
1572 if (file->d_type != DT_REG) {
1573 continue;
1574 }
1575
1576 // Skip anything that starts with a "."
1577 if (file->d_name[0] == '.') {
1578 continue;
1579 }
1580
1581 // Find the current file's user.
1582 char* end;
1583 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1584 if (end[0] != '_' || end[1] == 0) {
1585 continue;
1586 }
1587 UserState* otherUser = getUserState(thisUid);
1588 if (otherUser->getUserId() != 0) {
1589 unlinkat(dirfd(dir), file->d_name, 0);
1590 }
1591
1592 // Rename the file into user directory.
1593 DIR* otherdir = opendir(otherUser->getUserDirName());
1594 if (otherdir == NULL) {
1595 ALOGW("couldn't open user directory for rename");
1596 continue;
1597 }
1598 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1599 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1600 }
1601 closedir(otherdir);
1602 }
1603 closedir(dir);
1604
1605 mMetaData.version = 1;
1606 upgraded = true;
1607 }
1608
1609 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001610 }
Kenny Roota91203b2012-02-15 15:00:46 -08001611};
1612
Kenny Root655b9582013-04-04 08:37:42 -07001613const char* KeyStore::sOldMasterKey = ".masterkey";
1614const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001615
Kenny Root1b0e3932013-09-05 13:06:32 -07001616const android::String16 KeyStore::sRSAKeyType("RSA");
1617
Kenny Root07438c82012-11-02 15:41:02 -07001618namespace android {
1619class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1620public:
1621 KeyStoreProxy(KeyStore* keyStore)
1622 : mKeyStore(keyStore)
1623 {
Kenny Roota91203b2012-02-15 15:00:46 -08001624 }
Kenny Roota91203b2012-02-15 15:00:46 -08001625
Kenny Root07438c82012-11-02 15:41:02 -07001626 void binderDied(const wp<IBinder>&) {
1627 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001628 }
Kenny Roota91203b2012-02-15 15:00:46 -08001629
Kenny Root07438c82012-11-02 15:41:02 -07001630 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001631 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001632 pid_t spid = IPCThreadState::self()->getCallingPid();
1633 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001634 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001635 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001636 }
Kenny Roota91203b2012-02-15 15:00:46 -08001637
Kenny Root655b9582013-04-04 08:37:42 -07001638 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001639 }
1640
Kenny Root07438c82012-11-02 15:41:02 -07001641 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001642 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001643 pid_t spid = IPCThreadState::self()->getCallingPid();
1644 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001645 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001646 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001647 }
Kenny Root07438c82012-11-02 15:41:02 -07001648
Kenny Root07438c82012-11-02 15:41:02 -07001649 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001650 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001651
Kenny Root655b9582013-04-04 08:37:42 -07001652 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001653 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001654 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001655 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001656 *item = NULL;
1657 *itemLength = 0;
1658 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001659 }
Kenny Roota91203b2012-02-15 15:00:46 -08001660
Kenny Root07438c82012-11-02 15:41:02 -07001661 *item = (uint8_t*) malloc(keyBlob.getLength());
1662 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1663 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001664
Kenny Root07438c82012-11-02 15:41:02 -07001665 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001666 }
1667
Kenny Rootf9119d62013-04-03 09:22:15 -07001668 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1669 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001670 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001671 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001672 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001673 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001674 return ::PERMISSION_DENIED;
1675 }
Kenny Root07438c82012-11-02 15:41:02 -07001676
Kenny Rootf9119d62013-04-03 09:22:15 -07001677 State state = mKeyStore->getState(callingUid);
1678 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1679 ALOGD("calling get in state: %d", state);
1680 return state;
1681 }
1682
Kenny Root49468902013-03-19 13:41:33 -07001683 if (targetUid == -1) {
1684 targetUid = callingUid;
1685 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001686 return ::PERMISSION_DENIED;
1687 }
1688
Kenny Root07438c82012-11-02 15:41:02 -07001689 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001690 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001691
1692 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001693 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1694
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001695 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001696 }
1697
Kenny Root49468902013-03-19 13:41:33 -07001698 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001699 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001700 pid_t spid = IPCThreadState::self()->getCallingPid();
1701 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001702 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001703 return ::PERMISSION_DENIED;
1704 }
Kenny Root70e3a862012-02-15 17:20:23 -08001705
Kenny Root49468902013-03-19 13:41:33 -07001706 if (targetUid == -1) {
1707 targetUid = callingUid;
1708 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001709 return ::PERMISSION_DENIED;
1710 }
1711
Kenny Root07438c82012-11-02 15:41:02 -07001712 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001713 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker17d68b92015-02-05 22:04:16 -08001714 return mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001715 }
1716
Kenny Root49468902013-03-19 13:41:33 -07001717 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001718 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001719 pid_t spid = IPCThreadState::self()->getCallingPid();
1720 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001721 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001722 return ::PERMISSION_DENIED;
1723 }
Kenny Root70e3a862012-02-15 17:20:23 -08001724
Kenny Root49468902013-03-19 13:41:33 -07001725 if (targetUid == -1) {
1726 targetUid = callingUid;
1727 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001728 return ::PERMISSION_DENIED;
1729 }
1730
Kenny Root07438c82012-11-02 15:41:02 -07001731 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001732 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001733
Kenny Root655b9582013-04-04 08:37:42 -07001734 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001735 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1736 }
1737 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001738 }
1739
Kenny Root49468902013-03-19 13:41:33 -07001740 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001741 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001742 pid_t spid = IPCThreadState::self()->getCallingPid();
1743 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001744 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001745 return ::PERMISSION_DENIED;
1746 }
Kenny Root70e3a862012-02-15 17:20:23 -08001747
Kenny Root49468902013-03-19 13:41:33 -07001748 if (targetUid == -1) {
1749 targetUid = callingUid;
1750 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001751 return ::PERMISSION_DENIED;
1752 }
1753
Kenny Root07438c82012-11-02 15:41:02 -07001754 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001755 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001756
Robin Lee4b84fdc2014-09-24 11:56:57 +01001757 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1758 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001759 }
Kenny Root07438c82012-11-02 15:41:02 -07001760 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001761 }
1762
Kenny Root07438c82012-11-02 15:41:02 -07001763 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001764 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001765 pid_t spid = IPCThreadState::self()->getCallingPid();
1766 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001767 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001768 return ::PERMISSION_DENIED;
1769 }
1770
Robin Lee4b84fdc2014-09-24 11:56:57 +01001771 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001772 }
1773
Kenny Root07438c82012-11-02 15:41:02 -07001774 /*
1775 * Here is the history. To improve the security, the parameters to generate the
1776 * master key has been changed. To make a seamless transition, we update the
1777 * file using the same password when the user unlock it for the first time. If
1778 * any thing goes wrong during the transition, the new file will not overwrite
1779 * the old one. This avoids permanent damages of the existing data.
1780 */
1781 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001782 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001783 pid_t spid = IPCThreadState::self()->getCallingPid();
1784 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001785 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001786 return ::PERMISSION_DENIED;
1787 }
Kenny Root70e3a862012-02-15 17:20:23 -08001788
Kenny Root07438c82012-11-02 15:41:02 -07001789 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001790
Kenny Root655b9582013-04-04 08:37:42 -07001791 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001792 case ::STATE_UNINITIALIZED: {
1793 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001794 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001795 }
1796 case ::STATE_NO_ERROR: {
1797 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001798 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001799 }
1800 case ::STATE_LOCKED: {
1801 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001802 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001803 }
1804 }
1805 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001806 }
1807
Kenny Root07438c82012-11-02 15:41:02 -07001808 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001809 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001810 pid_t spid = IPCThreadState::self()->getCallingPid();
1811 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001812 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001813 return ::PERMISSION_DENIED;
1814 }
Kenny Root70e3a862012-02-15 17:20:23 -08001815
Kenny Root655b9582013-04-04 08:37:42 -07001816 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001817 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001818 ALOGD("calling lock in state: %d", state);
1819 return state;
1820 }
1821
Kenny Root655b9582013-04-04 08:37:42 -07001822 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001823 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001824 }
1825
Kenny Root07438c82012-11-02 15:41:02 -07001826 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001827 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001828 pid_t spid = IPCThreadState::self()->getCallingPid();
1829 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001830 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001831 return ::PERMISSION_DENIED;
1832 }
1833
Kenny Root655b9582013-04-04 08:37:42 -07001834 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001835 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001836 ALOGD("calling unlock when not locked");
1837 return state;
1838 }
1839
1840 const String8 password8(pw);
1841 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001842 }
1843
Kenny Root07438c82012-11-02 15:41:02 -07001844 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001845 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001846 pid_t spid = IPCThreadState::self()->getCallingPid();
1847 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001848 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001849 return -1;
1850 }
Kenny Root70e3a862012-02-15 17:20:23 -08001851
Kenny Root655b9582013-04-04 08:37:42 -07001852 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001853 }
1854
Kenny Root96427ba2013-08-16 14:02:41 -07001855 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1856 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001857 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001858 pid_t spid = IPCThreadState::self()->getCallingPid();
1859 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001860 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001861 return ::PERMISSION_DENIED;
1862 }
Kenny Root70e3a862012-02-15 17:20:23 -08001863
Kenny Root49468902013-03-19 13:41:33 -07001864 if (targetUid == -1) {
1865 targetUid = callingUid;
1866 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001867 return ::PERMISSION_DENIED;
1868 }
1869
Kenny Root655b9582013-04-04 08:37:42 -07001870 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001871 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1872 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001873 return state;
1874 }
Kenny Root70e3a862012-02-15 17:20:23 -08001875
Kenny Root07438c82012-11-02 15:41:02 -07001876 uint8_t* data;
1877 size_t dataLength;
1878 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001879 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001880
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001881 const keymaster1_device_t* device = mKeyStore->getDevice();
1882 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001883 if (device == NULL) {
1884 return ::SYSTEM_ERROR;
1885 }
1886
1887 if (device->generate_keypair == NULL) {
1888 return ::SYSTEM_ERROR;
1889 }
1890
Kenny Root17208e02013-09-04 13:56:03 -07001891 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001892 keymaster_dsa_keygen_params_t dsa_params;
1893 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001894
Kenny Root96427ba2013-08-16 14:02:41 -07001895 if (keySize == -1) {
1896 keySize = DSA_DEFAULT_KEY_SIZE;
1897 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1898 || keySize > DSA_MAX_KEY_SIZE) {
1899 ALOGI("invalid key size %d", keySize);
1900 return ::SYSTEM_ERROR;
1901 }
1902 dsa_params.key_size = keySize;
1903
1904 if (args->size() == 3) {
1905 sp<KeystoreArg> gArg = args->itemAt(0);
1906 sp<KeystoreArg> pArg = args->itemAt(1);
1907 sp<KeystoreArg> qArg = args->itemAt(2);
1908
1909 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1910 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1911 dsa_params.generator_len = gArg->size();
1912
1913 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1914 dsa_params.prime_p_len = pArg->size();
1915
1916 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1917 dsa_params.prime_q_len = qArg->size();
1918 } else {
1919 ALOGI("not all DSA parameters were read");
1920 return ::SYSTEM_ERROR;
1921 }
1922 } else if (args->size() != 0) {
1923 ALOGI("DSA args must be 3");
1924 return ::SYSTEM_ERROR;
1925 }
1926
Kenny Root1d448c02013-11-21 10:36:53 -08001927 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001928 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1929 } else {
1930 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001931 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1932 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001933 }
1934 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001935 keymaster_ec_keygen_params_t ec_params;
1936 memset(&ec_params, '\0', sizeof(ec_params));
1937
1938 if (keySize == -1) {
1939 keySize = EC_DEFAULT_KEY_SIZE;
1940 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1941 ALOGI("invalid key size %d", keySize);
1942 return ::SYSTEM_ERROR;
1943 }
1944 ec_params.field_size = keySize;
1945
Kenny Root1d448c02013-11-21 10:36:53 -08001946 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001947 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1948 } else {
1949 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001950 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001951 }
Kenny Root96427ba2013-08-16 14:02:41 -07001952 } else if (keyType == EVP_PKEY_RSA) {
1953 keymaster_rsa_keygen_params_t rsa_params;
1954 memset(&rsa_params, '\0', sizeof(rsa_params));
1955 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1956
1957 if (keySize == -1) {
1958 keySize = RSA_DEFAULT_KEY_SIZE;
1959 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1960 ALOGI("invalid key size %d", keySize);
1961 return ::SYSTEM_ERROR;
1962 }
1963 rsa_params.modulus_size = keySize;
1964
1965 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001966 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001967 return ::SYSTEM_ERROR;
1968 } else if (args->size() == 1) {
1969 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1970 if (pubExpBlob != NULL) {
1971 Unique_BIGNUM pubExpBn(
1972 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1973 pubExpBlob->size(), NULL));
1974 if (pubExpBn.get() == NULL) {
1975 ALOGI("Could not convert public exponent to BN");
1976 return ::SYSTEM_ERROR;
1977 }
1978 unsigned long pubExp = BN_get_word(pubExpBn.get());
1979 if (pubExp == 0xFFFFFFFFL) {
1980 ALOGI("cannot represent public exponent as a long value");
1981 return ::SYSTEM_ERROR;
1982 }
1983 rsa_params.public_exponent = pubExp;
1984 }
1985 }
1986
1987 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1988 } else {
1989 ALOGW("Unsupported key type %d", keyType);
1990 rc = -1;
1991 }
1992
Kenny Root07438c82012-11-02 15:41:02 -07001993 if (rc) {
1994 return ::SYSTEM_ERROR;
1995 }
1996
Kenny Root655b9582013-04-04 08:37:42 -07001997 String8 name8(name);
1998 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001999
2000 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
2001 free(data);
2002
Kenny Rootee8068b2013-10-07 09:49:15 -07002003 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07002004 keyBlob.setFallback(isFallback);
2005
Kenny Root655b9582013-04-04 08:37:42 -07002006 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08002007 }
2008
Kenny Rootf9119d62013-04-03 09:22:15 -07002009 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2010 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002011 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002012 pid_t spid = IPCThreadState::self()->getCallingPid();
2013 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002014 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002015 return ::PERMISSION_DENIED;
2016 }
Kenny Root07438c82012-11-02 15:41:02 -07002017
Kenny Root49468902013-03-19 13:41:33 -07002018 if (targetUid == -1) {
2019 targetUid = callingUid;
2020 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002021 return ::PERMISSION_DENIED;
2022 }
2023
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002024 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07002025 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002026 ALOGD("calling import in state: %d", state);
2027 return state;
2028 }
2029
2030 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002031 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002032
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002033 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002034 }
2035
Kenny Root07438c82012-11-02 15:41:02 -07002036 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2037 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002038 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002039 pid_t spid = IPCThreadState::self()->getCallingPid();
2040 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002041 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002042 return ::PERMISSION_DENIED;
2043 }
Kenny Root07438c82012-11-02 15:41:02 -07002044
Kenny Root07438c82012-11-02 15:41:02 -07002045 Blob keyBlob;
2046 String8 name8(name);
2047
Kenny Rootd38a0b02013-02-13 12:59:14 -08002048 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002049 int rc;
2050
Kenny Root655b9582013-04-04 08:37:42 -07002051 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002052 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002053 if (responseCode != ::NO_ERROR) {
2054 return responseCode;
2055 }
2056
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002057 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002058 if (device == NULL) {
2059 ALOGE("no keymaster device; cannot sign");
2060 return ::SYSTEM_ERROR;
2061 }
2062
2063 if (device->sign_data == NULL) {
2064 ALOGE("device doesn't implement signing");
2065 return ::SYSTEM_ERROR;
2066 }
2067
2068 keymaster_rsa_sign_params_t params;
2069 params.digest_type = DIGEST_NONE;
2070 params.padding_type = PADDING_NONE;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002071 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2072 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002073 if (rc) {
2074 ALOGW("device couldn't sign data");
2075 return ::SYSTEM_ERROR;
2076 }
2077
2078 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002079 }
2080
Kenny Root07438c82012-11-02 15:41:02 -07002081 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2082 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002083 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002084 pid_t spid = IPCThreadState::self()->getCallingPid();
2085 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002086 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002087 return ::PERMISSION_DENIED;
2088 }
Kenny Root70e3a862012-02-15 17:20:23 -08002089
Kenny Root655b9582013-04-04 08:37:42 -07002090 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002091 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002092 ALOGD("calling verify in state: %d", state);
2093 return state;
2094 }
Kenny Root70e3a862012-02-15 17:20:23 -08002095
Kenny Root07438c82012-11-02 15:41:02 -07002096 Blob keyBlob;
2097 String8 name8(name);
2098 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002099
Kenny Root655b9582013-04-04 08:37:42 -07002100 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002101 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002102 if (responseCode != ::NO_ERROR) {
2103 return responseCode;
2104 }
Kenny Root70e3a862012-02-15 17:20:23 -08002105
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002106 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002107 if (device == NULL) {
2108 return ::SYSTEM_ERROR;
2109 }
Kenny Root70e3a862012-02-15 17:20:23 -08002110
Kenny Root07438c82012-11-02 15:41:02 -07002111 if (device->verify_data == NULL) {
2112 return ::SYSTEM_ERROR;
2113 }
Kenny Root70e3a862012-02-15 17:20:23 -08002114
Kenny Root07438c82012-11-02 15:41:02 -07002115 keymaster_rsa_sign_params_t params;
2116 params.digest_type = DIGEST_NONE;
2117 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002118
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002119 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2120 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002121 if (rc) {
2122 return ::SYSTEM_ERROR;
2123 } else {
2124 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002125 }
2126 }
Kenny Root07438c82012-11-02 15:41:02 -07002127
2128 /*
2129 * TODO: The abstraction between things stored in hardware and regular blobs
2130 * of data stored on the filesystem should be moved down to keystore itself.
2131 * Unfortunately the Java code that calls this has naming conventions that it
2132 * knows about. Ideally keystore shouldn't be used to store random blobs of
2133 * data.
2134 *
2135 * Until that happens, it's necessary to have a separate "get_pubkey" and
2136 * "del_key" since the Java code doesn't really communicate what it's
2137 * intentions are.
2138 */
2139 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002140 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002141 pid_t spid = IPCThreadState::self()->getCallingPid();
2142 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002143 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002144 return ::PERMISSION_DENIED;
2145 }
Kenny Root07438c82012-11-02 15:41:02 -07002146
Kenny Root07438c82012-11-02 15:41:02 -07002147 Blob keyBlob;
2148 String8 name8(name);
2149
Kenny Rootd38a0b02013-02-13 12:59:14 -08002150 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002151
Kenny Root655b9582013-04-04 08:37:42 -07002152 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002153 TYPE_KEY_PAIR);
2154 if (responseCode != ::NO_ERROR) {
2155 return responseCode;
2156 }
2157
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002158 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002159 if (device == NULL) {
2160 return ::SYSTEM_ERROR;
2161 }
2162
2163 if (device->get_keypair_public == NULL) {
2164 ALOGE("device has no get_keypair_public implementation!");
2165 return ::SYSTEM_ERROR;
2166 }
2167
Kenny Root17208e02013-09-04 13:56:03 -07002168 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002169 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2170 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002171 if (rc) {
2172 return ::SYSTEM_ERROR;
2173 }
2174
2175 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002176 }
Kenny Root07438c82012-11-02 15:41:02 -07002177
Kenny Root49468902013-03-19 13:41:33 -07002178 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002179 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002180 pid_t spid = IPCThreadState::self()->getCallingPid();
2181 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002182 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002183 return ::PERMISSION_DENIED;
2184 }
Kenny Root07438c82012-11-02 15:41:02 -07002185
Kenny Root49468902013-03-19 13:41:33 -07002186 if (targetUid == -1) {
2187 targetUid = callingUid;
2188 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002189 return ::PERMISSION_DENIED;
2190 }
2191
Kenny Root07438c82012-11-02 15:41:02 -07002192 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002193 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01002194 return mKeyStore->del(filename.string(), ::TYPE_KEY_PAIR, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002195 }
2196
2197 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002198 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002199 pid_t spid = IPCThreadState::self()->getCallingPid();
2200 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002201 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002202 return ::PERMISSION_DENIED;
2203 }
Kenny Root07438c82012-11-02 15:41:02 -07002204
Kenny Root655b9582013-04-04 08:37:42 -07002205 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002206 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002207 ALOGD("calling grant in state: %d", state);
2208 return state;
2209 }
2210
2211 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002212 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002213
Kenny Root655b9582013-04-04 08:37:42 -07002214 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002215 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2216 }
2217
Kenny Root655b9582013-04-04 08:37:42 -07002218 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002219 return ::NO_ERROR;
2220 }
2221
2222 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002223 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002224 pid_t spid = IPCThreadState::self()->getCallingPid();
2225 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002226 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002227 return ::PERMISSION_DENIED;
2228 }
Kenny Root07438c82012-11-02 15:41:02 -07002229
Kenny Root655b9582013-04-04 08:37:42 -07002230 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002231 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002232 ALOGD("calling ungrant in state: %d", state);
2233 return state;
2234 }
2235
2236 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002237 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002238
Kenny Root655b9582013-04-04 08:37:42 -07002239 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002240 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2241 }
2242
Kenny Root655b9582013-04-04 08:37:42 -07002243 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002244 }
2245
2246 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002247 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002248 pid_t spid = IPCThreadState::self()->getCallingPid();
2249 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002250 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002251 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002252 }
Kenny Root07438c82012-11-02 15:41:02 -07002253
2254 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002255 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002256
Kenny Root655b9582013-04-04 08:37:42 -07002257 if (access(filename.string(), R_OK) == -1) {
2258 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002259 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002260 }
2261
Kenny Root655b9582013-04-04 08:37:42 -07002262 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002263 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002264 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002265 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002266 }
2267
2268 struct stat s;
2269 int ret = fstat(fd, &s);
2270 close(fd);
2271 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002272 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002273 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002274 }
2275
Kenny Root36a9e232013-02-04 14:24:15 -08002276 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002277 }
2278
Kenny Rootd53bc922013-03-21 14:10:15 -07002279 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2280 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002281 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002282 pid_t spid = IPCThreadState::self()->getCallingPid();
2283 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002284 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002285 return -1L;
2286 }
2287
Kenny Root655b9582013-04-04 08:37:42 -07002288 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002289 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002290 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002291 return state;
2292 }
2293
Kenny Rootd53bc922013-03-21 14:10:15 -07002294 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2295 srcUid = callingUid;
2296 } else if (!is_granted_to(callingUid, srcUid)) {
2297 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002298 return ::PERMISSION_DENIED;
2299 }
2300
Kenny Rootd53bc922013-03-21 14:10:15 -07002301 if (destUid == -1) {
2302 destUid = callingUid;
2303 }
2304
2305 if (srcUid != destUid) {
2306 if (static_cast<uid_t>(srcUid) != callingUid) {
2307 ALOGD("can only duplicate from caller to other or to same uid: "
2308 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2309 return ::PERMISSION_DENIED;
2310 }
2311
2312 if (!is_granted_to(callingUid, destUid)) {
2313 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2314 return ::PERMISSION_DENIED;
2315 }
2316 }
2317
2318 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002319 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002320
Kenny Rootd53bc922013-03-21 14:10:15 -07002321 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002322 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002323
Kenny Root655b9582013-04-04 08:37:42 -07002324 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2325 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002326 return ::SYSTEM_ERROR;
2327 }
2328
Kenny Rootd53bc922013-03-21 14:10:15 -07002329 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002330 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002331 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002332 if (responseCode != ::NO_ERROR) {
2333 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002334 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002335
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002336 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002337 }
2338
Kenny Root1b0e3932013-09-05 13:06:32 -07002339 int32_t is_hardware_backed(const String16& keyType) {
2340 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002341 }
2342
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002343 int32_t clear_uid(int64_t targetUid64) {
2344 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002345 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002346 pid_t spid = IPCThreadState::self()->getCallingPid();
2347 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002348 ALOGW("permission denied for %d: clear_uid", callingUid);
2349 return ::PERMISSION_DENIED;
2350 }
2351
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002352 if (targetUid64 == -1) {
2353 targetUid = callingUid;
Kenny Root007cb232014-07-30 16:59:42 -07002354 } else if (!is_self_or_system(callingUid, targetUid)) {
2355 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002356 return ::PERMISSION_DENIED;
2357 }
2358
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002359 const keymaster1_device_t* device = mKeyStore->getDevice();
Kenny Roota9bb5492013-04-01 16:29:11 -07002360 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002361 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002362 return ::SYSTEM_ERROR;
2363 }
2364
Robin Lee4b84fdc2014-09-24 11:56:57 +01002365 String8 prefix = String8::format("%u_", targetUid);
2366 Vector<String16> aliases;
2367 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002368 return ::SYSTEM_ERROR;
2369 }
2370
Robin Lee4b84fdc2014-09-24 11:56:57 +01002371 for (uint32_t i = 0; i < aliases.size(); i++) {
2372 String8 name8(aliases[i]);
2373 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2374 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002375 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002376 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002377 }
2378
Robin Lee4b84fdc2014-09-24 11:56:57 +01002379 int32_t reset_uid(int32_t targetUid) {
Robin Lee4e865752014-08-19 17:37:55 +01002380 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2381 pid_t spid = IPCThreadState::self()->getCallingPid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01002382
Robin Lee4e865752014-08-19 17:37:55 +01002383 if (!has_permission(callingUid, P_RESET_UID, spid)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01002384 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002385 return ::PERMISSION_DENIED;
2386 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002387 if (!is_self_or_system(callingUid, targetUid)) {
2388 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002389 return ::PERMISSION_DENIED;
2390 }
2391
Robin Lee4b84fdc2014-09-24 11:56:57 +01002392 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002393 }
2394
2395 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
2396 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2397 pid_t spid = IPCThreadState::self()->getCallingPid();
2398 if (!has_permission(callingUid, P_SYNC_UID, spid)) {
2399 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2400 return ::PERMISSION_DENIED;
2401 }
2402 if (callingUid != AID_SYSTEM) {
2403 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2404 return ::PERMISSION_DENIED;
2405 }
2406 if (sourceUid == targetUid) {
2407 return ::SYSTEM_ERROR;
2408 }
2409
2410 // Initialise user keystore with existing master key held in-memory
2411 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2412 }
2413
2414 int32_t password_uid(const String16& pw, int32_t targetUid) {
2415 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2416 pid_t spid = IPCThreadState::self()->getCallingPid();
2417 if (!has_permission(callingUid, P_PASSWORD_UID, spid)) {
2418 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2419 return ::PERMISSION_DENIED;
2420 }
2421 if (callingUid != AID_SYSTEM) {
2422 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2423 return ::PERMISSION_DENIED;
2424 }
2425
2426 const String8 password8(pw);
2427
2428 switch (mKeyStore->getState(targetUid)) {
2429 case ::STATE_UNINITIALIZED: {
2430 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2431 return mKeyStore->initializeUser(password8, targetUid);
2432 }
2433 case ::STATE_NO_ERROR: {
2434 // rewrite master key with new password.
2435 return mKeyStore->writeMasterKey(password8, targetUid);
2436 }
2437 case ::STATE_LOCKED: {
2438 // read master key, decrypt with password, initialize mMasterKey*.
2439 return mKeyStore->readMasterKey(password8, targetUid);
2440 }
2441 }
2442 return ::SYSTEM_ERROR;
2443 }
2444
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002445 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2446 const keymaster1_device_t* device = mKeyStore->getDevice();
2447 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2448 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2449 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2450 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2451 device->add_rng_entropy != NULL) {
2452 devResult = device->add_rng_entropy(device, data, dataLength);
2453 }
2454 if (fallback->add_rng_entropy) {
2455 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2456 }
2457 if (devResult) {
2458 return devResult;
2459 }
2460 if (fallbackResult) {
2461 return fallbackResult;
2462 }
2463 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002464 }
2465
Chad Brubaker17d68b92015-02-05 22:04:16 -08002466 int32_t generateKey(const String16& name, const KeymasterArguments& params,
2467 int uid, int flags, KeyCharacteristics* outCharacteristics) {
2468 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2469 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2470 if (!has_permission(callingUid, P_INSERT, callingPid)) {
2471 ALOGW("permission denied for %d: generateKey", callingUid);
2472 return ::PERMISSION_DENIED;
2473 }
2474
2475 State state = mKeyStore->getState(callingUid);
2476 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
2477 ALOGW("calling generate in state: %d", state);
2478 return state;
2479 }
2480
2481 if (uid == -1) {
2482 uid = callingUid;
2483 } else if (!is_granted_to(callingUid, uid)) {
2484 return ::PERMISSION_DENIED;
2485 }
2486
2487 uint8_t* data;
2488 size_t dataLength;
2489 int rc = KM_ERROR_UNIMPLEMENTED;
2490 bool isFallback = false;
2491 keymaster_key_blob_t blob;
2492 keymaster_key_characteristics_t *out = NULL;
2493
2494 const keymaster1_device_t* device = mKeyStore->getDevice();
2495 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2496 if (device == NULL) {
2497 return ::SYSTEM_ERROR;
2498 }
2499 // TODO: Seed from Linux RNG either before this or periodically
2500 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2501 device->generate_key != NULL) {
2502 rc = device->generate_key(device, params.params.data(), params.params.size(), &blob,
2503 &out);
2504 }
2505 // If the HW device didn't support generate_key or generate_key failed
2506 // fall back to the software implementation.
2507 if (rc && fallback->generate_key != NULL) {
2508 isFallback = true;
2509 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2510 &blob,
2511 &out);
2512 }
2513
2514 if (out) {
2515 if (outCharacteristics) {
2516 outCharacteristics->characteristics = *out;
2517 } else {
2518 keymaster_free_characteristics(out);
2519 }
2520 free(out);
2521 }
2522
2523 if (rc) {
2524 return rc;
2525 }
2526
2527 String8 name8(name);
2528 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2529
2530 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2531 keyBlob.setFallback(isFallback);
2532 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2533
2534 free(const_cast<uint8_t*>(blob.key_material));
2535
2536 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002537 }
2538
2539 int32_t getKeyCharacteristics(const String16& /*name*/,
2540 const keymaster_blob_t& /*clientId*/,
2541 const keymaster_blob_t& /*appData*/,
2542 KeyCharacteristics* /*outCharacteristics*/) {
2543 return KM_ERROR_UNIMPLEMENTED;
2544 }
2545
2546 int32_t importKey(const String16& /*name*/, const KeymasterArguments& /*params*/,
2547 keymaster_key_format_t /*format*/, const uint8_t* /*keyData*/,
2548 size_t /*keyLength*/, int /*uid*/, int /*flags*/,
2549 KeyCharacteristics* /*outCharacteristics*/) {
2550 return KM_ERROR_UNIMPLEMENTED;
2551 }
2552
2553 void exportKey(const String16& /*name*/, keymaster_key_format_t /*format*/,
2554 const keymaster_blob_t& /*clientId*/,
2555 const keymaster_blob_t& /*appData*/, ExportResult* result) {
2556 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2557 }
2558
2559 void begin(const sp<IBinder>& /*appToken*/, const String16& /*name*/,
2560 keymaster_purpose_t /*purpose*/, bool /*pruneable*/,
2561 const KeymasterArguments& /*params*/, KeymasterArguments* /*outParams*/,
2562 OperationResult* result) {
2563 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2564 }
2565
2566 void update(const sp<IBinder>& /*token*/, const KeymasterArguments& /*params*/,
2567 uint8_t* /*data*/, size_t /*dataLength*/, OperationResult* result) {
2568 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2569 }
2570
2571 void finish(const sp<IBinder>& /*token*/, const KeymasterArguments& /*args*/,
2572 uint8_t* /*signature*/, size_t /*signatureLength*/, OperationResult* result) {
2573 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2574 }
2575
2576 int32_t abort(const sp<IBinder>& /*token*/) {
2577 return KM_ERROR_UNIMPLEMENTED;
2578 }
2579
Kenny Root07438c82012-11-02 15:41:02 -07002580private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002581 inline bool isKeystoreUnlocked(State state) {
2582 switch (state) {
2583 case ::STATE_NO_ERROR:
2584 return true;
2585 case ::STATE_UNINITIALIZED:
2586 case ::STATE_LOCKED:
2587 return false;
2588 }
2589 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002590 }
2591
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002592 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002593 const int32_t device_api = device->common.module->module_api_version;
2594 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2595 switch (keyType) {
2596 case TYPE_RSA:
2597 case TYPE_DSA:
2598 case TYPE_EC:
2599 return true;
2600 default:
2601 return false;
2602 }
2603 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2604 switch (keyType) {
2605 case TYPE_RSA:
2606 return true;
2607 case TYPE_DSA:
2608 return device->flags & KEYMASTER_SUPPORTS_DSA;
2609 case TYPE_EC:
2610 return device->flags & KEYMASTER_SUPPORTS_EC;
2611 default:
2612 return false;
2613 }
2614 } else {
2615 return keyType == TYPE_RSA;
2616 }
2617 }
2618
Kenny Root07438c82012-11-02 15:41:02 -07002619 ::KeyStore* mKeyStore;
2620};
2621
2622}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002623
2624int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002625 if (argc < 2) {
2626 ALOGE("A directory must be specified!");
2627 return 1;
2628 }
2629 if (chdir(argv[1]) == -1) {
2630 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2631 return 1;
2632 }
2633
2634 Entropy entropy;
2635 if (!entropy.open()) {
2636 return 1;
2637 }
Kenny Root70e3a862012-02-15 17:20:23 -08002638
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07002639 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08002640 if (keymaster_device_initialize(&dev)) {
2641 ALOGE("keystore keymaster could not be initialized; exiting");
2642 return 1;
2643 }
2644
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002645 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002646 if (fallback_keymaster_device_initialize(&fallback)) {
2647 ALOGE("software keymaster could not be initialized; exiting");
2648 return 1;
2649 }
2650
Riley Spahneaabae92014-06-30 12:39:52 -07002651 ks_is_selinux_enabled = is_selinux_enabled();
2652 if (ks_is_selinux_enabled) {
2653 union selinux_callback cb;
2654 cb.func_log = selinux_log_callback;
2655 selinux_set_callback(SELINUX_CB_LOG, cb);
2656 if (getcon(&tctx) != 0) {
2657 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2658 return -1;
2659 }
2660 } else {
2661 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2662 }
2663
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002664 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07002665 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002666 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2667 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2668 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2669 if (ret != android::OK) {
2670 ALOGE("Couldn't register binder service!");
2671 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002672 }
Kenny Root07438c82012-11-02 15:41:02 -07002673
2674 /*
2675 * We're the only thread in existence, so we're just going to process
2676 * Binder transaction as a single-threaded program.
2677 */
2678 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002679
2680 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002681 return 1;
2682}