blob: da3ffabc4c0952389432958a3507db42c234519d [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willdena5bbf2f2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Kenny Root17208e02013-09-04 13:56:03 -070046#include <keymaster/softkeymaster.h>
Chad Brubaker919cb2a2015-02-05 21:58:25 -080047#include <keymaster/soft_keymaster_device.h>
Kenny Root17208e02013-09-04 13:56:03 -070048
Kenny Root26cfc082013-09-11 14:38:56 -070049#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070050#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080052
Kenny Root07438c82012-11-02 15:41:02 -070053#include <keystore/IKeystoreService.h>
54#include <binder/IPCThreadState.h>
55#include <binder/IServiceManager.h>
56
Kenny Roota91203b2012-02-15 15:00:46 -080057#include <cutils/log.h>
58#include <cutils/sockets.h>
59#include <private/android_filesystem_config.h>
60
Kenny Root07438c82012-11-02 15:41:02 -070061#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080062
Riley Spahneaabae92014-06-30 12:39:52 -070063#include <selinux/android.h>
64
Kenny Root96427ba2013-08-16 14:02:41 -070065#include "defaults.h"
66
Kenny Roota91203b2012-02-15 15:00:46 -080067/* KeyStore is a secured storage for key-value pairs. In this implementation,
68 * each file stores one key-value pair. Keys are encoded in file names, and
69 * values are encrypted with checksums. The encryption key is protected by a
70 * user-defined password. To keep things simple, buffers are always larger than
71 * the maximum space we needed, so boundary checks on buffers are omitted. */
72
73#define KEY_SIZE ((NAME_MAX - 15) / 2)
74#define VALUE_SIZE 32768
75#define PASSWORD_SIZE VALUE_SIZE
76
Kenny Root822c3a92012-03-23 16:34:39 -070077
Kenny Root96427ba2013-08-16 14:02:41 -070078struct BIGNUM_Delete {
79 void operator()(BIGNUM* p) const {
80 BN_free(p);
81 }
82};
83typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
84
Kenny Root822c3a92012-03-23 16:34:39 -070085struct BIO_Delete {
86 void operator()(BIO* p) const {
87 BIO_free(p);
88 }
89};
90typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
91
92struct EVP_PKEY_Delete {
93 void operator()(EVP_PKEY* p) const {
94 EVP_PKEY_free(p);
95 }
96};
97typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
98
99struct PKCS8_PRIV_KEY_INFO_Delete {
100 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
101 PKCS8_PRIV_KEY_INFO_free(p);
102 }
103};
104typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
105
106
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700107static int keymaster_device_initialize(keymaster0_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800108 int rc;
109
110 const hw_module_t* mod;
111 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
112 if (rc) {
113 ALOGE("could not find any keystore module");
114 goto out;
115 }
116
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700117 rc = keymaster0_open(mod, dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800118 if (rc) {
119 ALOGE("could not open keymaster device in %s (%s)",
120 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
121 goto out;
122 }
123
124 return 0;
125
126out:
127 *dev = NULL;
128 return rc;
129}
130
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800131static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
132 keymaster::SoftKeymasterDevice* softkeymaster =
133 new keymaster::SoftKeymasterDevice();
134 // SoftKeymasterDevice is designed to make this cast safe.
135 *dev = reinterpret_cast<keymaster1_device_t*>(softkeymaster);
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800136 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800137}
138
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700139static void keymaster_device_release(keymaster0_device_t* dev) {
140 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800141}
142
Kenny Root07438c82012-11-02 15:41:02 -0700143/***************
144 * PERMISSIONS *
145 ***************/
146
147/* Here are the permissions, actions, users, and the main function. */
148typedef enum {
Robin Lee4e865752014-08-19 17:37:55 +0100149 P_TEST = 1 << 0,
150 P_GET = 1 << 1,
151 P_INSERT = 1 << 2,
152 P_DELETE = 1 << 3,
153 P_EXIST = 1 << 4,
154 P_SAW = 1 << 5,
155 P_RESET = 1 << 6,
156 P_PASSWORD = 1 << 7,
157 P_LOCK = 1 << 8,
158 P_UNLOCK = 1 << 9,
159 P_ZERO = 1 << 10,
160 P_SIGN = 1 << 11,
161 P_VERIFY = 1 << 12,
162 P_GRANT = 1 << 13,
163 P_DUPLICATE = 1 << 14,
164 P_CLEAR_UID = 1 << 15,
165 P_RESET_UID = 1 << 16,
166 P_SYNC_UID = 1 << 17,
167 P_PASSWORD_UID = 1 << 18,
Kenny Root07438c82012-11-02 15:41:02 -0700168} perm_t;
169
170static struct user_euid {
171 uid_t uid;
172 uid_t euid;
173} user_euids[] = {
174 {AID_VPN, AID_SYSTEM},
175 {AID_WIFI, AID_SYSTEM},
176 {AID_ROOT, AID_SYSTEM},
177};
178
Riley Spahneaabae92014-06-30 12:39:52 -0700179/* perm_labels associcated with keystore_key SELinux class verbs. */
180const char *perm_labels[] = {
181 "test",
182 "get",
183 "insert",
184 "delete",
185 "exist",
186 "saw",
187 "reset",
188 "password",
189 "lock",
190 "unlock",
191 "zero",
192 "sign",
193 "verify",
194 "grant",
195 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100196 "clear_uid",
197 "reset_uid",
198 "sync_uid",
199 "password_uid",
Riley Spahneaabae92014-06-30 12:39:52 -0700200};
201
Kenny Root07438c82012-11-02 15:41:02 -0700202static struct user_perm {
203 uid_t uid;
204 perm_t perms;
205} user_perms[] = {
206 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
207 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
208 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
209 {AID_ROOT, static_cast<perm_t>(P_GET) },
210};
211
212static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
213 | P_VERIFY);
214
Riley Spahneaabae92014-06-30 12:39:52 -0700215static char *tctx;
216static int ks_is_selinux_enabled;
217
218static const char *get_perm_label(perm_t perm) {
219 unsigned int index = ffs(perm);
220 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
221 return perm_labels[index - 1];
222 } else {
223 ALOGE("Keystore: Failed to retrieve permission label.\n");
224 abort();
225 }
226}
227
Kenny Root655b9582013-04-04 08:37:42 -0700228/**
229 * Returns the app ID (in the Android multi-user sense) for the current
230 * UNIX UID.
231 */
232static uid_t get_app_id(uid_t uid) {
233 return uid % AID_USER;
234}
235
236/**
237 * Returns the user ID (in the Android multi-user sense) for the current
238 * UNIX UID.
239 */
240static uid_t get_user_id(uid_t uid) {
241 return uid / AID_USER;
242}
243
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700244static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700245 if (!ks_is_selinux_enabled) {
246 return true;
247 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000248
Riley Spahneaabae92014-06-30 12:39:52 -0700249 char *sctx = NULL;
250 const char *selinux_class = "keystore_key";
251 const char *str_perm = get_perm_label(perm);
252
253 if (!str_perm) {
254 return false;
255 }
256
257 if (getpidcon(spid, &sctx) != 0) {
258 ALOGE("SELinux: Failed to get source pid context.\n");
259 return false;
260 }
261
262 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
263 NULL) == 0;
264 freecon(sctx);
265 return allowed;
266}
267
268static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700269 // All system users are equivalent for multi-user support.
270 if (get_app_id(uid) == AID_SYSTEM) {
271 uid = AID_SYSTEM;
272 }
273
Kenny Root07438c82012-11-02 15:41:02 -0700274 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
275 struct user_perm user = user_perms[i];
276 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700277 return (user.perms & perm) &&
278 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700279 }
280 }
281
Riley Spahneaabae92014-06-30 12:39:52 -0700282 return (DEFAULT_PERMS & perm) &&
283 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700284}
285
Kenny Root49468902013-03-19 13:41:33 -0700286/**
287 * Returns the UID that the callingUid should act as. This is here for
288 * legacy support of the WiFi and VPN systems and should be removed
289 * when WiFi can operate in its own namespace.
290 */
Kenny Root07438c82012-11-02 15:41:02 -0700291static uid_t get_keystore_euid(uid_t uid) {
292 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
293 struct user_euid user = user_euids[i];
294 if (user.uid == uid) {
295 return user.euid;
296 }
297 }
298
299 return uid;
300}
301
Kenny Root49468902013-03-19 13:41:33 -0700302/**
303 * Returns true if the callingUid is allowed to interact in the targetUid's
304 * namespace.
305 */
306static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
307 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
308 struct user_euid user = user_euids[i];
309 if (user.euid == callingUid && user.uid == targetUid) {
310 return true;
311 }
312 }
313
314 return false;
315}
316
Kenny Root007cb232014-07-30 16:59:42 -0700317/**
318 * Allow the system to perform some privileged tasks that have to do with
319 * system maintenance. This should not be used for any function that uses
320 * the keys in any way (e.g., signing).
321 */
322static bool is_self_or_system(uid_t callingUid, uid_t targetUid) {
323 return callingUid == targetUid || callingUid == AID_SYSTEM;
324}
325
Kenny Roota91203b2012-02-15 15:00:46 -0800326/* Here is the encoding of keys. This is necessary in order to allow arbitrary
327 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
328 * into two bytes. The first byte is one of [+-.] which represents the first
329 * two bits of the character. The second byte encodes the rest of the bits into
330 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
331 * that Base64 cannot be used here due to the need of prefix match on keys. */
332
Kenny Root655b9582013-04-04 08:37:42 -0700333static size_t encode_key_length(const android::String8& keyName) {
334 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
335 size_t length = keyName.length();
336 for (int i = length; i > 0; --i, ++in) {
337 if (*in < '0' || *in > '~') {
338 ++length;
339 }
340 }
341 return length;
342}
343
Kenny Root07438c82012-11-02 15:41:02 -0700344static int encode_key(char* out, const android::String8& keyName) {
345 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
346 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800347 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700348 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800349 *out = '+' + (*in >> 6);
350 *++out = '0' + (*in & 0x3F);
351 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700352 } else {
353 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800354 }
355 }
356 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800357 return length;
358}
359
Kenny Root07438c82012-11-02 15:41:02 -0700360/*
361 * Converts from the "escaped" format on disk to actual name.
362 * This will be smaller than the input string.
363 *
364 * Characters that should combine with the next at the end will be truncated.
365 */
366static size_t decode_key_length(const char* in, size_t length) {
367 size_t outLength = 0;
368
369 for (const char* end = in + length; in < end; in++) {
370 /* This combines with the next character. */
371 if (*in < '0' || *in > '~') {
372 continue;
373 }
374
375 outLength++;
376 }
377 return outLength;
378}
379
380static void decode_key(char* out, const char* in, size_t length) {
381 for (const char* end = in + length; in < end; in++) {
382 if (*in < '0' || *in > '~') {
383 /* Truncate combining characters at the end. */
384 if (in + 1 >= end) {
385 break;
386 }
387
388 *out = (*in++ - '+') << 6;
389 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800390 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700391 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800392 }
393 }
394 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800395}
396
397static size_t readFully(int fd, uint8_t* data, size_t size) {
398 size_t remaining = size;
399 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800400 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800401 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800402 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800403 }
404 data += n;
405 remaining -= n;
406 }
407 return size;
408}
409
410static size_t writeFully(int fd, uint8_t* data, size_t size) {
411 size_t remaining = size;
412 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800413 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
414 if (n < 0) {
415 ALOGW("write failed: %s", strerror(errno));
416 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800417 }
418 data += n;
419 remaining -= n;
420 }
421 return size;
422}
423
424class Entropy {
425public:
426 Entropy() : mRandom(-1) {}
427 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800428 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800429 close(mRandom);
430 }
431 }
432
433 bool open() {
434 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800435 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
436 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800437 ALOGE("open: %s: %s", randomDevice, strerror(errno));
438 return false;
439 }
440 return true;
441 }
442
Kenny Root51878182012-03-13 12:53:19 -0700443 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800444 return (readFully(mRandom, data, size) == size);
445 }
446
447private:
448 int mRandom;
449};
450
451/* Here is the file format. There are two parts in blob.value, the secret and
452 * the description. The secret is stored in ciphertext, and its original size
453 * can be found in blob.length. The description is stored after the secret in
454 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700455 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700456 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800457 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
458 * and decryptBlob(). Thus they should not be accessed from outside. */
459
Kenny Root822c3a92012-03-23 16:34:39 -0700460/* ** Note to future implementors of encryption: **
461 * Currently this is the construction:
462 * metadata || Enc(MD5(data) || data)
463 *
464 * This should be the construction used for encrypting if re-implementing:
465 *
466 * Derive independent keys for encryption and MAC:
467 * Kenc = AES_encrypt(masterKey, "Encrypt")
468 * Kmac = AES_encrypt(masterKey, "MAC")
469 *
470 * Store this:
471 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
472 * HMAC(Kmac, metadata || Enc(data))
473 */
Kenny Roota91203b2012-02-15 15:00:46 -0800474struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700475 uint8_t version;
476 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700477 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800478 uint8_t info;
479 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700480 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800481 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700482 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800483 int32_t length; // in network byte order when encrypted
484 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
485};
486
Kenny Root822c3a92012-03-23 16:34:39 -0700487typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700488 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700489 TYPE_GENERIC = 1,
490 TYPE_MASTER_KEY = 2,
491 TYPE_KEY_PAIR = 3,
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) {
Kenny Roota91203b2012-02-15 15:00:46 -0800500 mBlob.length = valueLength;
501 memcpy(mBlob.value, value, valueLength);
502
503 mBlob.info = infoLength;
504 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700505
Kenny Root07438c82012-11-02 15:41:02 -0700506 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700507 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700508
Kenny Rootee8068b2013-10-07 09:49:15 -0700509 if (type == TYPE_MASTER_KEY) {
510 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
511 } else {
512 mBlob.flags = KEYSTORE_FLAG_NONE;
513 }
Kenny Roota91203b2012-02-15 15:00:46 -0800514 }
515
516 Blob(blob b) {
517 mBlob = b;
518 }
519
520 Blob() {}
521
Kenny Root51878182012-03-13 12:53:19 -0700522 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800523 return mBlob.value;
524 }
525
Kenny Root51878182012-03-13 12:53:19 -0700526 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800527 return mBlob.length;
528 }
529
Kenny Root51878182012-03-13 12:53:19 -0700530 const uint8_t* getInfo() const {
531 return mBlob.value + mBlob.length;
532 }
533
534 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800535 return mBlob.info;
536 }
537
Kenny Root822c3a92012-03-23 16:34:39 -0700538 uint8_t getVersion() const {
539 return mBlob.version;
540 }
541
Kenny Rootf9119d62013-04-03 09:22:15 -0700542 bool isEncrypted() const {
543 if (mBlob.version < 2) {
544 return true;
545 }
546
547 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
548 }
549
550 void setEncrypted(bool encrypted) {
551 if (encrypted) {
552 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
553 } else {
554 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
555 }
556 }
557
Kenny Root17208e02013-09-04 13:56:03 -0700558 bool isFallback() const {
559 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
560 }
561
562 void setFallback(bool fallback) {
563 if (fallback) {
564 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
565 } else {
566 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
567 }
568 }
569
Kenny Root822c3a92012-03-23 16:34:39 -0700570 void setVersion(uint8_t version) {
571 mBlob.version = version;
572 }
573
574 BlobType getType() const {
575 return BlobType(mBlob.type);
576 }
577
578 void setType(BlobType type) {
579 mBlob.type = uint8_t(type);
580 }
581
Kenny Rootf9119d62013-04-03 09:22:15 -0700582 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
583 ALOGV("writing blob %s", filename);
584 if (isEncrypted()) {
585 if (state != STATE_NO_ERROR) {
586 ALOGD("couldn't insert encrypted blob while not unlocked");
587 return LOCKED;
588 }
589
590 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
591 ALOGW("Could not read random data for: %s", filename);
592 return SYSTEM_ERROR;
593 }
Kenny Roota91203b2012-02-15 15:00:46 -0800594 }
595
596 // data includes the value and the value's length
597 size_t dataLength = mBlob.length + sizeof(mBlob.length);
598 // pad data to the AES_BLOCK_SIZE
599 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
600 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
601 // encrypted data includes the digest value
602 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
603 // move info after space for padding
604 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
605 // zero padding area
606 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
607
608 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800609
Kenny Rootf9119d62013-04-03 09:22:15 -0700610 if (isEncrypted()) {
611 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800612
Kenny Rootf9119d62013-04-03 09:22:15 -0700613 uint8_t vector[AES_BLOCK_SIZE];
614 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
615 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
616 aes_key, vector, AES_ENCRYPT);
617 }
618
Kenny Roota91203b2012-02-15 15:00:46 -0800619 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
620 size_t fileLength = encryptedLength + headerLength + mBlob.info;
621
622 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800623 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
624 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
625 if (out < 0) {
626 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800627 return SYSTEM_ERROR;
628 }
629 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
630 if (close(out) != 0) {
631 return SYSTEM_ERROR;
632 }
633 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800634 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800635 unlink(tmpFileName);
636 return SYSTEM_ERROR;
637 }
Kenny Root150ca932012-11-14 14:29:02 -0800638 if (rename(tmpFileName, filename) == -1) {
639 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
640 return SYSTEM_ERROR;
641 }
642 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800643 }
644
Kenny Rootf9119d62013-04-03 09:22:15 -0700645 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
646 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800647 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
648 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800649 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
650 }
651 // fileLength may be less than sizeof(mBlob) since the in
652 // memory version has extra padding to tolerate rounding up to
653 // the AES_BLOCK_SIZE
654 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
655 if (close(in) != 0) {
656 return SYSTEM_ERROR;
657 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700658
659 if (isEncrypted() && (state != STATE_NO_ERROR)) {
660 return LOCKED;
661 }
662
Kenny Roota91203b2012-02-15 15:00:46 -0800663 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
664 if (fileLength < headerLength) {
665 return VALUE_CORRUPTED;
666 }
667
668 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700669 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800670 return VALUE_CORRUPTED;
671 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700672
673 ssize_t digestedLength;
674 if (isEncrypted()) {
675 if (encryptedLength % AES_BLOCK_SIZE != 0) {
676 return VALUE_CORRUPTED;
677 }
678
679 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
680 mBlob.vector, AES_DECRYPT);
681 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
682 uint8_t computedDigest[MD5_DIGEST_LENGTH];
683 MD5(mBlob.digested, digestedLength, computedDigest);
684 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
685 return VALUE_CORRUPTED;
686 }
687 } else {
688 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800689 }
690
691 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
692 mBlob.length = ntohl(mBlob.length);
693 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
694 return VALUE_CORRUPTED;
695 }
696 if (mBlob.info != 0) {
697 // move info from after padding to after data
698 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
699 }
Kenny Root07438c82012-11-02 15:41:02 -0700700 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800701 }
702
703private:
704 struct blob mBlob;
705};
706
Kenny Root655b9582013-04-04 08:37:42 -0700707class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800708public:
Kenny Root655b9582013-04-04 08:37:42 -0700709 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
710 asprintf(&mUserDir, "user_%u", mUserId);
711 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
712 }
713
714 ~UserState() {
715 free(mUserDir);
716 free(mMasterKeyFile);
717 }
718
719 bool initialize() {
720 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
721 ALOGE("Could not create directory '%s'", mUserDir);
722 return false;
723 }
724
725 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800726 setState(STATE_LOCKED);
727 } else {
728 setState(STATE_UNINITIALIZED);
729 }
Kenny Root70e3a862012-02-15 17:20:23 -0800730
Kenny Root655b9582013-04-04 08:37:42 -0700731 return true;
732 }
733
734 uid_t getUserId() const {
735 return mUserId;
736 }
737
738 const char* getUserDirName() const {
739 return mUserDir;
740 }
741
742 const char* getMasterKeyFileName() const {
743 return mMasterKeyFile;
744 }
745
746 void setState(State state) {
747 mState = state;
748 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
749 mRetry = MAX_RETRY;
750 }
Kenny Roota91203b2012-02-15 15:00:46 -0800751 }
752
Kenny Root51878182012-03-13 12:53:19 -0700753 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800754 return mState;
755 }
756
Kenny Root51878182012-03-13 12:53:19 -0700757 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800758 return mRetry;
759 }
760
Kenny Root655b9582013-04-04 08:37:42 -0700761 void zeroizeMasterKeysInMemory() {
762 memset(mMasterKey, 0, sizeof(mMasterKey));
763 memset(mSalt, 0, sizeof(mSalt));
764 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
765 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800766 }
767
Kenny Root655b9582013-04-04 08:37:42 -0700768 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
769 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800770 return SYSTEM_ERROR;
771 }
Kenny Root655b9582013-04-04 08:37:42 -0700772 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800773 if (response != NO_ERROR) {
774 return response;
775 }
776 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700777 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800778 }
779
Robin Lee4e865752014-08-19 17:37:55 +0100780 ResponseCode copyMasterKey(UserState* src) {
781 if (mState != STATE_UNINITIALIZED) {
782 return ::SYSTEM_ERROR;
783 }
784 if (src->getState() != STATE_NO_ERROR) {
785 return ::SYSTEM_ERROR;
786 }
787 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
788 setupMasterKeys();
789 return ::NO_ERROR;
790 }
791
Kenny Root655b9582013-04-04 08:37:42 -0700792 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800793 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
794 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
795 AES_KEY passwordAesKey;
796 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700797 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700798 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800799 }
800
Kenny Root655b9582013-04-04 08:37:42 -0700801 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
802 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800803 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800804 return SYSTEM_ERROR;
805 }
806
807 // we read the raw blob to just to get the salt to generate
808 // the AES key, then we create the Blob to use with decryptBlob
809 blob rawBlob;
810 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
811 if (close(in) != 0) {
812 return SYSTEM_ERROR;
813 }
814 // find salt at EOF if present, otherwise we have an old file
815 uint8_t* salt;
816 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
817 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
818 } else {
819 salt = NULL;
820 }
821 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
822 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
823 AES_KEY passwordAesKey;
824 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
825 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700826 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
827 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800828 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700829 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800830 }
831 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
832 // if salt was missing, generate one and write a new master key file with the salt.
833 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700834 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800835 return SYSTEM_ERROR;
836 }
Kenny Root655b9582013-04-04 08:37:42 -0700837 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800838 }
839 if (response == NO_ERROR) {
840 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
841 setupMasterKeys();
842 }
843 return response;
844 }
845 if (mRetry <= 0) {
846 reset();
847 return UNINITIALIZED;
848 }
849 --mRetry;
850 switch (mRetry) {
851 case 0: return WRONG_PASSWORD_0;
852 case 1: return WRONG_PASSWORD_1;
853 case 2: return WRONG_PASSWORD_2;
854 case 3: return WRONG_PASSWORD_3;
855 default: return WRONG_PASSWORD_3;
856 }
857 }
858
Kenny Root655b9582013-04-04 08:37:42 -0700859 AES_KEY* getEncryptionKey() {
860 return &mMasterKeyEncryption;
861 }
862
863 AES_KEY* getDecryptionKey() {
864 return &mMasterKeyDecryption;
865 }
866
Kenny Roota91203b2012-02-15 15:00:46 -0800867 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700868 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800869 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700870 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800871 return false;
872 }
Kenny Root655b9582013-04-04 08:37:42 -0700873
874 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800875 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700876 // We only care about files.
877 if (file->d_type != DT_REG) {
878 continue;
879 }
880
881 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700882 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700883 continue;
884 }
885
886 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800887 }
888 closedir(dir);
889 return true;
890 }
891
Kenny Root655b9582013-04-04 08:37:42 -0700892private:
893 static const int MASTER_KEY_SIZE_BYTES = 16;
894 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
895
896 static const int MAX_RETRY = 4;
897 static const size_t SALT_SIZE = 16;
898
899 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
900 uint8_t* salt) {
901 size_t saltSize;
902 if (salt != NULL) {
903 saltSize = SALT_SIZE;
904 } else {
905 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
906 salt = (uint8_t*) "keystore";
907 // sizeof = 9, not strlen = 8
908 saltSize = sizeof("keystore");
909 }
910
911 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
912 saltSize, 8192, keySize, key);
913 }
914
915 bool generateSalt(Entropy* entropy) {
916 return entropy->generate_random_data(mSalt, sizeof(mSalt));
917 }
918
919 bool generateMasterKey(Entropy* entropy) {
920 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
921 return false;
922 }
923 if (!generateSalt(entropy)) {
924 return false;
925 }
926 return true;
927 }
928
929 void setupMasterKeys() {
930 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
931 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
932 setState(STATE_NO_ERROR);
933 }
934
935 uid_t mUserId;
936
937 char* mUserDir;
938 char* mMasterKeyFile;
939
940 State mState;
941 int8_t mRetry;
942
943 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
944 uint8_t mSalt[SALT_SIZE];
945
946 AES_KEY mMasterKeyEncryption;
947 AES_KEY mMasterKeyDecryption;
948};
949
950typedef struct {
951 uint32_t uid;
952 const uint8_t* filename;
953} grant_t;
954
955class KeyStore {
956public:
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800957 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700958 : mEntropy(entropy)
959 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800960 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700961 {
962 memset(&mMetaData, '\0', sizeof(mMetaData));
963 }
964
965 ~KeyStore() {
966 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
967 it != mGrants.end(); it++) {
968 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700969 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800970 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700971
972 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
973 it != mMasterKeys.end(); it++) {
974 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700975 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800976 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700977 }
978
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800979 /**
980 * Depending on the hardware keymaster version is this may return a
981 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
982 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
983 * be guarded by a check on the device's version.
984 */
985 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700986 return mDevice;
987 }
988
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800989 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800990 return mFallbackDevice;
991 }
992
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800993 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800994 return blob.isFallback() ? mFallbackDevice: mDevice;
995 }
996
Kenny Root655b9582013-04-04 08:37:42 -0700997 ResponseCode initialize() {
998 readMetaData();
999 if (upgradeKeystore()) {
1000 writeMetaData();
1001 }
1002
1003 return ::NO_ERROR;
1004 }
1005
1006 State getState(uid_t uid) {
1007 return getUserState(uid)->getState();
1008 }
1009
1010 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
1011 UserState* userState = getUserState(uid);
1012 return userState->initialize(pw, mEntropy);
1013 }
1014
Robin Lee4e865752014-08-19 17:37:55 +01001015 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
1016 UserState *userState = getUserState(uid);
1017 UserState *initState = getUserState(src);
1018 return userState->copyMasterKey(initState);
1019 }
1020
Kenny Root655b9582013-04-04 08:37:42 -07001021 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001022 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001023 return userState->writeMasterKey(pw, mEntropy);
1024 }
1025
1026 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001027 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001028 return userState->readMasterKey(pw, mEntropy);
1029 }
1030
1031 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001032 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001033 encode_key(encoded, keyName);
1034 return android::String8(encoded);
1035 }
1036
1037 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001038 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001039 encode_key(encoded, keyName);
1040 return android::String8::format("%u_%s", uid, encoded);
1041 }
1042
1043 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001044 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001045 encode_key(encoded, keyName);
1046 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1047 encoded);
1048 }
1049
1050 bool reset(uid_t uid) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001051 android::String8 prefix("");
1052 android::Vector<android::String16> aliases;
1053 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1054 return ::SYSTEM_ERROR;
1055 }
1056
Kenny Root655b9582013-04-04 08:37:42 -07001057 UserState* userState = getUserState(uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001058 for (uint32_t i = 0; i < aliases.size(); i++) {
1059 android::String8 filename(aliases[i]);
1060 filename = android::String8::format("%s/%s", userState->getUserDirName(),
1061 getKeyName(filename).string());
1062 del(filename, ::TYPE_ANY, uid);
1063 }
1064
Kenny Root655b9582013-04-04 08:37:42 -07001065 userState->zeroizeMasterKeysInMemory();
1066 userState->setState(STATE_UNINITIALIZED);
1067 return userState->reset();
1068 }
1069
1070 bool isEmpty(uid_t uid) const {
1071 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001072 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001073 return true;
1074 }
1075
1076 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001077 if (!dir) {
1078 return true;
1079 }
Kenny Root31e27462014-09-10 11:28:03 -07001080
Kenny Roota91203b2012-02-15 15:00:46 -08001081 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001082 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001083 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001084 // We only care about files.
1085 if (file->d_type != DT_REG) {
1086 continue;
1087 }
1088
1089 // Skip anything that starts with a "."
1090 if (file->d_name[0] == '.') {
1091 continue;
1092 }
1093
Kenny Root31e27462014-09-10 11:28:03 -07001094 result = false;
1095 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001096 }
1097 closedir(dir);
1098 return result;
1099 }
1100
Kenny Root655b9582013-04-04 08:37:42 -07001101 void lock(uid_t uid) {
1102 UserState* userState = getUserState(uid);
1103 userState->zeroizeMasterKeysInMemory();
1104 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001105 }
1106
Kenny Root655b9582013-04-04 08:37:42 -07001107 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1108 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001109 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1110 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001111 if (rc != NO_ERROR) {
1112 return rc;
1113 }
1114
1115 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001116 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001117 /* If we upgrade the key, we need to write it to disk again. Then
1118 * it must be read it again since the blob is encrypted each time
1119 * it's written.
1120 */
Kenny Root655b9582013-04-04 08:37:42 -07001121 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1122 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001123 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1124 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001125 return rc;
1126 }
1127 }
Kenny Root822c3a92012-03-23 16:34:39 -07001128 }
1129
Kenny Root17208e02013-09-04 13:56:03 -07001130 /*
1131 * This will upgrade software-backed keys to hardware-backed keys when
1132 * the HAL for the device supports the newer key types.
1133 */
1134 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1135 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1136 && keyBlob->isFallback()) {
1137 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1138 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1139
1140 // The HAL allowed the import, reget the key to have the "fresh"
1141 // version.
1142 if (imported == NO_ERROR) {
1143 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1144 }
1145 }
1146
Kenny Rootd53bc922013-03-21 14:10:15 -07001147 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001148 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1149 return KEY_NOT_FOUND;
1150 }
1151
1152 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001153 }
1154
Kenny Root655b9582013-04-04 08:37:42 -07001155 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1156 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001157 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1158 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001159 }
1160
Robin Lee4b84fdc2014-09-24 11:56:57 +01001161 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1162 Blob keyBlob;
1163 ResponseCode rc = get(filename, &keyBlob, type, uid);
1164 if (rc != ::NO_ERROR) {
1165 return rc;
1166 }
1167
1168 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1169 // A device doesn't have to implement delete_keypair.
1170 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1171 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1172 rc = ::SYSTEM_ERROR;
1173 }
1174 }
1175 }
1176 if (rc != ::NO_ERROR) {
1177 return rc;
1178 }
1179
1180 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1181 }
1182
1183 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1184 uid_t uid) {
1185
1186 UserState* userState = getUserState(uid);
1187 size_t n = prefix.length();
1188
1189 DIR* dir = opendir(userState->getUserDirName());
1190 if (!dir) {
1191 ALOGW("can't open directory for user: %s", strerror(errno));
1192 return ::SYSTEM_ERROR;
1193 }
1194
1195 struct dirent* file;
1196 while ((file = readdir(dir)) != NULL) {
1197 // We only care about files.
1198 if (file->d_type != DT_REG) {
1199 continue;
1200 }
1201
1202 // Skip anything that starts with a "."
1203 if (file->d_name[0] == '.') {
1204 continue;
1205 }
1206
1207 if (!strncmp(prefix.string(), file->d_name, n)) {
1208 const char* p = &file->d_name[n];
1209 size_t plen = strlen(p);
1210
1211 size_t extra = decode_key_length(p, plen);
1212 char *match = (char*) malloc(extra + 1);
1213 if (match != NULL) {
1214 decode_key(match, p, plen);
1215 matches->push(android::String16(match, extra));
1216 free(match);
1217 } else {
1218 ALOGW("could not allocate match of size %zd", extra);
1219 }
1220 }
1221 }
1222 closedir(dir);
1223 return ::NO_ERROR;
1224 }
1225
Kenny Root07438c82012-11-02 15:41:02 -07001226 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001227 const grant_t* existing = getGrant(filename, granteeUid);
1228 if (existing == NULL) {
1229 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001230 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001231 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001232 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001233 }
1234 }
1235
Kenny Root07438c82012-11-02 15:41:02 -07001236 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001237 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1238 it != mGrants.end(); it++) {
1239 grant_t* grant = *it;
1240 if (grant->uid == granteeUid
1241 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1242 mGrants.erase(it);
1243 return true;
1244 }
Kenny Root70e3a862012-02-15 17:20:23 -08001245 }
Kenny Root70e3a862012-02-15 17:20:23 -08001246 return false;
1247 }
1248
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001249 bool hasGrant(const char* filename, const uid_t uid) const {
1250 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001251 }
1252
Kenny Rootf9119d62013-04-03 09:22:15 -07001253 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1254 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001255 uint8_t* data;
1256 size_t dataLength;
1257 int rc;
1258
1259 if (mDevice->import_keypair == NULL) {
1260 ALOGE("Keymaster doesn't support import!");
1261 return SYSTEM_ERROR;
1262 }
1263
Kenny Root17208e02013-09-04 13:56:03 -07001264 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001265 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001266 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001267 /*
1268 * Maybe the device doesn't support this type of key. Try to use the
1269 * software fallback keymaster implementation. This is a little bit
1270 * lazier than checking the PKCS#8 key type, but the software
1271 * implementation will do that anyway.
1272 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001273 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001274 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001275
1276 if (rc) {
1277 ALOGE("Error while importing keypair: %d", rc);
1278 return SYSTEM_ERROR;
1279 }
Kenny Root822c3a92012-03-23 16:34:39 -07001280 }
1281
1282 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1283 free(data);
1284
Kenny Rootf9119d62013-04-03 09:22:15 -07001285 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001286 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001287
Kenny Root655b9582013-04-04 08:37:42 -07001288 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001289 }
1290
Kenny Root1b0e3932013-09-05 13:06:32 -07001291 bool isHardwareBacked(const android::String16& keyType) const {
1292 if (mDevice == NULL) {
1293 ALOGW("can't get keymaster device");
1294 return false;
1295 }
1296
1297 if (sRSAKeyType == keyType) {
1298 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1299 } else {
1300 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1301 && (mDevice->common.module->module_api_version
1302 >= KEYMASTER_MODULE_API_VERSION_0_2);
1303 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001304 }
1305
Kenny Root655b9582013-04-04 08:37:42 -07001306 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1307 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001308 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001309
1310 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1311 if (responseCode == NO_ERROR) {
1312 return responseCode;
1313 }
1314
1315 // If this is one of the legacy UID->UID mappings, use it.
1316 uid_t euid = get_keystore_euid(uid);
1317 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001318 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001319 responseCode = get(filepath8.string(), keyBlob, type, uid);
1320 if (responseCode == NO_ERROR) {
1321 return responseCode;
1322 }
1323 }
1324
1325 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001326 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001327 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001328 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001329 if (end[0] != '_' || end[1] == 0) {
1330 return KEY_NOT_FOUND;
1331 }
Kenny Root86b16e82013-09-09 11:15:54 -07001332 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1333 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001334 if (!hasGrant(filepath8.string(), uid)) {
1335 return responseCode;
1336 }
1337
1338 // It is a granted key. Try to load it.
1339 return get(filepath8.string(), keyBlob, type, uid);
1340 }
1341
1342 /**
1343 * Returns any existing UserState or creates it if it doesn't exist.
1344 */
1345 UserState* getUserState(uid_t uid) {
1346 uid_t userId = get_user_id(uid);
1347
1348 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1349 it != mMasterKeys.end(); it++) {
1350 UserState* state = *it;
1351 if (state->getUserId() == userId) {
1352 return state;
1353 }
1354 }
1355
1356 UserState* userState = new UserState(userId);
1357 if (!userState->initialize()) {
1358 /* There's not much we can do if initialization fails. Trying to
1359 * unlock the keystore for that user will fail as well, so any
1360 * subsequent request for this user will just return SYSTEM_ERROR.
1361 */
1362 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1363 }
1364 mMasterKeys.add(userState);
1365 return userState;
1366 }
1367
1368 /**
1369 * Returns NULL if the UserState doesn't already exist.
1370 */
1371 const UserState* getUserState(uid_t uid) const {
1372 uid_t userId = get_user_id(uid);
1373
1374 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1375 it != mMasterKeys.end(); it++) {
1376 UserState* state = *it;
1377 if (state->getUserId() == userId) {
1378 return state;
1379 }
1380 }
1381
1382 return NULL;
1383 }
1384
Kenny Roota91203b2012-02-15 15:00:46 -08001385private:
Kenny Root655b9582013-04-04 08:37:42 -07001386 static const char* sOldMasterKey;
1387 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001388 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001389 Entropy* mEntropy;
1390
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001391 keymaster1_device_t* mDevice;
1392 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001393
Kenny Root655b9582013-04-04 08:37:42 -07001394 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001395
Kenny Root655b9582013-04-04 08:37:42 -07001396 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001397
Kenny Root655b9582013-04-04 08:37:42 -07001398 typedef struct {
1399 uint32_t version;
1400 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001401
Kenny Root655b9582013-04-04 08:37:42 -07001402 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001403
Kenny Root655b9582013-04-04 08:37:42 -07001404 const grant_t* getGrant(const char* filename, uid_t uid) const {
1405 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1406 it != mGrants.end(); it++) {
1407 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001408 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001409 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001410 return grant;
1411 }
1412 }
Kenny Root70e3a862012-02-15 17:20:23 -08001413 return NULL;
1414 }
1415
Kenny Root822c3a92012-03-23 16:34:39 -07001416 /**
1417 * Upgrade code. This will upgrade the key from the current version
1418 * to whatever is newest.
1419 */
Kenny Root655b9582013-04-04 08:37:42 -07001420 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1421 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001422 bool updated = false;
1423 uint8_t version = oldVersion;
1424
1425 /* From V0 -> V1: All old types were unknown */
1426 if (version == 0) {
1427 ALOGV("upgrading to version 1 and setting type %d", type);
1428
1429 blob->setType(type);
1430 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001431 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001432 }
1433 version = 1;
1434 updated = true;
1435 }
1436
Kenny Rootf9119d62013-04-03 09:22:15 -07001437 /* From V1 -> V2: All old keys were encrypted */
1438 if (version == 1) {
1439 ALOGV("upgrading to version 2");
1440
1441 blob->setEncrypted(true);
1442 version = 2;
1443 updated = true;
1444 }
1445
Kenny Root822c3a92012-03-23 16:34:39 -07001446 /*
1447 * If we've updated, set the key blob to the right version
1448 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001449 */
Kenny Root822c3a92012-03-23 16:34:39 -07001450 if (updated) {
1451 ALOGV("updated and writing file %s", filename);
1452 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001453 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001454
1455 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001456 }
1457
1458 /**
1459 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1460 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1461 * Then it overwrites the original blob with the new blob
1462 * format that is returned from the keymaster.
1463 */
Kenny Root655b9582013-04-04 08:37:42 -07001464 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001465 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1466 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1467 if (b.get() == NULL) {
1468 ALOGE("Problem instantiating BIO");
1469 return SYSTEM_ERROR;
1470 }
1471
1472 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1473 if (pkey.get() == NULL) {
1474 ALOGE("Couldn't read old PEM file");
1475 return SYSTEM_ERROR;
1476 }
1477
1478 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1479 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1480 if (len < 0) {
1481 ALOGE("Couldn't measure PKCS#8 length");
1482 return SYSTEM_ERROR;
1483 }
1484
Kenny Root70c98892013-02-07 09:10:36 -08001485 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1486 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001487 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1488 ALOGE("Couldn't convert to PKCS#8");
1489 return SYSTEM_ERROR;
1490 }
1491
Kenny Rootf9119d62013-04-03 09:22:15 -07001492 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1493 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001494 if (rc != NO_ERROR) {
1495 return rc;
1496 }
1497
Kenny Root655b9582013-04-04 08:37:42 -07001498 return get(filename, blob, TYPE_KEY_PAIR, uid);
1499 }
1500
1501 void readMetaData() {
1502 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1503 if (in < 0) {
1504 return;
1505 }
1506 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1507 if (fileLength != sizeof(mMetaData)) {
1508 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1509 sizeof(mMetaData));
1510 }
1511 close(in);
1512 }
1513
1514 void writeMetaData() {
1515 const char* tmpFileName = ".metadata.tmp";
1516 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1517 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1518 if (out < 0) {
1519 ALOGE("couldn't write metadata file: %s", strerror(errno));
1520 return;
1521 }
1522 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1523 if (fileLength != sizeof(mMetaData)) {
1524 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1525 sizeof(mMetaData));
1526 }
1527 close(out);
1528 rename(tmpFileName, sMetaDataFile);
1529 }
1530
1531 bool upgradeKeystore() {
1532 bool upgraded = false;
1533
1534 if (mMetaData.version == 0) {
1535 UserState* userState = getUserState(0);
1536
1537 // Initialize first so the directory is made.
1538 userState->initialize();
1539
1540 // Migrate the old .masterkey file to user 0.
1541 if (access(sOldMasterKey, R_OK) == 0) {
1542 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1543 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1544 return false;
1545 }
1546 }
1547
1548 // Initialize again in case we had a key.
1549 userState->initialize();
1550
1551 // Try to migrate existing keys.
1552 DIR* dir = opendir(".");
1553 if (!dir) {
1554 // Give up now; maybe we can upgrade later.
1555 ALOGE("couldn't open keystore's directory; something is wrong");
1556 return false;
1557 }
1558
1559 struct dirent* file;
1560 while ((file = readdir(dir)) != NULL) {
1561 // We only care about files.
1562 if (file->d_type != DT_REG) {
1563 continue;
1564 }
1565
1566 // Skip anything that starts with a "."
1567 if (file->d_name[0] == '.') {
1568 continue;
1569 }
1570
1571 // Find the current file's user.
1572 char* end;
1573 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1574 if (end[0] != '_' || end[1] == 0) {
1575 continue;
1576 }
1577 UserState* otherUser = getUserState(thisUid);
1578 if (otherUser->getUserId() != 0) {
1579 unlinkat(dirfd(dir), file->d_name, 0);
1580 }
1581
1582 // Rename the file into user directory.
1583 DIR* otherdir = opendir(otherUser->getUserDirName());
1584 if (otherdir == NULL) {
1585 ALOGW("couldn't open user directory for rename");
1586 continue;
1587 }
1588 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1589 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1590 }
1591 closedir(otherdir);
1592 }
1593 closedir(dir);
1594
1595 mMetaData.version = 1;
1596 upgraded = true;
1597 }
1598
1599 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001600 }
Kenny Roota91203b2012-02-15 15:00:46 -08001601};
1602
Kenny Root655b9582013-04-04 08:37:42 -07001603const char* KeyStore::sOldMasterKey = ".masterkey";
1604const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001605
Kenny Root1b0e3932013-09-05 13:06:32 -07001606const android::String16 KeyStore::sRSAKeyType("RSA");
1607
Kenny Root07438c82012-11-02 15:41:02 -07001608namespace android {
1609class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1610public:
1611 KeyStoreProxy(KeyStore* keyStore)
1612 : mKeyStore(keyStore)
1613 {
Kenny Roota91203b2012-02-15 15:00:46 -08001614 }
Kenny Roota91203b2012-02-15 15:00:46 -08001615
Kenny Root07438c82012-11-02 15:41:02 -07001616 void binderDied(const wp<IBinder>&) {
1617 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001618 }
Kenny Roota91203b2012-02-15 15:00:46 -08001619
Kenny Root07438c82012-11-02 15:41:02 -07001620 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001621 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001622 pid_t spid = IPCThreadState::self()->getCallingPid();
1623 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001624 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001625 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001626 }
Kenny Roota91203b2012-02-15 15:00:46 -08001627
Kenny Root655b9582013-04-04 08:37:42 -07001628 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001629 }
1630
Kenny Root07438c82012-11-02 15:41:02 -07001631 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001632 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001633 pid_t spid = IPCThreadState::self()->getCallingPid();
1634 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001635 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001636 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001637 }
Kenny Root07438c82012-11-02 15:41:02 -07001638
Kenny Root07438c82012-11-02 15:41:02 -07001639 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001640 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001641
Kenny Root655b9582013-04-04 08:37:42 -07001642 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001643 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001644 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001645 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001646 *item = NULL;
1647 *itemLength = 0;
1648 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001649 }
Kenny Roota91203b2012-02-15 15:00:46 -08001650
Kenny Root07438c82012-11-02 15:41:02 -07001651 *item = (uint8_t*) malloc(keyBlob.getLength());
1652 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1653 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001654
Kenny Root07438c82012-11-02 15:41:02 -07001655 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001656 }
1657
Kenny Rootf9119d62013-04-03 09:22:15 -07001658 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1659 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001660 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001661 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001662 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001663 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001664 return ::PERMISSION_DENIED;
1665 }
Kenny Root07438c82012-11-02 15:41:02 -07001666
Kenny Rootf9119d62013-04-03 09:22:15 -07001667 State state = mKeyStore->getState(callingUid);
1668 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1669 ALOGD("calling get in state: %d", state);
1670 return state;
1671 }
1672
Kenny Root49468902013-03-19 13:41:33 -07001673 if (targetUid == -1) {
1674 targetUid = callingUid;
1675 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001676 return ::PERMISSION_DENIED;
1677 }
1678
Kenny Root07438c82012-11-02 15:41:02 -07001679 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001680 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001681
1682 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001683 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1684
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001685 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001686 }
1687
Kenny Root49468902013-03-19 13:41:33 -07001688 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001689 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001690 pid_t spid = IPCThreadState::self()->getCallingPid();
1691 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001692 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001693 return ::PERMISSION_DENIED;
1694 }
Kenny Root70e3a862012-02-15 17:20:23 -08001695
Kenny Root49468902013-03-19 13:41:33 -07001696 if (targetUid == -1) {
1697 targetUid = callingUid;
1698 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001699 return ::PERMISSION_DENIED;
1700 }
1701
Kenny Root07438c82012-11-02 15:41:02 -07001702 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001703 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01001704 return mKeyStore->del(filename.string(), ::TYPE_GENERIC, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001705 }
1706
Kenny Root49468902013-03-19 13:41:33 -07001707 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001708 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001709 pid_t spid = IPCThreadState::self()->getCallingPid();
1710 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001711 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001712 return ::PERMISSION_DENIED;
1713 }
Kenny Root70e3a862012-02-15 17:20:23 -08001714
Kenny Root49468902013-03-19 13:41:33 -07001715 if (targetUid == -1) {
1716 targetUid = callingUid;
1717 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001718 return ::PERMISSION_DENIED;
1719 }
1720
Kenny Root07438c82012-11-02 15:41:02 -07001721 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001722 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001723
Kenny Root655b9582013-04-04 08:37:42 -07001724 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001725 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1726 }
1727 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001728 }
1729
Kenny Root49468902013-03-19 13:41:33 -07001730 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001731 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001732 pid_t spid = IPCThreadState::self()->getCallingPid();
1733 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001734 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001735 return ::PERMISSION_DENIED;
1736 }
Kenny Root70e3a862012-02-15 17:20:23 -08001737
Kenny Root49468902013-03-19 13:41:33 -07001738 if (targetUid == -1) {
1739 targetUid = callingUid;
1740 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001741 return ::PERMISSION_DENIED;
1742 }
1743
Kenny Root07438c82012-11-02 15:41:02 -07001744 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001745 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001746
Robin Lee4b84fdc2014-09-24 11:56:57 +01001747 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1748 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001749 }
Kenny Root07438c82012-11-02 15:41:02 -07001750 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001751 }
1752
Kenny Root07438c82012-11-02 15:41:02 -07001753 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001754 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001755 pid_t spid = IPCThreadState::self()->getCallingPid();
1756 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001757 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001758 return ::PERMISSION_DENIED;
1759 }
1760
Robin Lee4b84fdc2014-09-24 11:56:57 +01001761 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001762 }
1763
Kenny Root07438c82012-11-02 15:41:02 -07001764 /*
1765 * Here is the history. To improve the security, the parameters to generate the
1766 * master key has been changed. To make a seamless transition, we update the
1767 * file using the same password when the user unlock it for the first time. If
1768 * any thing goes wrong during the transition, the new file will not overwrite
1769 * the old one. This avoids permanent damages of the existing data.
1770 */
1771 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001772 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001773 pid_t spid = IPCThreadState::self()->getCallingPid();
1774 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001775 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001776 return ::PERMISSION_DENIED;
1777 }
Kenny Root70e3a862012-02-15 17:20:23 -08001778
Kenny Root07438c82012-11-02 15:41:02 -07001779 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001780
Kenny Root655b9582013-04-04 08:37:42 -07001781 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001782 case ::STATE_UNINITIALIZED: {
1783 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001784 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001785 }
1786 case ::STATE_NO_ERROR: {
1787 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001788 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001789 }
1790 case ::STATE_LOCKED: {
1791 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001792 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001793 }
1794 }
1795 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001796 }
1797
Kenny Root07438c82012-11-02 15:41:02 -07001798 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001799 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001800 pid_t spid = IPCThreadState::self()->getCallingPid();
1801 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001802 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001803 return ::PERMISSION_DENIED;
1804 }
Kenny Root70e3a862012-02-15 17:20:23 -08001805
Kenny Root655b9582013-04-04 08:37:42 -07001806 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001807 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001808 ALOGD("calling lock in state: %d", state);
1809 return state;
1810 }
1811
Kenny Root655b9582013-04-04 08:37:42 -07001812 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001813 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001814 }
1815
Kenny Root07438c82012-11-02 15:41:02 -07001816 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001817 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001818 pid_t spid = IPCThreadState::self()->getCallingPid();
1819 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001820 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001821 return ::PERMISSION_DENIED;
1822 }
1823
Kenny Root655b9582013-04-04 08:37:42 -07001824 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001825 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001826 ALOGD("calling unlock when not locked");
1827 return state;
1828 }
1829
1830 const String8 password8(pw);
1831 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001832 }
1833
Kenny Root07438c82012-11-02 15:41:02 -07001834 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001835 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001836 pid_t spid = IPCThreadState::self()->getCallingPid();
1837 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001838 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001839 return -1;
1840 }
Kenny Root70e3a862012-02-15 17:20:23 -08001841
Kenny Root655b9582013-04-04 08:37:42 -07001842 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001843 }
1844
Kenny Root96427ba2013-08-16 14:02:41 -07001845 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1846 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001847 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001848 pid_t spid = IPCThreadState::self()->getCallingPid();
1849 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001850 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001851 return ::PERMISSION_DENIED;
1852 }
Kenny Root70e3a862012-02-15 17:20:23 -08001853
Kenny Root49468902013-03-19 13:41:33 -07001854 if (targetUid == -1) {
1855 targetUid = callingUid;
1856 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001857 return ::PERMISSION_DENIED;
1858 }
1859
Kenny Root655b9582013-04-04 08:37:42 -07001860 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001861 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1862 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001863 return state;
1864 }
Kenny Root70e3a862012-02-15 17:20:23 -08001865
Kenny Root07438c82012-11-02 15:41:02 -07001866 uint8_t* data;
1867 size_t dataLength;
1868 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001869 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001870
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001871 const keymaster1_device_t* device = mKeyStore->getDevice();
1872 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001873 if (device == NULL) {
1874 return ::SYSTEM_ERROR;
1875 }
1876
1877 if (device->generate_keypair == NULL) {
1878 return ::SYSTEM_ERROR;
1879 }
1880
Kenny Root17208e02013-09-04 13:56:03 -07001881 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001882 keymaster_dsa_keygen_params_t dsa_params;
1883 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001884
Kenny Root96427ba2013-08-16 14:02:41 -07001885 if (keySize == -1) {
1886 keySize = DSA_DEFAULT_KEY_SIZE;
1887 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1888 || keySize > DSA_MAX_KEY_SIZE) {
1889 ALOGI("invalid key size %d", keySize);
1890 return ::SYSTEM_ERROR;
1891 }
1892 dsa_params.key_size = keySize;
1893
1894 if (args->size() == 3) {
1895 sp<KeystoreArg> gArg = args->itemAt(0);
1896 sp<KeystoreArg> pArg = args->itemAt(1);
1897 sp<KeystoreArg> qArg = args->itemAt(2);
1898
1899 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1900 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1901 dsa_params.generator_len = gArg->size();
1902
1903 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1904 dsa_params.prime_p_len = pArg->size();
1905
1906 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1907 dsa_params.prime_q_len = qArg->size();
1908 } else {
1909 ALOGI("not all DSA parameters were read");
1910 return ::SYSTEM_ERROR;
1911 }
1912 } else if (args->size() != 0) {
1913 ALOGI("DSA args must be 3");
1914 return ::SYSTEM_ERROR;
1915 }
1916
Kenny Root1d448c02013-11-21 10:36:53 -08001917 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001918 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1919 } else {
1920 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001921 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1922 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001923 }
1924 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001925 keymaster_ec_keygen_params_t ec_params;
1926 memset(&ec_params, '\0', sizeof(ec_params));
1927
1928 if (keySize == -1) {
1929 keySize = EC_DEFAULT_KEY_SIZE;
1930 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1931 ALOGI("invalid key size %d", keySize);
1932 return ::SYSTEM_ERROR;
1933 }
1934 ec_params.field_size = keySize;
1935
Kenny Root1d448c02013-11-21 10:36:53 -08001936 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001937 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1938 } else {
1939 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001940 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001941 }
Kenny Root96427ba2013-08-16 14:02:41 -07001942 } else if (keyType == EVP_PKEY_RSA) {
1943 keymaster_rsa_keygen_params_t rsa_params;
1944 memset(&rsa_params, '\0', sizeof(rsa_params));
1945 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1946
1947 if (keySize == -1) {
1948 keySize = RSA_DEFAULT_KEY_SIZE;
1949 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1950 ALOGI("invalid key size %d", keySize);
1951 return ::SYSTEM_ERROR;
1952 }
1953 rsa_params.modulus_size = keySize;
1954
1955 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001956 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001957 return ::SYSTEM_ERROR;
1958 } else if (args->size() == 1) {
1959 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1960 if (pubExpBlob != NULL) {
1961 Unique_BIGNUM pubExpBn(
1962 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1963 pubExpBlob->size(), NULL));
1964 if (pubExpBn.get() == NULL) {
1965 ALOGI("Could not convert public exponent to BN");
1966 return ::SYSTEM_ERROR;
1967 }
1968 unsigned long pubExp = BN_get_word(pubExpBn.get());
1969 if (pubExp == 0xFFFFFFFFL) {
1970 ALOGI("cannot represent public exponent as a long value");
1971 return ::SYSTEM_ERROR;
1972 }
1973 rsa_params.public_exponent = pubExp;
1974 }
1975 }
1976
1977 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1978 } else {
1979 ALOGW("Unsupported key type %d", keyType);
1980 rc = -1;
1981 }
1982
Kenny Root07438c82012-11-02 15:41:02 -07001983 if (rc) {
1984 return ::SYSTEM_ERROR;
1985 }
1986
Kenny Root655b9582013-04-04 08:37:42 -07001987 String8 name8(name);
1988 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001989
1990 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1991 free(data);
1992
Kenny Rootee8068b2013-10-07 09:49:15 -07001993 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001994 keyBlob.setFallback(isFallback);
1995
Kenny Root655b9582013-04-04 08:37:42 -07001996 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001997 }
1998
Kenny Rootf9119d62013-04-03 09:22:15 -07001999 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2000 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002001 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002002 pid_t spid = IPCThreadState::self()->getCallingPid();
2003 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002004 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002005 return ::PERMISSION_DENIED;
2006 }
Kenny Root07438c82012-11-02 15:41:02 -07002007
Kenny Root49468902013-03-19 13:41:33 -07002008 if (targetUid == -1) {
2009 targetUid = callingUid;
2010 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002011 return ::PERMISSION_DENIED;
2012 }
2013
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002014 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07002015 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002016 ALOGD("calling import in state: %d", state);
2017 return state;
2018 }
2019
2020 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002021 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002022
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002023 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002024 }
2025
Kenny Root07438c82012-11-02 15:41:02 -07002026 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2027 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002028 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002029 pid_t spid = IPCThreadState::self()->getCallingPid();
2030 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002031 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002032 return ::PERMISSION_DENIED;
2033 }
Kenny Root07438c82012-11-02 15:41:02 -07002034
Kenny Root07438c82012-11-02 15:41:02 -07002035 Blob keyBlob;
2036 String8 name8(name);
2037
Kenny Rootd38a0b02013-02-13 12:59:14 -08002038 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002039 int rc;
2040
Kenny Root655b9582013-04-04 08:37:42 -07002041 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002042 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002043 if (responseCode != ::NO_ERROR) {
2044 return responseCode;
2045 }
2046
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002047 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002048 if (device == NULL) {
2049 ALOGE("no keymaster device; cannot sign");
2050 return ::SYSTEM_ERROR;
2051 }
2052
2053 if (device->sign_data == NULL) {
2054 ALOGE("device doesn't implement signing");
2055 return ::SYSTEM_ERROR;
2056 }
2057
2058 keymaster_rsa_sign_params_t params;
2059 params.digest_type = DIGEST_NONE;
2060 params.padding_type = PADDING_NONE;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002061 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2062 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002063 if (rc) {
2064 ALOGW("device couldn't sign data");
2065 return ::SYSTEM_ERROR;
2066 }
2067
2068 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002069 }
2070
Kenny Root07438c82012-11-02 15:41:02 -07002071 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2072 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002073 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002074 pid_t spid = IPCThreadState::self()->getCallingPid();
2075 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002076 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002077 return ::PERMISSION_DENIED;
2078 }
Kenny Root70e3a862012-02-15 17:20:23 -08002079
Kenny Root655b9582013-04-04 08:37:42 -07002080 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002081 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002082 ALOGD("calling verify in state: %d", state);
2083 return state;
2084 }
Kenny Root70e3a862012-02-15 17:20:23 -08002085
Kenny Root07438c82012-11-02 15:41:02 -07002086 Blob keyBlob;
2087 String8 name8(name);
2088 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002089
Kenny Root655b9582013-04-04 08:37:42 -07002090 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002091 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002092 if (responseCode != ::NO_ERROR) {
2093 return responseCode;
2094 }
Kenny Root70e3a862012-02-15 17:20:23 -08002095
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002096 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002097 if (device == NULL) {
2098 return ::SYSTEM_ERROR;
2099 }
Kenny Root70e3a862012-02-15 17:20:23 -08002100
Kenny Root07438c82012-11-02 15:41:02 -07002101 if (device->verify_data == NULL) {
2102 return ::SYSTEM_ERROR;
2103 }
Kenny Root70e3a862012-02-15 17:20:23 -08002104
Kenny Root07438c82012-11-02 15:41:02 -07002105 keymaster_rsa_sign_params_t params;
2106 params.digest_type = DIGEST_NONE;
2107 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002108
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002109 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2110 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002111 if (rc) {
2112 return ::SYSTEM_ERROR;
2113 } else {
2114 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002115 }
2116 }
Kenny Root07438c82012-11-02 15:41:02 -07002117
2118 /*
2119 * TODO: The abstraction between things stored in hardware and regular blobs
2120 * of data stored on the filesystem should be moved down to keystore itself.
2121 * Unfortunately the Java code that calls this has naming conventions that it
2122 * knows about. Ideally keystore shouldn't be used to store random blobs of
2123 * data.
2124 *
2125 * Until that happens, it's necessary to have a separate "get_pubkey" and
2126 * "del_key" since the Java code doesn't really communicate what it's
2127 * intentions are.
2128 */
2129 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002130 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002131 pid_t spid = IPCThreadState::self()->getCallingPid();
2132 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002133 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002134 return ::PERMISSION_DENIED;
2135 }
Kenny Root07438c82012-11-02 15:41:02 -07002136
Kenny Root07438c82012-11-02 15:41:02 -07002137 Blob keyBlob;
2138 String8 name8(name);
2139
Kenny Rootd38a0b02013-02-13 12:59:14 -08002140 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002141
Kenny Root655b9582013-04-04 08:37:42 -07002142 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002143 TYPE_KEY_PAIR);
2144 if (responseCode != ::NO_ERROR) {
2145 return responseCode;
2146 }
2147
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002148 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002149 if (device == NULL) {
2150 return ::SYSTEM_ERROR;
2151 }
2152
2153 if (device->get_keypair_public == NULL) {
2154 ALOGE("device has no get_keypair_public implementation!");
2155 return ::SYSTEM_ERROR;
2156 }
2157
Kenny Root17208e02013-09-04 13:56:03 -07002158 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002159 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2160 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002161 if (rc) {
2162 return ::SYSTEM_ERROR;
2163 }
2164
2165 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002166 }
Kenny Root07438c82012-11-02 15:41:02 -07002167
Kenny Root49468902013-03-19 13:41:33 -07002168 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002169 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002170 pid_t spid = IPCThreadState::self()->getCallingPid();
2171 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002172 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002173 return ::PERMISSION_DENIED;
2174 }
Kenny Root07438c82012-11-02 15:41:02 -07002175
Kenny Root49468902013-03-19 13:41:33 -07002176 if (targetUid == -1) {
2177 targetUid = callingUid;
2178 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002179 return ::PERMISSION_DENIED;
2180 }
2181
Kenny Root07438c82012-11-02 15:41:02 -07002182 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002183 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01002184 return mKeyStore->del(filename.string(), ::TYPE_KEY_PAIR, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002185 }
2186
2187 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002188 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002189 pid_t spid = IPCThreadState::self()->getCallingPid();
2190 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002191 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002192 return ::PERMISSION_DENIED;
2193 }
Kenny Root07438c82012-11-02 15:41:02 -07002194
Kenny Root655b9582013-04-04 08:37:42 -07002195 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002196 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002197 ALOGD("calling grant in state: %d", state);
2198 return state;
2199 }
2200
2201 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002202 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002203
Kenny Root655b9582013-04-04 08:37:42 -07002204 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002205 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2206 }
2207
Kenny Root655b9582013-04-04 08:37:42 -07002208 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002209 return ::NO_ERROR;
2210 }
2211
2212 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002213 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002214 pid_t spid = IPCThreadState::self()->getCallingPid();
2215 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002216 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002217 return ::PERMISSION_DENIED;
2218 }
Kenny Root07438c82012-11-02 15:41:02 -07002219
Kenny Root655b9582013-04-04 08:37:42 -07002220 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002221 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002222 ALOGD("calling ungrant in state: %d", state);
2223 return state;
2224 }
2225
2226 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002227 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002228
Kenny Root655b9582013-04-04 08:37:42 -07002229 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002230 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2231 }
2232
Kenny Root655b9582013-04-04 08:37:42 -07002233 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002234 }
2235
2236 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002237 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002238 pid_t spid = IPCThreadState::self()->getCallingPid();
2239 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002240 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002241 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002242 }
Kenny Root07438c82012-11-02 15:41:02 -07002243
2244 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002245 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002246
Kenny Root655b9582013-04-04 08:37:42 -07002247 if (access(filename.string(), R_OK) == -1) {
2248 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002249 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002250 }
2251
Kenny Root655b9582013-04-04 08:37:42 -07002252 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002253 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002254 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002255 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002256 }
2257
2258 struct stat s;
2259 int ret = fstat(fd, &s);
2260 close(fd);
2261 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002262 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002263 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002264 }
2265
Kenny Root36a9e232013-02-04 14:24:15 -08002266 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002267 }
2268
Kenny Rootd53bc922013-03-21 14:10:15 -07002269 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2270 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002271 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002272 pid_t spid = IPCThreadState::self()->getCallingPid();
2273 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002274 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002275 return -1L;
2276 }
2277
Kenny Root655b9582013-04-04 08:37:42 -07002278 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002279 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002280 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002281 return state;
2282 }
2283
Kenny Rootd53bc922013-03-21 14:10:15 -07002284 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2285 srcUid = callingUid;
2286 } else if (!is_granted_to(callingUid, srcUid)) {
2287 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002288 return ::PERMISSION_DENIED;
2289 }
2290
Kenny Rootd53bc922013-03-21 14:10:15 -07002291 if (destUid == -1) {
2292 destUid = callingUid;
2293 }
2294
2295 if (srcUid != destUid) {
2296 if (static_cast<uid_t>(srcUid) != callingUid) {
2297 ALOGD("can only duplicate from caller to other or to same uid: "
2298 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2299 return ::PERMISSION_DENIED;
2300 }
2301
2302 if (!is_granted_to(callingUid, destUid)) {
2303 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2304 return ::PERMISSION_DENIED;
2305 }
2306 }
2307
2308 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002309 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002310
Kenny Rootd53bc922013-03-21 14:10:15 -07002311 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002312 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002313
Kenny Root655b9582013-04-04 08:37:42 -07002314 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2315 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002316 return ::SYSTEM_ERROR;
2317 }
2318
Kenny Rootd53bc922013-03-21 14:10:15 -07002319 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002320 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002321 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002322 if (responseCode != ::NO_ERROR) {
2323 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002324 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002325
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002326 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002327 }
2328
Kenny Root1b0e3932013-09-05 13:06:32 -07002329 int32_t is_hardware_backed(const String16& keyType) {
2330 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002331 }
2332
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002333 int32_t clear_uid(int64_t targetUid64) {
2334 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002335 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002336 pid_t spid = IPCThreadState::self()->getCallingPid();
2337 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002338 ALOGW("permission denied for %d: clear_uid", callingUid);
2339 return ::PERMISSION_DENIED;
2340 }
2341
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002342 if (targetUid64 == -1) {
2343 targetUid = callingUid;
Kenny Root007cb232014-07-30 16:59:42 -07002344 } else if (!is_self_or_system(callingUid, targetUid)) {
2345 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002346 return ::PERMISSION_DENIED;
2347 }
2348
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002349 const keymaster1_device_t* device = mKeyStore->getDevice();
Kenny Roota9bb5492013-04-01 16:29:11 -07002350 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002351 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002352 return ::SYSTEM_ERROR;
2353 }
2354
Robin Lee4b84fdc2014-09-24 11:56:57 +01002355 String8 prefix = String8::format("%u_", targetUid);
2356 Vector<String16> aliases;
2357 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002358 return ::SYSTEM_ERROR;
2359 }
2360
Robin Lee4b84fdc2014-09-24 11:56:57 +01002361 for (uint32_t i = 0; i < aliases.size(); i++) {
2362 String8 name8(aliases[i]);
2363 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2364 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002365 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002366 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002367 }
2368
Robin Lee4b84fdc2014-09-24 11:56:57 +01002369 int32_t reset_uid(int32_t targetUid) {
Robin Lee4e865752014-08-19 17:37:55 +01002370 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2371 pid_t spid = IPCThreadState::self()->getCallingPid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01002372
Robin Lee4e865752014-08-19 17:37:55 +01002373 if (!has_permission(callingUid, P_RESET_UID, spid)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01002374 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002375 return ::PERMISSION_DENIED;
2376 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002377 if (!is_self_or_system(callingUid, targetUid)) {
2378 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002379 return ::PERMISSION_DENIED;
2380 }
2381
Robin Lee4b84fdc2014-09-24 11:56:57 +01002382 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002383 }
2384
2385 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
2386 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2387 pid_t spid = IPCThreadState::self()->getCallingPid();
2388 if (!has_permission(callingUid, P_SYNC_UID, spid)) {
2389 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2390 return ::PERMISSION_DENIED;
2391 }
2392 if (callingUid != AID_SYSTEM) {
2393 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2394 return ::PERMISSION_DENIED;
2395 }
2396 if (sourceUid == targetUid) {
2397 return ::SYSTEM_ERROR;
2398 }
2399
2400 // Initialise user keystore with existing master key held in-memory
2401 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2402 }
2403
2404 int32_t password_uid(const String16& pw, int32_t targetUid) {
2405 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2406 pid_t spid = IPCThreadState::self()->getCallingPid();
2407 if (!has_permission(callingUid, P_PASSWORD_UID, spid)) {
2408 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2409 return ::PERMISSION_DENIED;
2410 }
2411 if (callingUid != AID_SYSTEM) {
2412 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2413 return ::PERMISSION_DENIED;
2414 }
2415
2416 const String8 password8(pw);
2417
2418 switch (mKeyStore->getState(targetUid)) {
2419 case ::STATE_UNINITIALIZED: {
2420 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2421 return mKeyStore->initializeUser(password8, targetUid);
2422 }
2423 case ::STATE_NO_ERROR: {
2424 // rewrite master key with new password.
2425 return mKeyStore->writeMasterKey(password8, targetUid);
2426 }
2427 case ::STATE_LOCKED: {
2428 // read master key, decrypt with password, initialize mMasterKey*.
2429 return mKeyStore->readMasterKey(password8, targetUid);
2430 }
2431 }
2432 return ::SYSTEM_ERROR;
2433 }
2434
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002435 int32_t addRngEntropy(const uint8_t* /*data*/, size_t /*dataLength*/) {
2436 return KM_ERROR_UNIMPLEMENTED;
2437 }
2438
2439 int32_t generateKey(const String16& /*name*/, const KeymasterArguments& /*params*/,
2440 int /*uid*/, int /*flags*/, KeyCharacteristics* /*outCharacteristics*/) {
2441 return KM_ERROR_UNIMPLEMENTED;
2442 }
2443
2444 int32_t getKeyCharacteristics(const String16& /*name*/,
2445 const keymaster_blob_t& /*clientId*/,
2446 const keymaster_blob_t& /*appData*/,
2447 KeyCharacteristics* /*outCharacteristics*/) {
2448 return KM_ERROR_UNIMPLEMENTED;
2449 }
2450
2451 int32_t importKey(const String16& /*name*/, const KeymasterArguments& /*params*/,
2452 keymaster_key_format_t /*format*/, const uint8_t* /*keyData*/,
2453 size_t /*keyLength*/, int /*uid*/, int /*flags*/,
2454 KeyCharacteristics* /*outCharacteristics*/) {
2455 return KM_ERROR_UNIMPLEMENTED;
2456 }
2457
2458 void exportKey(const String16& /*name*/, keymaster_key_format_t /*format*/,
2459 const keymaster_blob_t& /*clientId*/,
2460 const keymaster_blob_t& /*appData*/, ExportResult* result) {
2461 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2462 }
2463
2464 void begin(const sp<IBinder>& /*appToken*/, const String16& /*name*/,
2465 keymaster_purpose_t /*purpose*/, bool /*pruneable*/,
2466 const KeymasterArguments& /*params*/, KeymasterArguments* /*outParams*/,
2467 OperationResult* result) {
2468 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2469 }
2470
2471 void update(const sp<IBinder>& /*token*/, const KeymasterArguments& /*params*/,
2472 uint8_t* /*data*/, size_t /*dataLength*/, OperationResult* result) {
2473 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2474 }
2475
2476 void finish(const sp<IBinder>& /*token*/, const KeymasterArguments& /*args*/,
2477 uint8_t* /*signature*/, size_t /*signatureLength*/, OperationResult* result) {
2478 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2479 }
2480
2481 int32_t abort(const sp<IBinder>& /*token*/) {
2482 return KM_ERROR_UNIMPLEMENTED;
2483 }
2484
Kenny Root07438c82012-11-02 15:41:02 -07002485private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002486 inline bool isKeystoreUnlocked(State state) {
2487 switch (state) {
2488 case ::STATE_NO_ERROR:
2489 return true;
2490 case ::STATE_UNINITIALIZED:
2491 case ::STATE_LOCKED:
2492 return false;
2493 }
2494 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002495 }
2496
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002497 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002498 const int32_t device_api = device->common.module->module_api_version;
2499 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2500 switch (keyType) {
2501 case TYPE_RSA:
2502 case TYPE_DSA:
2503 case TYPE_EC:
2504 return true;
2505 default:
2506 return false;
2507 }
2508 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2509 switch (keyType) {
2510 case TYPE_RSA:
2511 return true;
2512 case TYPE_DSA:
2513 return device->flags & KEYMASTER_SUPPORTS_DSA;
2514 case TYPE_EC:
2515 return device->flags & KEYMASTER_SUPPORTS_EC;
2516 default:
2517 return false;
2518 }
2519 } else {
2520 return keyType == TYPE_RSA;
2521 }
2522 }
2523
Kenny Root07438c82012-11-02 15:41:02 -07002524 ::KeyStore* mKeyStore;
2525};
2526
2527}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002528
2529int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002530 if (argc < 2) {
2531 ALOGE("A directory must be specified!");
2532 return 1;
2533 }
2534 if (chdir(argv[1]) == -1) {
2535 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2536 return 1;
2537 }
2538
2539 Entropy entropy;
2540 if (!entropy.open()) {
2541 return 1;
2542 }
Kenny Root70e3a862012-02-15 17:20:23 -08002543
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07002544 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08002545 if (keymaster_device_initialize(&dev)) {
2546 ALOGE("keystore keymaster could not be initialized; exiting");
2547 return 1;
2548 }
2549
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002550 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002551 if (fallback_keymaster_device_initialize(&fallback)) {
2552 ALOGE("software keymaster could not be initialized; exiting");
2553 return 1;
2554 }
2555
Riley Spahneaabae92014-06-30 12:39:52 -07002556 ks_is_selinux_enabled = is_selinux_enabled();
2557 if (ks_is_selinux_enabled) {
2558 union selinux_callback cb;
2559 cb.func_log = selinux_log_callback;
2560 selinux_set_callback(SELINUX_CB_LOG, cb);
2561 if (getcon(&tctx) != 0) {
2562 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2563 return -1;
2564 }
2565 } else {
2566 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2567 }
2568
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002569 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07002570 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002571 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2572 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2573 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2574 if (ret != android::OK) {
2575 ALOGE("Couldn't register binder service!");
2576 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002577 }
Kenny Root07438c82012-11-02 15:41:02 -07002578
2579 /*
2580 * We're the only thread in existence, so we're just going to process
2581 * Binder transaction as a single-threaded program.
2582 */
2583 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002584
2585 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002586 return 1;
2587}