blob: c10dbdfc1d9fb9306b7509d5ee0d12d1a1ed9880 [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 Willden80843db2015-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 Willden80843db2015-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 Willden80843db2015-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 Willden80843db2015-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,
492} BlobType;
493
Kenny Rootf9119d62013-04-03 09:22:15 -0700494static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700495
Kenny Roota91203b2012-02-15 15:00:46 -0800496class Blob {
497public:
Kenny Root07438c82012-11-02 15:41:02 -0700498 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
499 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800500 memset(&mBlob, 0, sizeof(mBlob));
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
Alex Klyubin1773b442015-02-20 12:33:33 -0800521 Blob() {
522 memset(&mBlob, 0, sizeof(mBlob));
523 }
Kenny Roota91203b2012-02-15 15:00:46 -0800524
Kenny Root51878182012-03-13 12:53:19 -0700525 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800526 return mBlob.value;
527 }
528
Kenny Root51878182012-03-13 12:53:19 -0700529 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800530 return mBlob.length;
531 }
532
Kenny Root51878182012-03-13 12:53:19 -0700533 const uint8_t* getInfo() const {
534 return mBlob.value + mBlob.length;
535 }
536
537 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800538 return mBlob.info;
539 }
540
Kenny Root822c3a92012-03-23 16:34:39 -0700541 uint8_t getVersion() const {
542 return mBlob.version;
543 }
544
Kenny Rootf9119d62013-04-03 09:22:15 -0700545 bool isEncrypted() const {
546 if (mBlob.version < 2) {
547 return true;
548 }
549
550 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
551 }
552
553 void setEncrypted(bool encrypted) {
554 if (encrypted) {
555 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
556 } else {
557 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
558 }
559 }
560
Kenny Root17208e02013-09-04 13:56:03 -0700561 bool isFallback() const {
562 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
563 }
564
565 void setFallback(bool fallback) {
566 if (fallback) {
567 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
568 } else {
569 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
570 }
571 }
572
Kenny Root822c3a92012-03-23 16:34:39 -0700573 void setVersion(uint8_t version) {
574 mBlob.version = version;
575 }
576
577 BlobType getType() const {
578 return BlobType(mBlob.type);
579 }
580
581 void setType(BlobType type) {
582 mBlob.type = uint8_t(type);
583 }
584
Kenny Rootf9119d62013-04-03 09:22:15 -0700585 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
586 ALOGV("writing blob %s", filename);
587 if (isEncrypted()) {
588 if (state != STATE_NO_ERROR) {
589 ALOGD("couldn't insert encrypted blob while not unlocked");
590 return LOCKED;
591 }
592
593 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
594 ALOGW("Could not read random data for: %s", filename);
595 return SYSTEM_ERROR;
596 }
Kenny Roota91203b2012-02-15 15:00:46 -0800597 }
598
599 // data includes the value and the value's length
600 size_t dataLength = mBlob.length + sizeof(mBlob.length);
601 // pad data to the AES_BLOCK_SIZE
602 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
603 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
604 // encrypted data includes the digest value
605 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
606 // move info after space for padding
607 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
608 // zero padding area
609 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
610
611 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800612
Kenny Rootf9119d62013-04-03 09:22:15 -0700613 if (isEncrypted()) {
614 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800615
Kenny Rootf9119d62013-04-03 09:22:15 -0700616 uint8_t vector[AES_BLOCK_SIZE];
617 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
618 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
619 aes_key, vector, AES_ENCRYPT);
620 }
621
Kenny Roota91203b2012-02-15 15:00:46 -0800622 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
623 size_t fileLength = encryptedLength + headerLength + mBlob.info;
624
625 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800626 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
627 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
628 if (out < 0) {
629 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800630 return SYSTEM_ERROR;
631 }
632 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
633 if (close(out) != 0) {
634 return SYSTEM_ERROR;
635 }
636 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800637 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800638 unlink(tmpFileName);
639 return SYSTEM_ERROR;
640 }
Kenny Root150ca932012-11-14 14:29:02 -0800641 if (rename(tmpFileName, filename) == -1) {
642 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
643 return SYSTEM_ERROR;
644 }
645 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800646 }
647
Kenny Rootf9119d62013-04-03 09:22:15 -0700648 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
649 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800650 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
651 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800652 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
653 }
654 // fileLength may be less than sizeof(mBlob) since the in
655 // memory version has extra padding to tolerate rounding up to
656 // the AES_BLOCK_SIZE
657 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
658 if (close(in) != 0) {
659 return SYSTEM_ERROR;
660 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700661
662 if (isEncrypted() && (state != STATE_NO_ERROR)) {
663 return LOCKED;
664 }
665
Kenny Roota91203b2012-02-15 15:00:46 -0800666 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
667 if (fileLength < headerLength) {
668 return VALUE_CORRUPTED;
669 }
670
671 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700672 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800673 return VALUE_CORRUPTED;
674 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700675
676 ssize_t digestedLength;
677 if (isEncrypted()) {
678 if (encryptedLength % AES_BLOCK_SIZE != 0) {
679 return VALUE_CORRUPTED;
680 }
681
682 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
683 mBlob.vector, AES_DECRYPT);
684 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
685 uint8_t computedDigest[MD5_DIGEST_LENGTH];
686 MD5(mBlob.digested, digestedLength, computedDigest);
687 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
688 return VALUE_CORRUPTED;
689 }
690 } else {
691 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800692 }
693
694 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
695 mBlob.length = ntohl(mBlob.length);
696 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
697 return VALUE_CORRUPTED;
698 }
699 if (mBlob.info != 0) {
700 // move info from after padding to after data
701 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
702 }
Kenny Root07438c82012-11-02 15:41:02 -0700703 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800704 }
705
706private:
707 struct blob mBlob;
708};
709
Kenny Root655b9582013-04-04 08:37:42 -0700710class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800711public:
Kenny Root655b9582013-04-04 08:37:42 -0700712 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
713 asprintf(&mUserDir, "user_%u", mUserId);
714 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
715 }
716
717 ~UserState() {
718 free(mUserDir);
719 free(mMasterKeyFile);
720 }
721
722 bool initialize() {
723 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
724 ALOGE("Could not create directory '%s'", mUserDir);
725 return false;
726 }
727
728 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800729 setState(STATE_LOCKED);
730 } else {
731 setState(STATE_UNINITIALIZED);
732 }
Kenny Root70e3a862012-02-15 17:20:23 -0800733
Kenny Root655b9582013-04-04 08:37:42 -0700734 return true;
735 }
736
737 uid_t getUserId() const {
738 return mUserId;
739 }
740
741 const char* getUserDirName() const {
742 return mUserDir;
743 }
744
745 const char* getMasterKeyFileName() const {
746 return mMasterKeyFile;
747 }
748
749 void setState(State state) {
750 mState = state;
751 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
752 mRetry = MAX_RETRY;
753 }
Kenny Roota91203b2012-02-15 15:00:46 -0800754 }
755
Kenny Root51878182012-03-13 12:53:19 -0700756 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800757 return mState;
758 }
759
Kenny Root51878182012-03-13 12:53:19 -0700760 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800761 return mRetry;
762 }
763
Kenny Root655b9582013-04-04 08:37:42 -0700764 void zeroizeMasterKeysInMemory() {
765 memset(mMasterKey, 0, sizeof(mMasterKey));
766 memset(mSalt, 0, sizeof(mSalt));
767 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
768 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800769 }
770
Kenny Root655b9582013-04-04 08:37:42 -0700771 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
772 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800773 return SYSTEM_ERROR;
774 }
Kenny Root655b9582013-04-04 08:37:42 -0700775 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800776 if (response != NO_ERROR) {
777 return response;
778 }
779 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700780 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800781 }
782
Robin Lee4e865752014-08-19 17:37:55 +0100783 ResponseCode copyMasterKey(UserState* src) {
784 if (mState != STATE_UNINITIALIZED) {
785 return ::SYSTEM_ERROR;
786 }
787 if (src->getState() != STATE_NO_ERROR) {
788 return ::SYSTEM_ERROR;
789 }
790 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
791 setupMasterKeys();
792 return ::NO_ERROR;
793 }
794
Kenny Root655b9582013-04-04 08:37:42 -0700795 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800796 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
797 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
798 AES_KEY passwordAesKey;
799 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700800 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700801 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800802 }
803
Kenny Root655b9582013-04-04 08:37:42 -0700804 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
805 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800806 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800807 return SYSTEM_ERROR;
808 }
809
810 // we read the raw blob to just to get the salt to generate
811 // the AES key, then we create the Blob to use with decryptBlob
812 blob rawBlob;
813 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
814 if (close(in) != 0) {
815 return SYSTEM_ERROR;
816 }
817 // find salt at EOF if present, otherwise we have an old file
818 uint8_t* salt;
819 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
820 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
821 } else {
822 salt = NULL;
823 }
824 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
825 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
826 AES_KEY passwordAesKey;
827 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
828 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700829 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
830 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800831 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700832 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800833 }
834 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
835 // if salt was missing, generate one and write a new master key file with the salt.
836 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700837 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800838 return SYSTEM_ERROR;
839 }
Kenny Root655b9582013-04-04 08:37:42 -0700840 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800841 }
842 if (response == NO_ERROR) {
843 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
844 setupMasterKeys();
845 }
846 return response;
847 }
848 if (mRetry <= 0) {
849 reset();
850 return UNINITIALIZED;
851 }
852 --mRetry;
853 switch (mRetry) {
854 case 0: return WRONG_PASSWORD_0;
855 case 1: return WRONG_PASSWORD_1;
856 case 2: return WRONG_PASSWORD_2;
857 case 3: return WRONG_PASSWORD_3;
858 default: return WRONG_PASSWORD_3;
859 }
860 }
861
Kenny Root655b9582013-04-04 08:37:42 -0700862 AES_KEY* getEncryptionKey() {
863 return &mMasterKeyEncryption;
864 }
865
866 AES_KEY* getDecryptionKey() {
867 return &mMasterKeyDecryption;
868 }
869
Kenny Roota91203b2012-02-15 15:00:46 -0800870 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700871 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800872 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700873 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800874 return false;
875 }
Kenny Root655b9582013-04-04 08:37:42 -0700876
877 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800878 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700879 // We only care about files.
880 if (file->d_type != DT_REG) {
881 continue;
882 }
883
884 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700885 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700886 continue;
887 }
888
889 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800890 }
891 closedir(dir);
892 return true;
893 }
894
Kenny Root655b9582013-04-04 08:37:42 -0700895private:
896 static const int MASTER_KEY_SIZE_BYTES = 16;
897 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
898
899 static const int MAX_RETRY = 4;
900 static const size_t SALT_SIZE = 16;
901
902 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
903 uint8_t* salt) {
904 size_t saltSize;
905 if (salt != NULL) {
906 saltSize = SALT_SIZE;
907 } else {
908 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
909 salt = (uint8_t*) "keystore";
910 // sizeof = 9, not strlen = 8
911 saltSize = sizeof("keystore");
912 }
913
914 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
915 saltSize, 8192, keySize, key);
916 }
917
918 bool generateSalt(Entropy* entropy) {
919 return entropy->generate_random_data(mSalt, sizeof(mSalt));
920 }
921
922 bool generateMasterKey(Entropy* entropy) {
923 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
924 return false;
925 }
926 if (!generateSalt(entropy)) {
927 return false;
928 }
929 return true;
930 }
931
932 void setupMasterKeys() {
933 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
934 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
935 setState(STATE_NO_ERROR);
936 }
937
938 uid_t mUserId;
939
940 char* mUserDir;
941 char* mMasterKeyFile;
942
943 State mState;
944 int8_t mRetry;
945
946 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
947 uint8_t mSalt[SALT_SIZE];
948
949 AES_KEY mMasterKeyEncryption;
950 AES_KEY mMasterKeyDecryption;
951};
952
953typedef struct {
954 uint32_t uid;
955 const uint8_t* filename;
956} grant_t;
957
958class KeyStore {
959public:
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800960 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700961 : mEntropy(entropy)
962 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800963 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700964 {
965 memset(&mMetaData, '\0', sizeof(mMetaData));
966 }
967
968 ~KeyStore() {
969 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
970 it != mGrants.end(); it++) {
971 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700972 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800973 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700974
975 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
976 it != mMasterKeys.end(); it++) {
977 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700978 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800979 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700980 }
981
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800982 /**
983 * Depending on the hardware keymaster version is this may return a
984 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
985 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
986 * be guarded by a check on the device's version.
987 */
988 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700989 return mDevice;
990 }
991
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800992 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800993 return mFallbackDevice;
994 }
995
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800996 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800997 return blob.isFallback() ? mFallbackDevice: mDevice;
998 }
999
Kenny Root655b9582013-04-04 08:37:42 -07001000 ResponseCode initialize() {
1001 readMetaData();
1002 if (upgradeKeystore()) {
1003 writeMetaData();
1004 }
1005
1006 return ::NO_ERROR;
1007 }
1008
1009 State getState(uid_t uid) {
1010 return getUserState(uid)->getState();
1011 }
1012
1013 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
1014 UserState* userState = getUserState(uid);
1015 return userState->initialize(pw, mEntropy);
1016 }
1017
Robin Lee4e865752014-08-19 17:37:55 +01001018 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
1019 UserState *userState = getUserState(uid);
1020 UserState *initState = getUserState(src);
1021 return userState->copyMasterKey(initState);
1022 }
1023
Kenny Root655b9582013-04-04 08:37:42 -07001024 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001025 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001026 return userState->writeMasterKey(pw, mEntropy);
1027 }
1028
1029 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001030 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001031 return userState->readMasterKey(pw, mEntropy);
1032 }
1033
1034 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001035 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001036 encode_key(encoded, keyName);
1037 return android::String8(encoded);
1038 }
1039
1040 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001041 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001042 encode_key(encoded, keyName);
1043 return android::String8::format("%u_%s", uid, encoded);
1044 }
1045
1046 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001047 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001048 encode_key(encoded, keyName);
1049 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1050 encoded);
1051 }
1052
1053 bool reset(uid_t uid) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001054 android::String8 prefix("");
1055 android::Vector<android::String16> aliases;
1056 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1057 return ::SYSTEM_ERROR;
1058 }
1059
Kenny Root655b9582013-04-04 08:37:42 -07001060 UserState* userState = getUserState(uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001061 for (uint32_t i = 0; i < aliases.size(); i++) {
1062 android::String8 filename(aliases[i]);
1063 filename = android::String8::format("%s/%s", userState->getUserDirName(),
1064 getKeyName(filename).string());
1065 del(filename, ::TYPE_ANY, uid);
1066 }
1067
Kenny Root655b9582013-04-04 08:37:42 -07001068 userState->zeroizeMasterKeysInMemory();
1069 userState->setState(STATE_UNINITIALIZED);
1070 return userState->reset();
1071 }
1072
1073 bool isEmpty(uid_t uid) const {
1074 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001075 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001076 return true;
1077 }
1078
1079 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001080 if (!dir) {
1081 return true;
1082 }
Kenny Root31e27462014-09-10 11:28:03 -07001083
Kenny Roota91203b2012-02-15 15:00:46 -08001084 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001085 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001086 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001087 // We only care about files.
1088 if (file->d_type != DT_REG) {
1089 continue;
1090 }
1091
1092 // Skip anything that starts with a "."
1093 if (file->d_name[0] == '.') {
1094 continue;
1095 }
1096
Kenny Root31e27462014-09-10 11:28:03 -07001097 result = false;
1098 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001099 }
1100 closedir(dir);
1101 return result;
1102 }
1103
Kenny Root655b9582013-04-04 08:37:42 -07001104 void lock(uid_t uid) {
1105 UserState* userState = getUserState(uid);
1106 userState->zeroizeMasterKeysInMemory();
1107 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001108 }
1109
Kenny Root655b9582013-04-04 08:37:42 -07001110 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1111 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001112 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1113 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001114 if (rc != NO_ERROR) {
1115 return rc;
1116 }
1117
1118 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001119 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001120 /* If we upgrade the key, we need to write it to disk again. Then
1121 * it must be read it again since the blob is encrypted each time
1122 * it's written.
1123 */
Kenny Root655b9582013-04-04 08:37:42 -07001124 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1125 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001126 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1127 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001128 return rc;
1129 }
1130 }
Kenny Root822c3a92012-03-23 16:34:39 -07001131 }
1132
Kenny Root17208e02013-09-04 13:56:03 -07001133 /*
1134 * This will upgrade software-backed keys to hardware-backed keys when
1135 * the HAL for the device supports the newer key types.
1136 */
1137 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1138 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1139 && keyBlob->isFallback()) {
1140 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1141 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1142
1143 // The HAL allowed the import, reget the key to have the "fresh"
1144 // version.
1145 if (imported == NO_ERROR) {
1146 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1147 }
1148 }
1149
Kenny Rootd53bc922013-03-21 14:10:15 -07001150 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001151 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1152 return KEY_NOT_FOUND;
1153 }
1154
1155 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001156 }
1157
Kenny Root655b9582013-04-04 08:37:42 -07001158 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1159 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001160 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1161 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001162 }
1163
Robin Lee4b84fdc2014-09-24 11:56:57 +01001164 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1165 Blob keyBlob;
1166 ResponseCode rc = get(filename, &keyBlob, type, uid);
1167 if (rc != ::NO_ERROR) {
1168 return rc;
1169 }
1170
1171 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1172 // A device doesn't have to implement delete_keypair.
1173 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1174 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1175 rc = ::SYSTEM_ERROR;
1176 }
1177 }
1178 }
1179 if (rc != ::NO_ERROR) {
1180 return rc;
1181 }
1182
1183 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1184 }
1185
1186 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1187 uid_t uid) {
1188
1189 UserState* userState = getUserState(uid);
1190 size_t n = prefix.length();
1191
1192 DIR* dir = opendir(userState->getUserDirName());
1193 if (!dir) {
1194 ALOGW("can't open directory for user: %s", strerror(errno));
1195 return ::SYSTEM_ERROR;
1196 }
1197
1198 struct dirent* file;
1199 while ((file = readdir(dir)) != NULL) {
1200 // We only care about files.
1201 if (file->d_type != DT_REG) {
1202 continue;
1203 }
1204
1205 // Skip anything that starts with a "."
1206 if (file->d_name[0] == '.') {
1207 continue;
1208 }
1209
1210 if (!strncmp(prefix.string(), file->d_name, n)) {
1211 const char* p = &file->d_name[n];
1212 size_t plen = strlen(p);
1213
1214 size_t extra = decode_key_length(p, plen);
1215 char *match = (char*) malloc(extra + 1);
1216 if (match != NULL) {
1217 decode_key(match, p, plen);
1218 matches->push(android::String16(match, extra));
1219 free(match);
1220 } else {
1221 ALOGW("could not allocate match of size %zd", extra);
1222 }
1223 }
1224 }
1225 closedir(dir);
1226 return ::NO_ERROR;
1227 }
1228
Kenny Root07438c82012-11-02 15:41:02 -07001229 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001230 const grant_t* existing = getGrant(filename, granteeUid);
1231 if (existing == NULL) {
1232 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001233 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001234 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001235 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001236 }
1237 }
1238
Kenny Root07438c82012-11-02 15:41:02 -07001239 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001240 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1241 it != mGrants.end(); it++) {
1242 grant_t* grant = *it;
1243 if (grant->uid == granteeUid
1244 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1245 mGrants.erase(it);
1246 return true;
1247 }
Kenny Root70e3a862012-02-15 17:20:23 -08001248 }
Kenny Root70e3a862012-02-15 17:20:23 -08001249 return false;
1250 }
1251
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001252 bool hasGrant(const char* filename, const uid_t uid) const {
1253 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001254 }
1255
Kenny Rootf9119d62013-04-03 09:22:15 -07001256 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1257 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001258 uint8_t* data;
1259 size_t dataLength;
1260 int rc;
1261
1262 if (mDevice->import_keypair == NULL) {
1263 ALOGE("Keymaster doesn't support import!");
1264 return SYSTEM_ERROR;
1265 }
1266
Kenny Root17208e02013-09-04 13:56:03 -07001267 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001268 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001269 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001270 /*
1271 * Maybe the device doesn't support this type of key. Try to use the
1272 * software fallback keymaster implementation. This is a little bit
1273 * lazier than checking the PKCS#8 key type, but the software
1274 * implementation will do that anyway.
1275 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001276 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001277 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001278
1279 if (rc) {
1280 ALOGE("Error while importing keypair: %d", rc);
1281 return SYSTEM_ERROR;
1282 }
Kenny Root822c3a92012-03-23 16:34:39 -07001283 }
1284
1285 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1286 free(data);
1287
Kenny Rootf9119d62013-04-03 09:22:15 -07001288 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001289 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001290
Kenny Root655b9582013-04-04 08:37:42 -07001291 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001292 }
1293
Kenny Root1b0e3932013-09-05 13:06:32 -07001294 bool isHardwareBacked(const android::String16& keyType) const {
1295 if (mDevice == NULL) {
1296 ALOGW("can't get keymaster device");
1297 return false;
1298 }
1299
1300 if (sRSAKeyType == keyType) {
1301 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1302 } else {
1303 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1304 && (mDevice->common.module->module_api_version
1305 >= KEYMASTER_MODULE_API_VERSION_0_2);
1306 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001307 }
1308
Kenny Root655b9582013-04-04 08:37:42 -07001309 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1310 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001311 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001312
1313 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1314 if (responseCode == NO_ERROR) {
1315 return responseCode;
1316 }
1317
1318 // If this is one of the legacy UID->UID mappings, use it.
1319 uid_t euid = get_keystore_euid(uid);
1320 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001321 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001322 responseCode = get(filepath8.string(), keyBlob, type, uid);
1323 if (responseCode == NO_ERROR) {
1324 return responseCode;
1325 }
1326 }
1327
1328 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001329 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001330 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001331 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001332 if (end[0] != '_' || end[1] == 0) {
1333 return KEY_NOT_FOUND;
1334 }
Kenny Root86b16e82013-09-09 11:15:54 -07001335 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1336 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001337 if (!hasGrant(filepath8.string(), uid)) {
1338 return responseCode;
1339 }
1340
1341 // It is a granted key. Try to load it.
1342 return get(filepath8.string(), keyBlob, type, uid);
1343 }
1344
1345 /**
1346 * Returns any existing UserState or creates it if it doesn't exist.
1347 */
1348 UserState* getUserState(uid_t uid) {
1349 uid_t userId = get_user_id(uid);
1350
1351 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1352 it != mMasterKeys.end(); it++) {
1353 UserState* state = *it;
1354 if (state->getUserId() == userId) {
1355 return state;
1356 }
1357 }
1358
1359 UserState* userState = new UserState(userId);
1360 if (!userState->initialize()) {
1361 /* There's not much we can do if initialization fails. Trying to
1362 * unlock the keystore for that user will fail as well, so any
1363 * subsequent request for this user will just return SYSTEM_ERROR.
1364 */
1365 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1366 }
1367 mMasterKeys.add(userState);
1368 return userState;
1369 }
1370
1371 /**
1372 * Returns NULL if the UserState doesn't already exist.
1373 */
1374 const UserState* getUserState(uid_t uid) const {
1375 uid_t userId = get_user_id(uid);
1376
1377 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1378 it != mMasterKeys.end(); it++) {
1379 UserState* state = *it;
1380 if (state->getUserId() == userId) {
1381 return state;
1382 }
1383 }
1384
1385 return NULL;
1386 }
1387
Kenny Roota91203b2012-02-15 15:00:46 -08001388private:
Kenny Root655b9582013-04-04 08:37:42 -07001389 static const char* sOldMasterKey;
1390 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001391 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001392 Entropy* mEntropy;
1393
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001394 keymaster1_device_t* mDevice;
1395 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001396
Kenny Root655b9582013-04-04 08:37:42 -07001397 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001398
Kenny Root655b9582013-04-04 08:37:42 -07001399 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001400
Kenny Root655b9582013-04-04 08:37:42 -07001401 typedef struct {
1402 uint32_t version;
1403 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001404
Kenny Root655b9582013-04-04 08:37:42 -07001405 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001406
Kenny Root655b9582013-04-04 08:37:42 -07001407 const grant_t* getGrant(const char* filename, uid_t uid) const {
1408 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1409 it != mGrants.end(); it++) {
1410 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001411 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001412 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001413 return grant;
1414 }
1415 }
Kenny Root70e3a862012-02-15 17:20:23 -08001416 return NULL;
1417 }
1418
Kenny Root822c3a92012-03-23 16:34:39 -07001419 /**
1420 * Upgrade code. This will upgrade the key from the current version
1421 * to whatever is newest.
1422 */
Kenny Root655b9582013-04-04 08:37:42 -07001423 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1424 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001425 bool updated = false;
1426 uint8_t version = oldVersion;
1427
1428 /* From V0 -> V1: All old types were unknown */
1429 if (version == 0) {
1430 ALOGV("upgrading to version 1 and setting type %d", type);
1431
1432 blob->setType(type);
1433 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001434 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001435 }
1436 version = 1;
1437 updated = true;
1438 }
1439
Kenny Rootf9119d62013-04-03 09:22:15 -07001440 /* From V1 -> V2: All old keys were encrypted */
1441 if (version == 1) {
1442 ALOGV("upgrading to version 2");
1443
1444 blob->setEncrypted(true);
1445 version = 2;
1446 updated = true;
1447 }
1448
Kenny Root822c3a92012-03-23 16:34:39 -07001449 /*
1450 * If we've updated, set the key blob to the right version
1451 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001452 */
Kenny Root822c3a92012-03-23 16:34:39 -07001453 if (updated) {
1454 ALOGV("updated and writing file %s", filename);
1455 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001456 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001457
1458 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001459 }
1460
1461 /**
1462 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1463 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1464 * Then it overwrites the original blob with the new blob
1465 * format that is returned from the keymaster.
1466 */
Kenny Root655b9582013-04-04 08:37:42 -07001467 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001468 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1469 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1470 if (b.get() == NULL) {
1471 ALOGE("Problem instantiating BIO");
1472 return SYSTEM_ERROR;
1473 }
1474
1475 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1476 if (pkey.get() == NULL) {
1477 ALOGE("Couldn't read old PEM file");
1478 return SYSTEM_ERROR;
1479 }
1480
1481 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1482 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1483 if (len < 0) {
1484 ALOGE("Couldn't measure PKCS#8 length");
1485 return SYSTEM_ERROR;
1486 }
1487
Kenny Root70c98892013-02-07 09:10:36 -08001488 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1489 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001490 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1491 ALOGE("Couldn't convert to PKCS#8");
1492 return SYSTEM_ERROR;
1493 }
1494
Kenny Rootf9119d62013-04-03 09:22:15 -07001495 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1496 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001497 if (rc != NO_ERROR) {
1498 return rc;
1499 }
1500
Kenny Root655b9582013-04-04 08:37:42 -07001501 return get(filename, blob, TYPE_KEY_PAIR, uid);
1502 }
1503
1504 void readMetaData() {
1505 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1506 if (in < 0) {
1507 return;
1508 }
1509 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1510 if (fileLength != sizeof(mMetaData)) {
1511 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1512 sizeof(mMetaData));
1513 }
1514 close(in);
1515 }
1516
1517 void writeMetaData() {
1518 const char* tmpFileName = ".metadata.tmp";
1519 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1520 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1521 if (out < 0) {
1522 ALOGE("couldn't write metadata file: %s", strerror(errno));
1523 return;
1524 }
1525 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1526 if (fileLength != sizeof(mMetaData)) {
1527 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1528 sizeof(mMetaData));
1529 }
1530 close(out);
1531 rename(tmpFileName, sMetaDataFile);
1532 }
1533
1534 bool upgradeKeystore() {
1535 bool upgraded = false;
1536
1537 if (mMetaData.version == 0) {
1538 UserState* userState = getUserState(0);
1539
1540 // Initialize first so the directory is made.
1541 userState->initialize();
1542
1543 // Migrate the old .masterkey file to user 0.
1544 if (access(sOldMasterKey, R_OK) == 0) {
1545 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1546 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1547 return false;
1548 }
1549 }
1550
1551 // Initialize again in case we had a key.
1552 userState->initialize();
1553
1554 // Try to migrate existing keys.
1555 DIR* dir = opendir(".");
1556 if (!dir) {
1557 // Give up now; maybe we can upgrade later.
1558 ALOGE("couldn't open keystore's directory; something is wrong");
1559 return false;
1560 }
1561
1562 struct dirent* file;
1563 while ((file = readdir(dir)) != NULL) {
1564 // We only care about files.
1565 if (file->d_type != DT_REG) {
1566 continue;
1567 }
1568
1569 // Skip anything that starts with a "."
1570 if (file->d_name[0] == '.') {
1571 continue;
1572 }
1573
1574 // Find the current file's user.
1575 char* end;
1576 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1577 if (end[0] != '_' || end[1] == 0) {
1578 continue;
1579 }
1580 UserState* otherUser = getUserState(thisUid);
1581 if (otherUser->getUserId() != 0) {
1582 unlinkat(dirfd(dir), file->d_name, 0);
1583 }
1584
1585 // Rename the file into user directory.
1586 DIR* otherdir = opendir(otherUser->getUserDirName());
1587 if (otherdir == NULL) {
1588 ALOGW("couldn't open user directory for rename");
1589 continue;
1590 }
1591 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1592 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1593 }
1594 closedir(otherdir);
1595 }
1596 closedir(dir);
1597
1598 mMetaData.version = 1;
1599 upgraded = true;
1600 }
1601
1602 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001603 }
Kenny Roota91203b2012-02-15 15:00:46 -08001604};
1605
Kenny Root655b9582013-04-04 08:37:42 -07001606const char* KeyStore::sOldMasterKey = ".masterkey";
1607const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001608
Kenny Root1b0e3932013-09-05 13:06:32 -07001609const android::String16 KeyStore::sRSAKeyType("RSA");
1610
Kenny Root07438c82012-11-02 15:41:02 -07001611namespace android {
1612class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1613public:
1614 KeyStoreProxy(KeyStore* keyStore)
1615 : mKeyStore(keyStore)
1616 {
Kenny Roota91203b2012-02-15 15:00:46 -08001617 }
Kenny Roota91203b2012-02-15 15:00:46 -08001618
Kenny Root07438c82012-11-02 15:41:02 -07001619 void binderDied(const wp<IBinder>&) {
1620 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001621 }
Kenny Roota91203b2012-02-15 15:00:46 -08001622
Kenny Root07438c82012-11-02 15:41:02 -07001623 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001624 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001625 pid_t spid = IPCThreadState::self()->getCallingPid();
1626 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001627 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001628 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001629 }
Kenny Roota91203b2012-02-15 15:00:46 -08001630
Kenny Root655b9582013-04-04 08:37:42 -07001631 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001632 }
1633
Kenny Root07438c82012-11-02 15:41:02 -07001634 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001635 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001636 pid_t spid = IPCThreadState::self()->getCallingPid();
1637 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001638 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001639 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001640 }
Kenny Root07438c82012-11-02 15:41:02 -07001641
Kenny Root07438c82012-11-02 15:41:02 -07001642 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001643 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001644
Kenny Root655b9582013-04-04 08:37:42 -07001645 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001646 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001647 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001648 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001649 *item = NULL;
1650 *itemLength = 0;
1651 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001652 }
Kenny Roota91203b2012-02-15 15:00:46 -08001653
Kenny Root07438c82012-11-02 15:41:02 -07001654 *item = (uint8_t*) malloc(keyBlob.getLength());
1655 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1656 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001657
Kenny Root07438c82012-11-02 15:41:02 -07001658 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001659 }
1660
Kenny Rootf9119d62013-04-03 09:22:15 -07001661 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1662 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001663 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001664 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001665 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001666 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001667 return ::PERMISSION_DENIED;
1668 }
Kenny Root07438c82012-11-02 15:41:02 -07001669
Kenny Rootf9119d62013-04-03 09:22:15 -07001670 State state = mKeyStore->getState(callingUid);
1671 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1672 ALOGD("calling get in state: %d", state);
1673 return state;
1674 }
1675
Kenny Root49468902013-03-19 13:41:33 -07001676 if (targetUid == -1) {
1677 targetUid = callingUid;
1678 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001679 return ::PERMISSION_DENIED;
1680 }
1681
Kenny Root07438c82012-11-02 15:41:02 -07001682 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001683 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001684
1685 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001686 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1687
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001688 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001689 }
1690
Kenny Root49468902013-03-19 13:41:33 -07001691 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001692 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001693 pid_t spid = IPCThreadState::self()->getCallingPid();
1694 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001695 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001696 return ::PERMISSION_DENIED;
1697 }
Kenny Root70e3a862012-02-15 17:20:23 -08001698
Kenny Root49468902013-03-19 13:41:33 -07001699 if (targetUid == -1) {
1700 targetUid = callingUid;
1701 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001702 return ::PERMISSION_DENIED;
1703 }
1704
Kenny Root07438c82012-11-02 15:41:02 -07001705 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001706 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01001707 return mKeyStore->del(filename.string(), ::TYPE_GENERIC, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001708 }
1709
Kenny Root49468902013-03-19 13:41:33 -07001710 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001711 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001712 pid_t spid = IPCThreadState::self()->getCallingPid();
1713 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001714 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001715 return ::PERMISSION_DENIED;
1716 }
Kenny Root70e3a862012-02-15 17:20:23 -08001717
Kenny Root49468902013-03-19 13:41:33 -07001718 if (targetUid == -1) {
1719 targetUid = callingUid;
1720 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001721 return ::PERMISSION_DENIED;
1722 }
1723
Kenny Root07438c82012-11-02 15:41:02 -07001724 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001725 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001726
Kenny Root655b9582013-04-04 08:37:42 -07001727 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001728 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1729 }
1730 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001731 }
1732
Kenny Root49468902013-03-19 13:41:33 -07001733 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001734 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001735 pid_t spid = IPCThreadState::self()->getCallingPid();
1736 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001737 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001738 return ::PERMISSION_DENIED;
1739 }
Kenny Root70e3a862012-02-15 17:20:23 -08001740
Kenny Root49468902013-03-19 13:41:33 -07001741 if (targetUid == -1) {
1742 targetUid = callingUid;
1743 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001744 return ::PERMISSION_DENIED;
1745 }
1746
Kenny Root07438c82012-11-02 15:41:02 -07001747 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001748 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001749
Robin Lee4b84fdc2014-09-24 11:56:57 +01001750 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1751 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001752 }
Kenny Root07438c82012-11-02 15:41:02 -07001753 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001754 }
1755
Kenny Root07438c82012-11-02 15:41:02 -07001756 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001757 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001758 pid_t spid = IPCThreadState::self()->getCallingPid();
1759 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001760 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001761 return ::PERMISSION_DENIED;
1762 }
1763
Robin Lee4b84fdc2014-09-24 11:56:57 +01001764 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001765 }
1766
Kenny Root07438c82012-11-02 15:41:02 -07001767 /*
1768 * Here is the history. To improve the security, the parameters to generate the
1769 * master key has been changed. To make a seamless transition, we update the
1770 * file using the same password when the user unlock it for the first time. If
1771 * any thing goes wrong during the transition, the new file will not overwrite
1772 * the old one. This avoids permanent damages of the existing data.
1773 */
1774 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001775 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001776 pid_t spid = IPCThreadState::self()->getCallingPid();
1777 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001778 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001779 return ::PERMISSION_DENIED;
1780 }
Kenny Root70e3a862012-02-15 17:20:23 -08001781
Kenny Root07438c82012-11-02 15:41:02 -07001782 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001783
Kenny Root655b9582013-04-04 08:37:42 -07001784 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001785 case ::STATE_UNINITIALIZED: {
1786 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001787 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001788 }
1789 case ::STATE_NO_ERROR: {
1790 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001791 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001792 }
1793 case ::STATE_LOCKED: {
1794 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001795 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001796 }
1797 }
1798 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001799 }
1800
Kenny Root07438c82012-11-02 15:41:02 -07001801 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001802 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001803 pid_t spid = IPCThreadState::self()->getCallingPid();
1804 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001805 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001806 return ::PERMISSION_DENIED;
1807 }
Kenny Root70e3a862012-02-15 17:20:23 -08001808
Kenny Root655b9582013-04-04 08:37:42 -07001809 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001810 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001811 ALOGD("calling lock in state: %d", state);
1812 return state;
1813 }
1814
Kenny Root655b9582013-04-04 08:37:42 -07001815 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001816 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001817 }
1818
Kenny Root07438c82012-11-02 15:41:02 -07001819 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001820 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001821 pid_t spid = IPCThreadState::self()->getCallingPid();
1822 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001823 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001824 return ::PERMISSION_DENIED;
1825 }
1826
Kenny Root655b9582013-04-04 08:37:42 -07001827 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001828 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001829 ALOGD("calling unlock when not locked");
1830 return state;
1831 }
1832
1833 const String8 password8(pw);
1834 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001835 }
1836
Kenny Root07438c82012-11-02 15:41:02 -07001837 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001838 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001839 pid_t spid = IPCThreadState::self()->getCallingPid();
1840 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001841 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001842 return -1;
1843 }
Kenny Root70e3a862012-02-15 17:20:23 -08001844
Kenny Root655b9582013-04-04 08:37:42 -07001845 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001846 }
1847
Kenny Root96427ba2013-08-16 14:02:41 -07001848 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1849 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001850 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001851 pid_t spid = IPCThreadState::self()->getCallingPid();
1852 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001853 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001854 return ::PERMISSION_DENIED;
1855 }
Kenny Root70e3a862012-02-15 17:20:23 -08001856
Kenny Root49468902013-03-19 13:41:33 -07001857 if (targetUid == -1) {
1858 targetUid = callingUid;
1859 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001860 return ::PERMISSION_DENIED;
1861 }
1862
Kenny Root655b9582013-04-04 08:37:42 -07001863 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001864 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1865 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001866 return state;
1867 }
Kenny Root70e3a862012-02-15 17:20:23 -08001868
Kenny Root07438c82012-11-02 15:41:02 -07001869 uint8_t* data;
1870 size_t dataLength;
1871 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001872 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001873
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001874 const keymaster1_device_t* device = mKeyStore->getDevice();
1875 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001876 if (device == NULL) {
1877 return ::SYSTEM_ERROR;
1878 }
1879
1880 if (device->generate_keypair == NULL) {
1881 return ::SYSTEM_ERROR;
1882 }
1883
Kenny Root17208e02013-09-04 13:56:03 -07001884 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001885 keymaster_dsa_keygen_params_t dsa_params;
1886 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001887
Kenny Root96427ba2013-08-16 14:02:41 -07001888 if (keySize == -1) {
1889 keySize = DSA_DEFAULT_KEY_SIZE;
1890 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1891 || keySize > DSA_MAX_KEY_SIZE) {
1892 ALOGI("invalid key size %d", keySize);
1893 return ::SYSTEM_ERROR;
1894 }
1895 dsa_params.key_size = keySize;
1896
1897 if (args->size() == 3) {
1898 sp<KeystoreArg> gArg = args->itemAt(0);
1899 sp<KeystoreArg> pArg = args->itemAt(1);
1900 sp<KeystoreArg> qArg = args->itemAt(2);
1901
1902 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1903 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1904 dsa_params.generator_len = gArg->size();
1905
1906 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1907 dsa_params.prime_p_len = pArg->size();
1908
1909 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1910 dsa_params.prime_q_len = qArg->size();
1911 } else {
1912 ALOGI("not all DSA parameters were read");
1913 return ::SYSTEM_ERROR;
1914 }
1915 } else if (args->size() != 0) {
1916 ALOGI("DSA args must be 3");
1917 return ::SYSTEM_ERROR;
1918 }
1919
Kenny Root1d448c02013-11-21 10:36:53 -08001920 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001921 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1922 } else {
1923 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001924 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1925 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001926 }
1927 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001928 keymaster_ec_keygen_params_t ec_params;
1929 memset(&ec_params, '\0', sizeof(ec_params));
1930
1931 if (keySize == -1) {
1932 keySize = EC_DEFAULT_KEY_SIZE;
1933 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1934 ALOGI("invalid key size %d", keySize);
1935 return ::SYSTEM_ERROR;
1936 }
1937 ec_params.field_size = keySize;
1938
Kenny Root1d448c02013-11-21 10:36:53 -08001939 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001940 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1941 } else {
1942 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001943 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001944 }
Kenny Root96427ba2013-08-16 14:02:41 -07001945 } else if (keyType == EVP_PKEY_RSA) {
1946 keymaster_rsa_keygen_params_t rsa_params;
1947 memset(&rsa_params, '\0', sizeof(rsa_params));
1948 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1949
1950 if (keySize == -1) {
1951 keySize = RSA_DEFAULT_KEY_SIZE;
1952 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1953 ALOGI("invalid key size %d", keySize);
1954 return ::SYSTEM_ERROR;
1955 }
1956 rsa_params.modulus_size = keySize;
1957
1958 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001959 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001960 return ::SYSTEM_ERROR;
1961 } else if (args->size() == 1) {
1962 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1963 if (pubExpBlob != NULL) {
1964 Unique_BIGNUM pubExpBn(
1965 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1966 pubExpBlob->size(), NULL));
1967 if (pubExpBn.get() == NULL) {
1968 ALOGI("Could not convert public exponent to BN");
1969 return ::SYSTEM_ERROR;
1970 }
1971 unsigned long pubExp = BN_get_word(pubExpBn.get());
1972 if (pubExp == 0xFFFFFFFFL) {
1973 ALOGI("cannot represent public exponent as a long value");
1974 return ::SYSTEM_ERROR;
1975 }
1976 rsa_params.public_exponent = pubExp;
1977 }
1978 }
1979
1980 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1981 } else {
1982 ALOGW("Unsupported key type %d", keyType);
1983 rc = -1;
1984 }
1985
Kenny Root07438c82012-11-02 15:41:02 -07001986 if (rc) {
1987 return ::SYSTEM_ERROR;
1988 }
1989
Kenny Root655b9582013-04-04 08:37:42 -07001990 String8 name8(name);
1991 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001992
1993 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1994 free(data);
1995
Kenny Rootee8068b2013-10-07 09:49:15 -07001996 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001997 keyBlob.setFallback(isFallback);
1998
Kenny Root655b9582013-04-04 08:37:42 -07001999 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08002000 }
2001
Kenny Rootf9119d62013-04-03 09:22:15 -07002002 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2003 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002004 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002005 pid_t spid = IPCThreadState::self()->getCallingPid();
2006 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002007 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002008 return ::PERMISSION_DENIED;
2009 }
Kenny Root07438c82012-11-02 15:41:02 -07002010
Kenny Root49468902013-03-19 13:41:33 -07002011 if (targetUid == -1) {
2012 targetUid = callingUid;
2013 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002014 return ::PERMISSION_DENIED;
2015 }
2016
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002017 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07002018 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002019 ALOGD("calling import in state: %d", state);
2020 return state;
2021 }
2022
2023 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002024 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002025
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002026 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002027 }
2028
Kenny Root07438c82012-11-02 15:41:02 -07002029 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2030 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002031 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002032 pid_t spid = IPCThreadState::self()->getCallingPid();
2033 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002034 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002035 return ::PERMISSION_DENIED;
2036 }
Kenny Root07438c82012-11-02 15:41:02 -07002037
Kenny Root07438c82012-11-02 15:41:02 -07002038 Blob keyBlob;
2039 String8 name8(name);
2040
Kenny Rootd38a0b02013-02-13 12:59:14 -08002041 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002042 int rc;
2043
Kenny Root655b9582013-04-04 08:37:42 -07002044 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002045 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002046 if (responseCode != ::NO_ERROR) {
2047 return responseCode;
2048 }
2049
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002050 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002051 if (device == NULL) {
2052 ALOGE("no keymaster device; cannot sign");
2053 return ::SYSTEM_ERROR;
2054 }
2055
2056 if (device->sign_data == NULL) {
2057 ALOGE("device doesn't implement signing");
2058 return ::SYSTEM_ERROR;
2059 }
2060
2061 keymaster_rsa_sign_params_t params;
2062 params.digest_type = DIGEST_NONE;
2063 params.padding_type = PADDING_NONE;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002064 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2065 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002066 if (rc) {
2067 ALOGW("device couldn't sign data");
2068 return ::SYSTEM_ERROR;
2069 }
2070
2071 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002072 }
2073
Kenny Root07438c82012-11-02 15:41:02 -07002074 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2075 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002076 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002077 pid_t spid = IPCThreadState::self()->getCallingPid();
2078 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002079 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002080 return ::PERMISSION_DENIED;
2081 }
Kenny Root70e3a862012-02-15 17:20:23 -08002082
Kenny Root655b9582013-04-04 08:37:42 -07002083 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002084 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002085 ALOGD("calling verify in state: %d", state);
2086 return state;
2087 }
Kenny Root70e3a862012-02-15 17:20:23 -08002088
Kenny Root07438c82012-11-02 15:41:02 -07002089 Blob keyBlob;
2090 String8 name8(name);
2091 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002092
Kenny Root655b9582013-04-04 08:37:42 -07002093 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002094 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002095 if (responseCode != ::NO_ERROR) {
2096 return responseCode;
2097 }
Kenny Root70e3a862012-02-15 17:20:23 -08002098
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002099 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002100 if (device == NULL) {
2101 return ::SYSTEM_ERROR;
2102 }
Kenny Root70e3a862012-02-15 17:20:23 -08002103
Kenny Root07438c82012-11-02 15:41:02 -07002104 if (device->verify_data == NULL) {
2105 return ::SYSTEM_ERROR;
2106 }
Kenny Root70e3a862012-02-15 17:20:23 -08002107
Kenny Root07438c82012-11-02 15:41:02 -07002108 keymaster_rsa_sign_params_t params;
2109 params.digest_type = DIGEST_NONE;
2110 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002111
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002112 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2113 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002114 if (rc) {
2115 return ::SYSTEM_ERROR;
2116 } else {
2117 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002118 }
2119 }
Kenny Root07438c82012-11-02 15:41:02 -07002120
2121 /*
2122 * TODO: The abstraction between things stored in hardware and regular blobs
2123 * of data stored on the filesystem should be moved down to keystore itself.
2124 * Unfortunately the Java code that calls this has naming conventions that it
2125 * knows about. Ideally keystore shouldn't be used to store random blobs of
2126 * data.
2127 *
2128 * Until that happens, it's necessary to have a separate "get_pubkey" and
2129 * "del_key" since the Java code doesn't really communicate what it's
2130 * intentions are.
2131 */
2132 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002133 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002134 pid_t spid = IPCThreadState::self()->getCallingPid();
2135 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002136 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002137 return ::PERMISSION_DENIED;
2138 }
Kenny Root07438c82012-11-02 15:41:02 -07002139
Kenny Root07438c82012-11-02 15:41:02 -07002140 Blob keyBlob;
2141 String8 name8(name);
2142
Kenny Rootd38a0b02013-02-13 12:59:14 -08002143 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002144
Kenny Root655b9582013-04-04 08:37:42 -07002145 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002146 TYPE_KEY_PAIR);
2147 if (responseCode != ::NO_ERROR) {
2148 return responseCode;
2149 }
2150
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002151 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002152 if (device == NULL) {
2153 return ::SYSTEM_ERROR;
2154 }
2155
2156 if (device->get_keypair_public == NULL) {
2157 ALOGE("device has no get_keypair_public implementation!");
2158 return ::SYSTEM_ERROR;
2159 }
2160
Kenny Root17208e02013-09-04 13:56:03 -07002161 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002162 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2163 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002164 if (rc) {
2165 return ::SYSTEM_ERROR;
2166 }
2167
2168 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002169 }
Kenny Root07438c82012-11-02 15:41:02 -07002170
Kenny Root49468902013-03-19 13:41:33 -07002171 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002172 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002173 pid_t spid = IPCThreadState::self()->getCallingPid();
2174 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002175 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002176 return ::PERMISSION_DENIED;
2177 }
Kenny Root07438c82012-11-02 15:41:02 -07002178
Kenny Root49468902013-03-19 13:41:33 -07002179 if (targetUid == -1) {
2180 targetUid = callingUid;
2181 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002182 return ::PERMISSION_DENIED;
2183 }
2184
Kenny Root07438c82012-11-02 15:41:02 -07002185 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002186 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01002187 return mKeyStore->del(filename.string(), ::TYPE_KEY_PAIR, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002188 }
2189
2190 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002191 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002192 pid_t spid = IPCThreadState::self()->getCallingPid();
2193 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002194 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002195 return ::PERMISSION_DENIED;
2196 }
Kenny Root07438c82012-11-02 15:41:02 -07002197
Kenny Root655b9582013-04-04 08:37:42 -07002198 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002199 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002200 ALOGD("calling grant in state: %d", state);
2201 return state;
2202 }
2203
2204 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002205 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002206
Kenny Root655b9582013-04-04 08:37:42 -07002207 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002208 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2209 }
2210
Kenny Root655b9582013-04-04 08:37:42 -07002211 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002212 return ::NO_ERROR;
2213 }
2214
2215 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002216 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002217 pid_t spid = IPCThreadState::self()->getCallingPid();
2218 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002219 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002220 return ::PERMISSION_DENIED;
2221 }
Kenny Root07438c82012-11-02 15:41:02 -07002222
Kenny Root655b9582013-04-04 08:37:42 -07002223 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002224 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002225 ALOGD("calling ungrant in state: %d", state);
2226 return state;
2227 }
2228
2229 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002230 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002231
Kenny Root655b9582013-04-04 08:37:42 -07002232 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002233 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2234 }
2235
Kenny Root655b9582013-04-04 08:37:42 -07002236 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002237 }
2238
2239 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002240 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002241 pid_t spid = IPCThreadState::self()->getCallingPid();
2242 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002243 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002244 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002245 }
Kenny Root07438c82012-11-02 15:41:02 -07002246
2247 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002248 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002249
Kenny Root655b9582013-04-04 08:37:42 -07002250 if (access(filename.string(), R_OK) == -1) {
2251 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002252 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002253 }
2254
Kenny Root655b9582013-04-04 08:37:42 -07002255 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002256 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002257 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002258 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002259 }
2260
2261 struct stat s;
2262 int ret = fstat(fd, &s);
2263 close(fd);
2264 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002265 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002266 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002267 }
2268
Kenny Root36a9e232013-02-04 14:24:15 -08002269 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002270 }
2271
Kenny Rootd53bc922013-03-21 14:10:15 -07002272 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2273 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002274 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002275 pid_t spid = IPCThreadState::self()->getCallingPid();
2276 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002277 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002278 return -1L;
2279 }
2280
Kenny Root655b9582013-04-04 08:37:42 -07002281 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002282 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002283 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002284 return state;
2285 }
2286
Kenny Rootd53bc922013-03-21 14:10:15 -07002287 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2288 srcUid = callingUid;
2289 } else if (!is_granted_to(callingUid, srcUid)) {
2290 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002291 return ::PERMISSION_DENIED;
2292 }
2293
Kenny Rootd53bc922013-03-21 14:10:15 -07002294 if (destUid == -1) {
2295 destUid = callingUid;
2296 }
2297
2298 if (srcUid != destUid) {
2299 if (static_cast<uid_t>(srcUid) != callingUid) {
2300 ALOGD("can only duplicate from caller to other or to same uid: "
2301 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2302 return ::PERMISSION_DENIED;
2303 }
2304
2305 if (!is_granted_to(callingUid, destUid)) {
2306 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2307 return ::PERMISSION_DENIED;
2308 }
2309 }
2310
2311 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002312 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002313
Kenny Rootd53bc922013-03-21 14:10:15 -07002314 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002315 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002316
Kenny Root655b9582013-04-04 08:37:42 -07002317 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2318 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002319 return ::SYSTEM_ERROR;
2320 }
2321
Kenny Rootd53bc922013-03-21 14:10:15 -07002322 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002323 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002324 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002325 if (responseCode != ::NO_ERROR) {
2326 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002327 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002328
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002329 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002330 }
2331
Kenny Root1b0e3932013-09-05 13:06:32 -07002332 int32_t is_hardware_backed(const String16& keyType) {
2333 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002334 }
2335
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002336 int32_t clear_uid(int64_t targetUid64) {
2337 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002338 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002339 pid_t spid = IPCThreadState::self()->getCallingPid();
2340 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002341 ALOGW("permission denied for %d: clear_uid", callingUid);
2342 return ::PERMISSION_DENIED;
2343 }
2344
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002345 if (targetUid64 == -1) {
2346 targetUid = callingUid;
Kenny Root007cb232014-07-30 16:59:42 -07002347 } else if (!is_self_or_system(callingUid, targetUid)) {
2348 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002349 return ::PERMISSION_DENIED;
2350 }
2351
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002352 const keymaster1_device_t* device = mKeyStore->getDevice();
Kenny Roota9bb5492013-04-01 16:29:11 -07002353 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002354 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002355 return ::SYSTEM_ERROR;
2356 }
2357
Robin Lee4b84fdc2014-09-24 11:56:57 +01002358 String8 prefix = String8::format("%u_", targetUid);
2359 Vector<String16> aliases;
2360 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002361 return ::SYSTEM_ERROR;
2362 }
2363
Robin Lee4b84fdc2014-09-24 11:56:57 +01002364 for (uint32_t i = 0; i < aliases.size(); i++) {
2365 String8 name8(aliases[i]);
2366 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2367 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002368 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002369 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002370 }
2371
Robin Lee4b84fdc2014-09-24 11:56:57 +01002372 int32_t reset_uid(int32_t targetUid) {
Robin Lee4e865752014-08-19 17:37:55 +01002373 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2374 pid_t spid = IPCThreadState::self()->getCallingPid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01002375
Robin Lee4e865752014-08-19 17:37:55 +01002376 if (!has_permission(callingUid, P_RESET_UID, spid)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01002377 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002378 return ::PERMISSION_DENIED;
2379 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002380 if (!is_self_or_system(callingUid, targetUid)) {
2381 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002382 return ::PERMISSION_DENIED;
2383 }
2384
Robin Lee4b84fdc2014-09-24 11:56:57 +01002385 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002386 }
2387
2388 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
2389 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2390 pid_t spid = IPCThreadState::self()->getCallingPid();
2391 if (!has_permission(callingUid, P_SYNC_UID, spid)) {
2392 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2393 return ::PERMISSION_DENIED;
2394 }
2395 if (callingUid != AID_SYSTEM) {
2396 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2397 return ::PERMISSION_DENIED;
2398 }
2399 if (sourceUid == targetUid) {
2400 return ::SYSTEM_ERROR;
2401 }
2402
2403 // Initialise user keystore with existing master key held in-memory
2404 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2405 }
2406
2407 int32_t password_uid(const String16& pw, int32_t targetUid) {
2408 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2409 pid_t spid = IPCThreadState::self()->getCallingPid();
2410 if (!has_permission(callingUid, P_PASSWORD_UID, spid)) {
2411 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2412 return ::PERMISSION_DENIED;
2413 }
2414 if (callingUid != AID_SYSTEM) {
2415 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2416 return ::PERMISSION_DENIED;
2417 }
2418
2419 const String8 password8(pw);
2420
2421 switch (mKeyStore->getState(targetUid)) {
2422 case ::STATE_UNINITIALIZED: {
2423 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2424 return mKeyStore->initializeUser(password8, targetUid);
2425 }
2426 case ::STATE_NO_ERROR: {
2427 // rewrite master key with new password.
2428 return mKeyStore->writeMasterKey(password8, targetUid);
2429 }
2430 case ::STATE_LOCKED: {
2431 // read master key, decrypt with password, initialize mMasterKey*.
2432 return mKeyStore->readMasterKey(password8, targetUid);
2433 }
2434 }
2435 return ::SYSTEM_ERROR;
2436 }
2437
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002438 int32_t addRngEntropy(const uint8_t* /*data*/, size_t /*dataLength*/) {
2439 return KM_ERROR_UNIMPLEMENTED;
2440 }
2441
2442 int32_t generateKey(const String16& /*name*/, const KeymasterArguments& /*params*/,
2443 int /*uid*/, int /*flags*/, KeyCharacteristics* /*outCharacteristics*/) {
2444 return KM_ERROR_UNIMPLEMENTED;
2445 }
2446
2447 int32_t getKeyCharacteristics(const String16& /*name*/,
2448 const keymaster_blob_t& /*clientId*/,
2449 const keymaster_blob_t& /*appData*/,
2450 KeyCharacteristics* /*outCharacteristics*/) {
2451 return KM_ERROR_UNIMPLEMENTED;
2452 }
2453
2454 int32_t importKey(const String16& /*name*/, const KeymasterArguments& /*params*/,
2455 keymaster_key_format_t /*format*/, const uint8_t* /*keyData*/,
2456 size_t /*keyLength*/, int /*uid*/, int /*flags*/,
2457 KeyCharacteristics* /*outCharacteristics*/) {
2458 return KM_ERROR_UNIMPLEMENTED;
2459 }
2460
2461 void exportKey(const String16& /*name*/, keymaster_key_format_t /*format*/,
2462 const keymaster_blob_t& /*clientId*/,
2463 const keymaster_blob_t& /*appData*/, ExportResult* result) {
2464 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2465 }
2466
2467 void begin(const sp<IBinder>& /*appToken*/, const String16& /*name*/,
2468 keymaster_purpose_t /*purpose*/, bool /*pruneable*/,
2469 const KeymasterArguments& /*params*/, KeymasterArguments* /*outParams*/,
2470 OperationResult* result) {
2471 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2472 }
2473
2474 void update(const sp<IBinder>& /*token*/, const KeymasterArguments& /*params*/,
2475 uint8_t* /*data*/, size_t /*dataLength*/, OperationResult* result) {
2476 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2477 }
2478
2479 void finish(const sp<IBinder>& /*token*/, const KeymasterArguments& /*args*/,
2480 uint8_t* /*signature*/, size_t /*signatureLength*/, OperationResult* result) {
2481 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2482 }
2483
2484 int32_t abort(const sp<IBinder>& /*token*/) {
2485 return KM_ERROR_UNIMPLEMENTED;
2486 }
2487
Kenny Root07438c82012-11-02 15:41:02 -07002488private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002489 inline bool isKeystoreUnlocked(State state) {
2490 switch (state) {
2491 case ::STATE_NO_ERROR:
2492 return true;
2493 case ::STATE_UNINITIALIZED:
2494 case ::STATE_LOCKED:
2495 return false;
2496 }
2497 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002498 }
2499
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002500 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002501 const int32_t device_api = device->common.module->module_api_version;
2502 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2503 switch (keyType) {
2504 case TYPE_RSA:
2505 case TYPE_DSA:
2506 case TYPE_EC:
2507 return true;
2508 default:
2509 return false;
2510 }
2511 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2512 switch (keyType) {
2513 case TYPE_RSA:
2514 return true;
2515 case TYPE_DSA:
2516 return device->flags & KEYMASTER_SUPPORTS_DSA;
2517 case TYPE_EC:
2518 return device->flags & KEYMASTER_SUPPORTS_EC;
2519 default:
2520 return false;
2521 }
2522 } else {
2523 return keyType == TYPE_RSA;
2524 }
2525 }
2526
Kenny Root07438c82012-11-02 15:41:02 -07002527 ::KeyStore* mKeyStore;
2528};
2529
2530}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002531
2532int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002533 if (argc < 2) {
2534 ALOGE("A directory must be specified!");
2535 return 1;
2536 }
2537 if (chdir(argv[1]) == -1) {
2538 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2539 return 1;
2540 }
2541
2542 Entropy entropy;
2543 if (!entropy.open()) {
2544 return 1;
2545 }
Kenny Root70e3a862012-02-15 17:20:23 -08002546
Shawn Willden80843db2015-02-24 09:31:25 -07002547 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08002548 if (keymaster_device_initialize(&dev)) {
2549 ALOGE("keystore keymaster could not be initialized; exiting");
2550 return 1;
2551 }
2552
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002553 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002554 if (fallback_keymaster_device_initialize(&fallback)) {
2555 ALOGE("software keymaster could not be initialized; exiting");
2556 return 1;
2557 }
2558
Riley Spahneaabae92014-06-30 12:39:52 -07002559 ks_is_selinux_enabled = is_selinux_enabled();
2560 if (ks_is_selinux_enabled) {
2561 union selinux_callback cb;
2562 cb.func_log = selinux_log_callback;
2563 selinux_set_callback(SELINUX_CB_LOG, cb);
2564 if (getcon(&tctx) != 0) {
2565 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2566 return -1;
2567 }
2568 } else {
2569 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2570 }
2571
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002572 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07002573 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002574 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2575 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2576 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2577 if (ret != android::OK) {
2578 ALOGE("Couldn't register binder service!");
2579 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002580 }
Kenny Root07438c82012-11-02 15:41:02 -07002581
2582 /*
2583 * We're the only thread in existence, so we're just going to process
2584 * Binder transaction as a single-threaded program.
2585 */
2586 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002587
2588 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002589 return 1;
2590}