blob: 27ced71ab889ba0a87235432369ae44652f89d3c [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>
23#include <unistd.h>
24#include <signal.h>
25#include <errno.h>
26#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070027#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080028#include <fcntl.h>
29#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070030#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080031#include <sys/types.h>
32#include <sys/socket.h>
33#include <sys/stat.h>
34#include <sys/time.h>
35#include <arpa/inet.h>
36
37#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070038#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080039#include <openssl/evp.h>
40#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070041#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080042
Kenny Root70e3a862012-02-15 17:20:23 -080043#include <hardware/keymaster.h>
44
Kenny Root17208e02013-09-04 13:56:03 -070045#include <keymaster/softkeymaster.h>
46
Kenny Root26cfc082013-09-11 14:38:56 -070047#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070048#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070049#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080050
Kenny Root07438c82012-11-02 15:41:02 -070051#include <keystore/IKeystoreService.h>
52#include <binder/IPCThreadState.h>
53#include <binder/IServiceManager.h>
54
Kenny Roota91203b2012-02-15 15:00:46 -080055#include <cutils/log.h>
56#include <cutils/sockets.h>
57#include <private/android_filesystem_config.h>
58
Kenny Root07438c82012-11-02 15:41:02 -070059#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080060
Riley Spahneaabae92014-06-30 12:39:52 -070061#include <selinux/android.h>
62
Kenny Root96427ba2013-08-16 14:02:41 -070063#include "defaults.h"
64
Kenny Roota91203b2012-02-15 15:00:46 -080065/* KeyStore is a secured storage for key-value pairs. In this implementation,
66 * each file stores one key-value pair. Keys are encoded in file names, and
67 * values are encrypted with checksums. The encryption key is protected by a
68 * user-defined password. To keep things simple, buffers are always larger than
69 * the maximum space we needed, so boundary checks on buffers are omitted. */
70
71#define KEY_SIZE ((NAME_MAX - 15) / 2)
72#define VALUE_SIZE 32768
73#define PASSWORD_SIZE VALUE_SIZE
74
Kenny Root822c3a92012-03-23 16:34:39 -070075
Kenny Root96427ba2013-08-16 14:02:41 -070076struct BIGNUM_Delete {
77 void operator()(BIGNUM* p) const {
78 BN_free(p);
79 }
80};
81typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
82
Kenny Root822c3a92012-03-23 16:34:39 -070083struct BIO_Delete {
84 void operator()(BIO* p) const {
85 BIO_free(p);
86 }
87};
88typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
89
90struct EVP_PKEY_Delete {
91 void operator()(EVP_PKEY* p) const {
92 EVP_PKEY_free(p);
93 }
94};
95typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
96
97struct PKCS8_PRIV_KEY_INFO_Delete {
98 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
99 PKCS8_PRIV_KEY_INFO_free(p);
100 }
101};
102typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
103
104
Kenny Root70e3a862012-02-15 17:20:23 -0800105static int keymaster_device_initialize(keymaster_device_t** dev) {
106 int rc;
107
108 const hw_module_t* mod;
109 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
110 if (rc) {
111 ALOGE("could not find any keystore module");
112 goto out;
113 }
114
115 rc = keymaster_open(mod, dev);
116 if (rc) {
117 ALOGE("could not open keymaster device in %s (%s)",
118 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
119 goto out;
120 }
121
122 return 0;
123
124out:
125 *dev = NULL;
126 return rc;
127}
128
129static void keymaster_device_release(keymaster_device_t* dev) {
130 keymaster_close(dev);
131}
132
Kenny Root07438c82012-11-02 15:41:02 -0700133/***************
134 * PERMISSIONS *
135 ***************/
136
137/* Here are the permissions, actions, users, and the main function. */
138typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700139 P_TEST = 1 << 0,
140 P_GET = 1 << 1,
141 P_INSERT = 1 << 2,
142 P_DELETE = 1 << 3,
143 P_EXIST = 1 << 4,
144 P_SAW = 1 << 5,
145 P_RESET = 1 << 6,
146 P_PASSWORD = 1 << 7,
147 P_LOCK = 1 << 8,
148 P_UNLOCK = 1 << 9,
149 P_ZERO = 1 << 10,
150 P_SIGN = 1 << 11,
151 P_VERIFY = 1 << 12,
152 P_GRANT = 1 << 13,
153 P_DUPLICATE = 1 << 14,
Kenny Roota9bb5492013-04-01 16:29:11 -0700154 P_CLEAR_UID = 1 << 15,
Kenny Root07438c82012-11-02 15:41:02 -0700155} perm_t;
156
157static struct user_euid {
158 uid_t uid;
159 uid_t euid;
160} user_euids[] = {
161 {AID_VPN, AID_SYSTEM},
162 {AID_WIFI, AID_SYSTEM},
163 {AID_ROOT, AID_SYSTEM},
164};
165
Riley Spahneaabae92014-06-30 12:39:52 -0700166/* perm_labels associcated with keystore_key SELinux class verbs. */
167const char *perm_labels[] = {
168 "test",
169 "get",
170 "insert",
171 "delete",
172 "exist",
173 "saw",
174 "reset",
175 "password",
176 "lock",
177 "unlock",
178 "zero",
179 "sign",
180 "verify",
181 "grant",
182 "duplicate",
183 "clear_uid"
184};
185
Kenny Root07438c82012-11-02 15:41:02 -0700186static struct user_perm {
187 uid_t uid;
188 perm_t perms;
189} user_perms[] = {
190 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
191 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
192 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
193 {AID_ROOT, static_cast<perm_t>(P_GET) },
194};
195
196static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
197 | P_VERIFY);
198
Riley Spahneaabae92014-06-30 12:39:52 -0700199static char *tctx;
200static int ks_is_selinux_enabled;
201
202static const char *get_perm_label(perm_t perm) {
203 unsigned int index = ffs(perm);
204 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
205 return perm_labels[index - 1];
206 } else {
207 ALOGE("Keystore: Failed to retrieve permission label.\n");
208 abort();
209 }
210}
211
Kenny Root655b9582013-04-04 08:37:42 -0700212/**
213 * Returns the app ID (in the Android multi-user sense) for the current
214 * UNIX UID.
215 */
216static uid_t get_app_id(uid_t uid) {
217 return uid % AID_USER;
218}
219
220/**
221 * Returns the user ID (in the Android multi-user sense) for the current
222 * UNIX UID.
223 */
224static uid_t get_user_id(uid_t uid) {
225 return uid / AID_USER;
226}
227
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700228static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700229 if (!ks_is_selinux_enabled) {
230 return true;
231 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000232
Riley Spahneaabae92014-06-30 12:39:52 -0700233 char *sctx = NULL;
234 const char *selinux_class = "keystore_key";
235 const char *str_perm = get_perm_label(perm);
236
237 if (!str_perm) {
238 return false;
239 }
240
241 if (getpidcon(spid, &sctx) != 0) {
242 ALOGE("SELinux: Failed to get source pid context.\n");
243 return false;
244 }
245
246 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
247 NULL) == 0;
248 freecon(sctx);
249 return allowed;
250}
251
252static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700253 // All system users are equivalent for multi-user support.
254 if (get_app_id(uid) == AID_SYSTEM) {
255 uid = AID_SYSTEM;
256 }
257
Kenny Root07438c82012-11-02 15:41:02 -0700258 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
259 struct user_perm user = user_perms[i];
260 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700261 return (user.perms & perm) &&
262 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700263 }
264 }
265
Riley Spahneaabae92014-06-30 12:39:52 -0700266 return (DEFAULT_PERMS & perm) &&
267 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700268}
269
Kenny Root49468902013-03-19 13:41:33 -0700270/**
271 * Returns the UID that the callingUid should act as. This is here for
272 * legacy support of the WiFi and VPN systems and should be removed
273 * when WiFi can operate in its own namespace.
274 */
Kenny Root07438c82012-11-02 15:41:02 -0700275static uid_t get_keystore_euid(uid_t uid) {
276 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
277 struct user_euid user = user_euids[i];
278 if (user.uid == uid) {
279 return user.euid;
280 }
281 }
282
283 return uid;
284}
285
Kenny Root49468902013-03-19 13:41:33 -0700286/**
287 * Returns true if the callingUid is allowed to interact in the targetUid's
288 * namespace.
289 */
290static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
291 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
292 struct user_euid user = user_euids[i];
293 if (user.euid == callingUid && user.uid == targetUid) {
294 return true;
295 }
296 }
297
298 return false;
299}
300
Kenny Roote17c2542014-07-30 16:59:42 -0700301/**
302 * Allow the system to perform some privileged tasks that have to do with
303 * system maintenance. This should not be used for any function that uses
304 * the keys in any way (e.g., signing).
305 */
306static bool is_self_or_system(uid_t callingUid, uid_t targetUid) {
307 return callingUid == targetUid || callingUid == AID_SYSTEM;
308}
309
Kenny Roota91203b2012-02-15 15:00:46 -0800310/* Here is the encoding of keys. This is necessary in order to allow arbitrary
311 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
312 * into two bytes. The first byte is one of [+-.] which represents the first
313 * two bits of the character. The second byte encodes the rest of the bits into
314 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
315 * that Base64 cannot be used here due to the need of prefix match on keys. */
316
Kenny Root655b9582013-04-04 08:37:42 -0700317static size_t encode_key_length(const android::String8& keyName) {
318 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
319 size_t length = keyName.length();
320 for (int i = length; i > 0; --i, ++in) {
321 if (*in < '0' || *in > '~') {
322 ++length;
323 }
324 }
325 return length;
326}
327
Kenny Root07438c82012-11-02 15:41:02 -0700328static int encode_key(char* out, const android::String8& keyName) {
329 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
330 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800331 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700332 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800333 *out = '+' + (*in >> 6);
334 *++out = '0' + (*in & 0x3F);
335 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700336 } else {
337 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800338 }
339 }
340 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800341 return length;
342}
343
Kenny Root07438c82012-11-02 15:41:02 -0700344/*
345 * Converts from the "escaped" format on disk to actual name.
346 * This will be smaller than the input string.
347 *
348 * Characters that should combine with the next at the end will be truncated.
349 */
350static size_t decode_key_length(const char* in, size_t length) {
351 size_t outLength = 0;
352
353 for (const char* end = in + length; in < end; in++) {
354 /* This combines with the next character. */
355 if (*in < '0' || *in > '~') {
356 continue;
357 }
358
359 outLength++;
360 }
361 return outLength;
362}
363
364static void decode_key(char* out, const char* in, size_t length) {
365 for (const char* end = in + length; in < end; in++) {
366 if (*in < '0' || *in > '~') {
367 /* Truncate combining characters at the end. */
368 if (in + 1 >= end) {
369 break;
370 }
371
372 *out = (*in++ - '+') << 6;
373 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800374 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700375 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800376 }
377 }
378 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800379}
380
381static size_t readFully(int fd, uint8_t* data, size_t size) {
382 size_t remaining = size;
383 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800384 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800385 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800386 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800387 }
388 data += n;
389 remaining -= n;
390 }
391 return size;
392}
393
394static size_t writeFully(int fd, uint8_t* data, size_t size) {
395 size_t remaining = size;
396 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800397 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
398 if (n < 0) {
399 ALOGW("write failed: %s", strerror(errno));
400 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800401 }
402 data += n;
403 remaining -= n;
404 }
405 return size;
406}
407
408class Entropy {
409public:
410 Entropy() : mRandom(-1) {}
411 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800412 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800413 close(mRandom);
414 }
415 }
416
417 bool open() {
418 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800419 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
420 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800421 ALOGE("open: %s: %s", randomDevice, strerror(errno));
422 return false;
423 }
424 return true;
425 }
426
Kenny Root51878182012-03-13 12:53:19 -0700427 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800428 return (readFully(mRandom, data, size) == size);
429 }
430
431private:
432 int mRandom;
433};
434
435/* Here is the file format. There are two parts in blob.value, the secret and
436 * the description. The secret is stored in ciphertext, and its original size
437 * can be found in blob.length. The description is stored after the secret in
438 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700439 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700440 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800441 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
442 * and decryptBlob(). Thus they should not be accessed from outside. */
443
Kenny Root822c3a92012-03-23 16:34:39 -0700444/* ** Note to future implementors of encryption: **
445 * Currently this is the construction:
446 * metadata || Enc(MD5(data) || data)
447 *
448 * This should be the construction used for encrypting if re-implementing:
449 *
450 * Derive independent keys for encryption and MAC:
451 * Kenc = AES_encrypt(masterKey, "Encrypt")
452 * Kmac = AES_encrypt(masterKey, "MAC")
453 *
454 * Store this:
455 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
456 * HMAC(Kmac, metadata || Enc(data))
457 */
Kenny Roota91203b2012-02-15 15:00:46 -0800458struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700459 uint8_t version;
460 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700461 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800462 uint8_t info;
463 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700464 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800465 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700466 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800467 int32_t length; // in network byte order when encrypted
468 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
469};
470
Kenny Root822c3a92012-03-23 16:34:39 -0700471typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700472 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700473 TYPE_GENERIC = 1,
474 TYPE_MASTER_KEY = 2,
475 TYPE_KEY_PAIR = 3,
476} BlobType;
477
Kenny Rootf9119d62013-04-03 09:22:15 -0700478static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700479
Kenny Roota91203b2012-02-15 15:00:46 -0800480class Blob {
481public:
Kenny Root07438c82012-11-02 15:41:02 -0700482 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
483 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800484 mBlob.length = valueLength;
485 memcpy(mBlob.value, value, valueLength);
486
487 mBlob.info = infoLength;
488 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700489
Kenny Root07438c82012-11-02 15:41:02 -0700490 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700491 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700492
Kenny Rootee8068b2013-10-07 09:49:15 -0700493 if (type == TYPE_MASTER_KEY) {
494 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
495 } else {
496 mBlob.flags = KEYSTORE_FLAG_NONE;
497 }
Kenny Roota91203b2012-02-15 15:00:46 -0800498 }
499
500 Blob(blob b) {
501 mBlob = b;
502 }
503
504 Blob() {}
505
Kenny Root51878182012-03-13 12:53:19 -0700506 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800507 return mBlob.value;
508 }
509
Kenny Root51878182012-03-13 12:53:19 -0700510 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800511 return mBlob.length;
512 }
513
Kenny Root51878182012-03-13 12:53:19 -0700514 const uint8_t* getInfo() const {
515 return mBlob.value + mBlob.length;
516 }
517
518 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800519 return mBlob.info;
520 }
521
Kenny Root822c3a92012-03-23 16:34:39 -0700522 uint8_t getVersion() const {
523 return mBlob.version;
524 }
525
Kenny Rootf9119d62013-04-03 09:22:15 -0700526 bool isEncrypted() const {
527 if (mBlob.version < 2) {
528 return true;
529 }
530
531 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
532 }
533
534 void setEncrypted(bool encrypted) {
535 if (encrypted) {
536 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
537 } else {
538 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
539 }
540 }
541
Kenny Root17208e02013-09-04 13:56:03 -0700542 bool isFallback() const {
543 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
544 }
545
546 void setFallback(bool fallback) {
547 if (fallback) {
548 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
549 } else {
550 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
551 }
552 }
553
Kenny Root822c3a92012-03-23 16:34:39 -0700554 void setVersion(uint8_t version) {
555 mBlob.version = version;
556 }
557
558 BlobType getType() const {
559 return BlobType(mBlob.type);
560 }
561
562 void setType(BlobType type) {
563 mBlob.type = uint8_t(type);
564 }
565
Kenny Rootf9119d62013-04-03 09:22:15 -0700566 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
567 ALOGV("writing blob %s", filename);
568 if (isEncrypted()) {
569 if (state != STATE_NO_ERROR) {
570 ALOGD("couldn't insert encrypted blob while not unlocked");
571 return LOCKED;
572 }
573
574 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
575 ALOGW("Could not read random data for: %s", filename);
576 return SYSTEM_ERROR;
577 }
Kenny Roota91203b2012-02-15 15:00:46 -0800578 }
579
580 // data includes the value and the value's length
581 size_t dataLength = mBlob.length + sizeof(mBlob.length);
582 // pad data to the AES_BLOCK_SIZE
583 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
584 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
585 // encrypted data includes the digest value
586 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
587 // move info after space for padding
588 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
589 // zero padding area
590 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
591
592 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800593
Kenny Rootf9119d62013-04-03 09:22:15 -0700594 if (isEncrypted()) {
595 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800596
Kenny Rootf9119d62013-04-03 09:22:15 -0700597 uint8_t vector[AES_BLOCK_SIZE];
598 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
599 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
600 aes_key, vector, AES_ENCRYPT);
601 }
602
Kenny Roota91203b2012-02-15 15:00:46 -0800603 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
604 size_t fileLength = encryptedLength + headerLength + mBlob.info;
605
606 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800607 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
608 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
609 if (out < 0) {
610 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800611 return SYSTEM_ERROR;
612 }
613 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
614 if (close(out) != 0) {
615 return SYSTEM_ERROR;
616 }
617 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800618 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800619 unlink(tmpFileName);
620 return SYSTEM_ERROR;
621 }
Kenny Root150ca932012-11-14 14:29:02 -0800622 if (rename(tmpFileName, filename) == -1) {
623 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
624 return SYSTEM_ERROR;
625 }
626 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800627 }
628
Kenny Rootf9119d62013-04-03 09:22:15 -0700629 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
630 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800631 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
632 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800633 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
634 }
635 // fileLength may be less than sizeof(mBlob) since the in
636 // memory version has extra padding to tolerate rounding up to
637 // the AES_BLOCK_SIZE
638 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
639 if (close(in) != 0) {
640 return SYSTEM_ERROR;
641 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700642
643 if (isEncrypted() && (state != STATE_NO_ERROR)) {
644 return LOCKED;
645 }
646
Kenny Roota91203b2012-02-15 15:00:46 -0800647 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
648 if (fileLength < headerLength) {
649 return VALUE_CORRUPTED;
650 }
651
652 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700653 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800654 return VALUE_CORRUPTED;
655 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700656
657 ssize_t digestedLength;
658 if (isEncrypted()) {
659 if (encryptedLength % AES_BLOCK_SIZE != 0) {
660 return VALUE_CORRUPTED;
661 }
662
663 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
664 mBlob.vector, AES_DECRYPT);
665 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
666 uint8_t computedDigest[MD5_DIGEST_LENGTH];
667 MD5(mBlob.digested, digestedLength, computedDigest);
668 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
669 return VALUE_CORRUPTED;
670 }
671 } else {
672 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800673 }
674
675 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
676 mBlob.length = ntohl(mBlob.length);
677 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
678 return VALUE_CORRUPTED;
679 }
680 if (mBlob.info != 0) {
681 // move info from after padding to after data
682 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
683 }
Kenny Root07438c82012-11-02 15:41:02 -0700684 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800685 }
686
687private:
688 struct blob mBlob;
689};
690
Kenny Root655b9582013-04-04 08:37:42 -0700691class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800692public:
Kenny Root655b9582013-04-04 08:37:42 -0700693 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
694 asprintf(&mUserDir, "user_%u", mUserId);
695 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
696 }
697
698 ~UserState() {
699 free(mUserDir);
700 free(mMasterKeyFile);
701 }
702
703 bool initialize() {
704 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
705 ALOGE("Could not create directory '%s'", mUserDir);
706 return false;
707 }
708
709 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800710 setState(STATE_LOCKED);
711 } else {
712 setState(STATE_UNINITIALIZED);
713 }
Kenny Root70e3a862012-02-15 17:20:23 -0800714
Kenny Root655b9582013-04-04 08:37:42 -0700715 return true;
716 }
717
718 uid_t getUserId() const {
719 return mUserId;
720 }
721
722 const char* getUserDirName() const {
723 return mUserDir;
724 }
725
726 const char* getMasterKeyFileName() const {
727 return mMasterKeyFile;
728 }
729
730 void setState(State state) {
731 mState = state;
732 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
733 mRetry = MAX_RETRY;
734 }
Kenny Roota91203b2012-02-15 15:00:46 -0800735 }
736
Kenny Root51878182012-03-13 12:53:19 -0700737 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800738 return mState;
739 }
740
Kenny Root51878182012-03-13 12:53:19 -0700741 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800742 return mRetry;
743 }
744
Kenny Root655b9582013-04-04 08:37:42 -0700745 void zeroizeMasterKeysInMemory() {
746 memset(mMasterKey, 0, sizeof(mMasterKey));
747 memset(mSalt, 0, sizeof(mSalt));
748 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
749 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800750 }
751
Kenny Root655b9582013-04-04 08:37:42 -0700752 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
753 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800754 return SYSTEM_ERROR;
755 }
Kenny Root655b9582013-04-04 08:37:42 -0700756 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800757 if (response != NO_ERROR) {
758 return response;
759 }
760 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700761 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800762 }
763
Kenny Root655b9582013-04-04 08:37:42 -0700764 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800765 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
766 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
767 AES_KEY passwordAesKey;
768 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700769 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700770 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800771 }
772
Kenny Root655b9582013-04-04 08:37:42 -0700773 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
774 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800775 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800776 return SYSTEM_ERROR;
777 }
778
779 // we read the raw blob to just to get the salt to generate
780 // the AES key, then we create the Blob to use with decryptBlob
781 blob rawBlob;
782 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
783 if (close(in) != 0) {
784 return SYSTEM_ERROR;
785 }
786 // find salt at EOF if present, otherwise we have an old file
787 uint8_t* salt;
788 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
789 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
790 } else {
791 salt = NULL;
792 }
793 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
794 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
795 AES_KEY passwordAesKey;
796 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
797 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700798 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
799 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800800 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700801 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800802 }
803 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
804 // if salt was missing, generate one and write a new master key file with the salt.
805 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700806 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800807 return SYSTEM_ERROR;
808 }
Kenny Root655b9582013-04-04 08:37:42 -0700809 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800810 }
811 if (response == NO_ERROR) {
812 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
813 setupMasterKeys();
814 }
815 return response;
816 }
817 if (mRetry <= 0) {
818 reset();
819 return UNINITIALIZED;
820 }
821 --mRetry;
822 switch (mRetry) {
823 case 0: return WRONG_PASSWORD_0;
824 case 1: return WRONG_PASSWORD_1;
825 case 2: return WRONG_PASSWORD_2;
826 case 3: return WRONG_PASSWORD_3;
827 default: return WRONG_PASSWORD_3;
828 }
829 }
830
Kenny Root655b9582013-04-04 08:37:42 -0700831 AES_KEY* getEncryptionKey() {
832 return &mMasterKeyEncryption;
833 }
834
835 AES_KEY* getDecryptionKey() {
836 return &mMasterKeyDecryption;
837 }
838
Kenny Roota91203b2012-02-15 15:00:46 -0800839 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700840 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800841 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700842 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800843 return false;
844 }
Kenny Root655b9582013-04-04 08:37:42 -0700845
846 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800847 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700848 // We only care about files.
849 if (file->d_type != DT_REG) {
850 continue;
851 }
852
853 // Skip anything that starts with a "."
Kenny Roota71c9d62014-07-30 16:39:40 -0700854 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700855 continue;
856 }
857
858 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800859 }
860 closedir(dir);
861 return true;
862 }
863
Kenny Root655b9582013-04-04 08:37:42 -0700864private:
865 static const int MASTER_KEY_SIZE_BYTES = 16;
866 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
867
868 static const int MAX_RETRY = 4;
869 static const size_t SALT_SIZE = 16;
870
871 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
872 uint8_t* salt) {
873 size_t saltSize;
874 if (salt != NULL) {
875 saltSize = SALT_SIZE;
876 } else {
877 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
878 salt = (uint8_t*) "keystore";
879 // sizeof = 9, not strlen = 8
880 saltSize = sizeof("keystore");
881 }
882
883 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
884 saltSize, 8192, keySize, key);
885 }
886
887 bool generateSalt(Entropy* entropy) {
888 return entropy->generate_random_data(mSalt, sizeof(mSalt));
889 }
890
891 bool generateMasterKey(Entropy* entropy) {
892 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
893 return false;
894 }
895 if (!generateSalt(entropy)) {
896 return false;
897 }
898 return true;
899 }
900
901 void setupMasterKeys() {
902 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
903 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
904 setState(STATE_NO_ERROR);
905 }
906
907 uid_t mUserId;
908
909 char* mUserDir;
910 char* mMasterKeyFile;
911
912 State mState;
913 int8_t mRetry;
914
915 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
916 uint8_t mSalt[SALT_SIZE];
917
918 AES_KEY mMasterKeyEncryption;
919 AES_KEY mMasterKeyDecryption;
920};
921
922typedef struct {
923 uint32_t uid;
924 const uint8_t* filename;
925} grant_t;
926
927class KeyStore {
928public:
929 KeyStore(Entropy* entropy, keymaster_device_t* device)
930 : mEntropy(entropy)
931 , mDevice(device)
932 {
933 memset(&mMetaData, '\0', sizeof(mMetaData));
934 }
935
936 ~KeyStore() {
937 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
938 it != mGrants.end(); it++) {
939 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700940 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800941 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700942
943 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
944 it != mMasterKeys.end(); it++) {
945 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700946 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800947 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700948 }
949
950 keymaster_device_t* getDevice() const {
951 return mDevice;
952 }
953
954 ResponseCode initialize() {
955 readMetaData();
956 if (upgradeKeystore()) {
957 writeMetaData();
958 }
959
960 return ::NO_ERROR;
961 }
962
963 State getState(uid_t uid) {
964 return getUserState(uid)->getState();
965 }
966
967 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
968 UserState* userState = getUserState(uid);
969 return userState->initialize(pw, mEntropy);
970 }
971
972 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Leeb224f0a2014-08-12 17:31:40 +0100973 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -0700974 return userState->writeMasterKey(pw, mEntropy);
975 }
976
977 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Leeb224f0a2014-08-12 17:31:40 +0100978 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -0700979 return userState->readMasterKey(pw, mEntropy);
980 }
981
982 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700983 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700984 encode_key(encoded, keyName);
985 return android::String8(encoded);
986 }
987
988 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700989 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700990 encode_key(encoded, keyName);
991 return android::String8::format("%u_%s", uid, encoded);
992 }
993
994 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700995 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700996 encode_key(encoded, keyName);
997 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
998 encoded);
999 }
1000
1001 bool reset(uid_t uid) {
1002 UserState* userState = getUserState(uid);
1003 userState->zeroizeMasterKeysInMemory();
1004 userState->setState(STATE_UNINITIALIZED);
1005 return userState->reset();
1006 }
1007
1008 bool isEmpty(uid_t uid) const {
1009 const UserState* userState = getUserState(uid);
1010 if (userState == NULL) {
1011 return true;
1012 }
1013
1014 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001015 struct dirent* file;
1016 if (!dir) {
1017 return true;
1018 }
1019 bool result = true;
Kenny Root655b9582013-04-04 08:37:42 -07001020
1021 char filename[NAME_MAX];
1022 int n = snprintf(filename, sizeof(filename), "%u_", uid);
1023
Kenny Roota91203b2012-02-15 15:00:46 -08001024 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001025 // We only care about files.
1026 if (file->d_type != DT_REG) {
1027 continue;
1028 }
1029
1030 // Skip anything that starts with a "."
1031 if (file->d_name[0] == '.') {
1032 continue;
1033 }
1034
1035 if (!strncmp(file->d_name, filename, n)) {
Kenny Roota91203b2012-02-15 15:00:46 -08001036 result = false;
1037 break;
1038 }
1039 }
1040 closedir(dir);
1041 return result;
1042 }
1043
Kenny Root655b9582013-04-04 08:37:42 -07001044 void lock(uid_t uid) {
1045 UserState* userState = getUserState(uid);
1046 userState->zeroizeMasterKeysInMemory();
1047 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001048 }
1049
Kenny Root655b9582013-04-04 08:37:42 -07001050 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1051 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001052 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1053 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001054 if (rc != NO_ERROR) {
1055 return rc;
1056 }
1057
1058 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001059 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001060 /* If we upgrade the key, we need to write it to disk again. Then
1061 * it must be read it again since the blob is encrypted each time
1062 * it's written.
1063 */
Kenny Root655b9582013-04-04 08:37:42 -07001064 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1065 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001066 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1067 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001068 return rc;
1069 }
1070 }
Kenny Root822c3a92012-03-23 16:34:39 -07001071 }
1072
Kenny Root17208e02013-09-04 13:56:03 -07001073 /*
1074 * This will upgrade software-backed keys to hardware-backed keys when
1075 * the HAL for the device supports the newer key types.
1076 */
1077 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1078 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1079 && keyBlob->isFallback()) {
1080 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1081 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1082
1083 // The HAL allowed the import, reget the key to have the "fresh"
1084 // version.
1085 if (imported == NO_ERROR) {
1086 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1087 }
1088 }
1089
Kenny Rootd53bc922013-03-21 14:10:15 -07001090 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001091 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1092 return KEY_NOT_FOUND;
1093 }
1094
1095 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001096 }
1097
Kenny Root655b9582013-04-04 08:37:42 -07001098 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1099 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001100 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1101 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001102 }
1103
Kenny Root07438c82012-11-02 15:41:02 -07001104 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001105 const grant_t* existing = getGrant(filename, granteeUid);
1106 if (existing == NULL) {
1107 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001108 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001109 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001110 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001111 }
1112 }
1113
Kenny Root07438c82012-11-02 15:41:02 -07001114 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001115 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1116 it != mGrants.end(); it++) {
1117 grant_t* grant = *it;
1118 if (grant->uid == granteeUid
1119 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1120 mGrants.erase(it);
1121 return true;
1122 }
Kenny Root70e3a862012-02-15 17:20:23 -08001123 }
Kenny Root70e3a862012-02-15 17:20:23 -08001124 return false;
1125 }
1126
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001127 bool hasGrant(const char* filename, const uid_t uid) const {
1128 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001129 }
1130
Kenny Rootf9119d62013-04-03 09:22:15 -07001131 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1132 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001133 uint8_t* data;
1134 size_t dataLength;
1135 int rc;
1136
1137 if (mDevice->import_keypair == NULL) {
1138 ALOGE("Keymaster doesn't support import!");
1139 return SYSTEM_ERROR;
1140 }
1141
Kenny Root17208e02013-09-04 13:56:03 -07001142 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001143 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001144 if (rc) {
Kenny Root17208e02013-09-04 13:56:03 -07001145 // If this is an old device HAL, try to fall back to an old version
1146 if (mDevice->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_2) {
1147 rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength);
1148 isFallback = true;
1149 }
1150
1151 if (rc) {
1152 ALOGE("Error while importing keypair: %d", rc);
1153 return SYSTEM_ERROR;
1154 }
Kenny Root822c3a92012-03-23 16:34:39 -07001155 }
1156
1157 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1158 free(data);
1159
Kenny Rootf9119d62013-04-03 09:22:15 -07001160 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001161 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001162
Kenny Root655b9582013-04-04 08:37:42 -07001163 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001164 }
1165
Kenny Root1b0e3932013-09-05 13:06:32 -07001166 bool isHardwareBacked(const android::String16& keyType) const {
1167 if (mDevice == NULL) {
1168 ALOGW("can't get keymaster device");
1169 return false;
1170 }
1171
1172 if (sRSAKeyType == keyType) {
1173 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1174 } else {
1175 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1176 && (mDevice->common.module->module_api_version
1177 >= KEYMASTER_MODULE_API_VERSION_0_2);
1178 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001179 }
1180
Kenny Root655b9582013-04-04 08:37:42 -07001181 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1182 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001183 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001184
1185 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1186 if (responseCode == NO_ERROR) {
1187 return responseCode;
1188 }
1189
1190 // If this is one of the legacy UID->UID mappings, use it.
1191 uid_t euid = get_keystore_euid(uid);
1192 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001193 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001194 responseCode = get(filepath8.string(), keyBlob, type, uid);
1195 if (responseCode == NO_ERROR) {
1196 return responseCode;
1197 }
1198 }
1199
1200 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001201 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001202 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001203 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001204 if (end[0] != '_' || end[1] == 0) {
1205 return KEY_NOT_FOUND;
1206 }
Kenny Root86b16e82013-09-09 11:15:54 -07001207 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1208 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001209 if (!hasGrant(filepath8.string(), uid)) {
1210 return responseCode;
1211 }
1212
1213 // It is a granted key. Try to load it.
1214 return get(filepath8.string(), keyBlob, type, uid);
1215 }
1216
1217 /**
1218 * Returns any existing UserState or creates it if it doesn't exist.
1219 */
1220 UserState* getUserState(uid_t uid) {
1221 uid_t userId = get_user_id(uid);
1222
1223 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1224 it != mMasterKeys.end(); it++) {
1225 UserState* state = *it;
1226 if (state->getUserId() == userId) {
1227 return state;
1228 }
1229 }
1230
1231 UserState* userState = new UserState(userId);
1232 if (!userState->initialize()) {
1233 /* There's not much we can do if initialization fails. Trying to
1234 * unlock the keystore for that user will fail as well, so any
1235 * subsequent request for this user will just return SYSTEM_ERROR.
1236 */
1237 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1238 }
1239 mMasterKeys.add(userState);
1240 return userState;
1241 }
1242
1243 /**
1244 * Returns NULL if the UserState doesn't already exist.
1245 */
1246 const UserState* getUserState(uid_t uid) const {
1247 uid_t userId = get_user_id(uid);
1248
1249 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1250 it != mMasterKeys.end(); it++) {
1251 UserState* state = *it;
1252 if (state->getUserId() == userId) {
1253 return state;
1254 }
1255 }
1256
1257 return NULL;
1258 }
1259
Kenny Roota91203b2012-02-15 15:00:46 -08001260private:
Kenny Root655b9582013-04-04 08:37:42 -07001261 static const char* sOldMasterKey;
1262 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001263 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001264 Entropy* mEntropy;
1265
Kenny Root70e3a862012-02-15 17:20:23 -08001266 keymaster_device_t* mDevice;
1267
Kenny Root655b9582013-04-04 08:37:42 -07001268 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001269
Kenny Root655b9582013-04-04 08:37:42 -07001270 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001271
Kenny Root655b9582013-04-04 08:37:42 -07001272 typedef struct {
1273 uint32_t version;
1274 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001275
Kenny Root655b9582013-04-04 08:37:42 -07001276 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001277
Kenny Root655b9582013-04-04 08:37:42 -07001278 const grant_t* getGrant(const char* filename, uid_t uid) const {
1279 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1280 it != mGrants.end(); it++) {
1281 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001282 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001283 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001284 return grant;
1285 }
1286 }
Kenny Root70e3a862012-02-15 17:20:23 -08001287 return NULL;
1288 }
1289
Kenny Root822c3a92012-03-23 16:34:39 -07001290 /**
1291 * Upgrade code. This will upgrade the key from the current version
1292 * to whatever is newest.
1293 */
Kenny Root655b9582013-04-04 08:37:42 -07001294 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1295 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001296 bool updated = false;
1297 uint8_t version = oldVersion;
1298
1299 /* From V0 -> V1: All old types were unknown */
1300 if (version == 0) {
1301 ALOGV("upgrading to version 1 and setting type %d", type);
1302
1303 blob->setType(type);
1304 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001305 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001306 }
1307 version = 1;
1308 updated = true;
1309 }
1310
Kenny Rootf9119d62013-04-03 09:22:15 -07001311 /* From V1 -> V2: All old keys were encrypted */
1312 if (version == 1) {
1313 ALOGV("upgrading to version 2");
1314
1315 blob->setEncrypted(true);
1316 version = 2;
1317 updated = true;
1318 }
1319
Kenny Root822c3a92012-03-23 16:34:39 -07001320 /*
1321 * If we've updated, set the key blob to the right version
1322 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001323 */
Kenny Root822c3a92012-03-23 16:34:39 -07001324 if (updated) {
1325 ALOGV("updated and writing file %s", filename);
1326 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001327 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001328
1329 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001330 }
1331
1332 /**
1333 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1334 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1335 * Then it overwrites the original blob with the new blob
1336 * format that is returned from the keymaster.
1337 */
Kenny Root655b9582013-04-04 08:37:42 -07001338 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001339 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1340 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1341 if (b.get() == NULL) {
1342 ALOGE("Problem instantiating BIO");
1343 return SYSTEM_ERROR;
1344 }
1345
1346 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1347 if (pkey.get() == NULL) {
1348 ALOGE("Couldn't read old PEM file");
1349 return SYSTEM_ERROR;
1350 }
1351
1352 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1353 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1354 if (len < 0) {
1355 ALOGE("Couldn't measure PKCS#8 length");
1356 return SYSTEM_ERROR;
1357 }
1358
Kenny Root70c98892013-02-07 09:10:36 -08001359 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1360 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001361 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1362 ALOGE("Couldn't convert to PKCS#8");
1363 return SYSTEM_ERROR;
1364 }
1365
Kenny Rootf9119d62013-04-03 09:22:15 -07001366 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1367 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001368 if (rc != NO_ERROR) {
1369 return rc;
1370 }
1371
Kenny Root655b9582013-04-04 08:37:42 -07001372 return get(filename, blob, TYPE_KEY_PAIR, uid);
1373 }
1374
1375 void readMetaData() {
1376 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1377 if (in < 0) {
1378 return;
1379 }
1380 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1381 if (fileLength != sizeof(mMetaData)) {
1382 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1383 sizeof(mMetaData));
1384 }
1385 close(in);
1386 }
1387
1388 void writeMetaData() {
1389 const char* tmpFileName = ".metadata.tmp";
1390 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1391 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1392 if (out < 0) {
1393 ALOGE("couldn't write metadata file: %s", strerror(errno));
1394 return;
1395 }
1396 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1397 if (fileLength != sizeof(mMetaData)) {
1398 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1399 sizeof(mMetaData));
1400 }
1401 close(out);
1402 rename(tmpFileName, sMetaDataFile);
1403 }
1404
1405 bool upgradeKeystore() {
1406 bool upgraded = false;
1407
1408 if (mMetaData.version == 0) {
1409 UserState* userState = getUserState(0);
1410
1411 // Initialize first so the directory is made.
1412 userState->initialize();
1413
1414 // Migrate the old .masterkey file to user 0.
1415 if (access(sOldMasterKey, R_OK) == 0) {
1416 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1417 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1418 return false;
1419 }
1420 }
1421
1422 // Initialize again in case we had a key.
1423 userState->initialize();
1424
1425 // Try to migrate existing keys.
1426 DIR* dir = opendir(".");
1427 if (!dir) {
1428 // Give up now; maybe we can upgrade later.
1429 ALOGE("couldn't open keystore's directory; something is wrong");
1430 return false;
1431 }
1432
1433 struct dirent* file;
1434 while ((file = readdir(dir)) != NULL) {
1435 // We only care about files.
1436 if (file->d_type != DT_REG) {
1437 continue;
1438 }
1439
1440 // Skip anything that starts with a "."
1441 if (file->d_name[0] == '.') {
1442 continue;
1443 }
1444
1445 // Find the current file's user.
1446 char* end;
1447 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1448 if (end[0] != '_' || end[1] == 0) {
1449 continue;
1450 }
1451 UserState* otherUser = getUserState(thisUid);
1452 if (otherUser->getUserId() != 0) {
1453 unlinkat(dirfd(dir), file->d_name, 0);
1454 }
1455
1456 // Rename the file into user directory.
1457 DIR* otherdir = opendir(otherUser->getUserDirName());
1458 if (otherdir == NULL) {
1459 ALOGW("couldn't open user directory for rename");
1460 continue;
1461 }
1462 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1463 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1464 }
1465 closedir(otherdir);
1466 }
1467 closedir(dir);
1468
1469 mMetaData.version = 1;
1470 upgraded = true;
1471 }
1472
1473 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001474 }
Kenny Roota91203b2012-02-15 15:00:46 -08001475};
1476
Kenny Root655b9582013-04-04 08:37:42 -07001477const char* KeyStore::sOldMasterKey = ".masterkey";
1478const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001479
Kenny Root1b0e3932013-09-05 13:06:32 -07001480const android::String16 KeyStore::sRSAKeyType("RSA");
1481
Kenny Root07438c82012-11-02 15:41:02 -07001482namespace android {
1483class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1484public:
1485 KeyStoreProxy(KeyStore* keyStore)
1486 : mKeyStore(keyStore)
1487 {
Kenny Roota91203b2012-02-15 15:00:46 -08001488 }
Kenny Roota91203b2012-02-15 15:00:46 -08001489
Kenny Root07438c82012-11-02 15:41:02 -07001490 void binderDied(const wp<IBinder>&) {
1491 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001492 }
Kenny Roota91203b2012-02-15 15:00:46 -08001493
Kenny Root07438c82012-11-02 15:41:02 -07001494 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001495 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001496 pid_t spid = IPCThreadState::self()->getCallingPid();
1497 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001498 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001499 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001500 }
Kenny Roota91203b2012-02-15 15:00:46 -08001501
Kenny Root655b9582013-04-04 08:37:42 -07001502 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001503 }
1504
Kenny Root07438c82012-11-02 15:41:02 -07001505 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001506 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001507 pid_t spid = IPCThreadState::self()->getCallingPid();
1508 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001509 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001510 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001511 }
Kenny Root07438c82012-11-02 15:41:02 -07001512
Kenny Root07438c82012-11-02 15:41:02 -07001513 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001514 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001515
Kenny Root655b9582013-04-04 08:37:42 -07001516 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001517 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001518 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001519 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001520 *item = NULL;
1521 *itemLength = 0;
1522 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001523 }
Kenny Roota91203b2012-02-15 15:00:46 -08001524
Kenny Root07438c82012-11-02 15:41:02 -07001525 *item = (uint8_t*) malloc(keyBlob.getLength());
1526 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1527 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001528
Kenny Root07438c82012-11-02 15:41:02 -07001529 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001530 }
1531
Kenny Rootf9119d62013-04-03 09:22:15 -07001532 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1533 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001534 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001535 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001536 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001537 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001538 return ::PERMISSION_DENIED;
1539 }
Kenny Root07438c82012-11-02 15:41:02 -07001540
Kenny Rootf9119d62013-04-03 09:22:15 -07001541 State state = mKeyStore->getState(callingUid);
1542 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1543 ALOGD("calling get in state: %d", state);
1544 return state;
1545 }
1546
Kenny Root49468902013-03-19 13:41:33 -07001547 if (targetUid == -1) {
1548 targetUid = callingUid;
1549 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001550 return ::PERMISSION_DENIED;
1551 }
1552
Kenny Root07438c82012-11-02 15:41:02 -07001553 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001554 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001555
1556 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001557 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1558
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001559 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001560 }
1561
Kenny Root49468902013-03-19 13:41:33 -07001562 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001563 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001564 pid_t spid = IPCThreadState::self()->getCallingPid();
1565 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001566 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001567 return ::PERMISSION_DENIED;
1568 }
Kenny Root70e3a862012-02-15 17:20:23 -08001569
Kenny Root49468902013-03-19 13:41:33 -07001570 if (targetUid == -1) {
1571 targetUid = callingUid;
1572 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001573 return ::PERMISSION_DENIED;
1574 }
1575
Kenny Root07438c82012-11-02 15:41:02 -07001576 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001577 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001578
1579 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001580 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001581 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07001582 if (responseCode != ::NO_ERROR) {
1583 return responseCode;
1584 }
1585 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001586 }
1587
Kenny Root49468902013-03-19 13:41:33 -07001588 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001589 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001590 pid_t spid = IPCThreadState::self()->getCallingPid();
1591 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001592 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001593 return ::PERMISSION_DENIED;
1594 }
Kenny Root70e3a862012-02-15 17:20:23 -08001595
Kenny Root49468902013-03-19 13:41:33 -07001596 if (targetUid == -1) {
1597 targetUid = callingUid;
1598 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001599 return ::PERMISSION_DENIED;
1600 }
1601
Kenny Root07438c82012-11-02 15:41:02 -07001602 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001603 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001604
Kenny Root655b9582013-04-04 08:37:42 -07001605 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001606 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1607 }
1608 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001609 }
1610
Kenny Root49468902013-03-19 13:41:33 -07001611 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001612 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001613 pid_t spid = IPCThreadState::self()->getCallingPid();
1614 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001615 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001616 return ::PERMISSION_DENIED;
1617 }
Kenny Root70e3a862012-02-15 17:20:23 -08001618
Kenny Root49468902013-03-19 13:41:33 -07001619 if (targetUid == -1) {
1620 targetUid = callingUid;
1621 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001622 return ::PERMISSION_DENIED;
1623 }
1624
Kenny Root655b9582013-04-04 08:37:42 -07001625 UserState* userState = mKeyStore->getUserState(targetUid);
1626 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001627 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07001628 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001629 return ::SYSTEM_ERROR;
1630 }
Kenny Root70e3a862012-02-15 17:20:23 -08001631
Kenny Root07438c82012-11-02 15:41:02 -07001632 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001633 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1634 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001635
Kenny Root07438c82012-11-02 15:41:02 -07001636 struct dirent* file;
1637 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001638 // We only care about files.
1639 if (file->d_type != DT_REG) {
1640 continue;
1641 }
1642
1643 // Skip anything that starts with a "."
1644 if (file->d_name[0] == '.') {
1645 continue;
1646 }
1647
1648 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001649 const char* p = &file->d_name[n];
1650 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001651
Kenny Root07438c82012-11-02 15:41:02 -07001652 size_t extra = decode_key_length(p, plen);
1653 char *match = (char*) malloc(extra + 1);
1654 if (match != NULL) {
1655 decode_key(match, p, plen);
1656 matches->push(String16(match, extra));
1657 free(match);
1658 } else {
1659 ALOGW("could not allocate match of size %zd", extra);
1660 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001661 }
1662 }
Kenny Root07438c82012-11-02 15:41:02 -07001663 closedir(dir);
1664
1665 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001666 }
1667
Kenny Root07438c82012-11-02 15:41:02 -07001668 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001669 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001670 pid_t spid = IPCThreadState::self()->getCallingPid();
1671 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001672 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001673 return ::PERMISSION_DENIED;
1674 }
1675
Kenny Root655b9582013-04-04 08:37:42 -07001676 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001677
1678 const keymaster_device_t* device = mKeyStore->getDevice();
1679 if (device == NULL) {
1680 ALOGE("No keymaster device!");
1681 return ::SYSTEM_ERROR;
1682 }
1683
1684 if (device->delete_all == NULL) {
1685 ALOGV("keymaster device doesn't implement delete_all");
1686 return rc;
1687 }
1688
1689 if (device->delete_all(device)) {
1690 ALOGE("Problem calling keymaster's delete_all");
1691 return ::SYSTEM_ERROR;
1692 }
1693
Kenny Root9a53d3e2012-08-14 10:47:54 -07001694 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001695 }
1696
Kenny Root07438c82012-11-02 15:41:02 -07001697 /*
1698 * Here is the history. To improve the security, the parameters to generate the
1699 * master key has been changed. To make a seamless transition, we update the
1700 * file using the same password when the user unlock it for the first time. If
1701 * any thing goes wrong during the transition, the new file will not overwrite
1702 * the old one. This avoids permanent damages of the existing data.
1703 */
1704 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001705 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001706 pid_t spid = IPCThreadState::self()->getCallingPid();
1707 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001708 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001709 return ::PERMISSION_DENIED;
1710 }
Kenny Root70e3a862012-02-15 17:20:23 -08001711
Kenny Root07438c82012-11-02 15:41:02 -07001712 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001713
Kenny Root655b9582013-04-04 08:37:42 -07001714 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001715 case ::STATE_UNINITIALIZED: {
1716 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001717 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001718 }
1719 case ::STATE_NO_ERROR: {
1720 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001721 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001722 }
1723 case ::STATE_LOCKED: {
1724 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001725 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001726 }
1727 }
1728 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001729 }
1730
Kenny Root07438c82012-11-02 15:41:02 -07001731 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001732 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001733 pid_t spid = IPCThreadState::self()->getCallingPid();
1734 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001735 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001736 return ::PERMISSION_DENIED;
1737 }
Kenny Root70e3a862012-02-15 17:20:23 -08001738
Kenny Root655b9582013-04-04 08:37:42 -07001739 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001740 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001741 ALOGD("calling lock in state: %d", state);
1742 return state;
1743 }
1744
Kenny Root655b9582013-04-04 08:37:42 -07001745 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001746 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001747 }
1748
Kenny Root07438c82012-11-02 15:41:02 -07001749 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001750 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001751 pid_t spid = IPCThreadState::self()->getCallingPid();
1752 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001753 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001754 return ::PERMISSION_DENIED;
1755 }
1756
Kenny Root655b9582013-04-04 08:37:42 -07001757 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001758 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001759 ALOGD("calling unlock when not locked");
1760 return state;
1761 }
1762
1763 const String8 password8(pw);
1764 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001765 }
1766
Kenny Root07438c82012-11-02 15:41:02 -07001767 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001768 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001769 pid_t spid = IPCThreadState::self()->getCallingPid();
1770 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001771 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001772 return -1;
1773 }
Kenny Root70e3a862012-02-15 17:20:23 -08001774
Kenny Root655b9582013-04-04 08:37:42 -07001775 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001776 }
1777
Kenny Root96427ba2013-08-16 14:02:41 -07001778 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1779 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001780 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001781 pid_t spid = IPCThreadState::self()->getCallingPid();
1782 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001783 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001784 return ::PERMISSION_DENIED;
1785 }
Kenny Root70e3a862012-02-15 17:20:23 -08001786
Kenny Root49468902013-03-19 13:41:33 -07001787 if (targetUid == -1) {
1788 targetUid = callingUid;
1789 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001790 return ::PERMISSION_DENIED;
1791 }
1792
Kenny Root655b9582013-04-04 08:37:42 -07001793 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001794 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1795 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001796 return state;
1797 }
Kenny Root70e3a862012-02-15 17:20:23 -08001798
Kenny Root07438c82012-11-02 15:41:02 -07001799 uint8_t* data;
1800 size_t dataLength;
1801 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001802 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001803
1804 const keymaster_device_t* device = mKeyStore->getDevice();
1805 if (device == NULL) {
1806 return ::SYSTEM_ERROR;
1807 }
1808
1809 if (device->generate_keypair == NULL) {
1810 return ::SYSTEM_ERROR;
1811 }
1812
Kenny Root17208e02013-09-04 13:56:03 -07001813 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001814 keymaster_dsa_keygen_params_t dsa_params;
1815 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001816
Kenny Root96427ba2013-08-16 14:02:41 -07001817 if (keySize == -1) {
1818 keySize = DSA_DEFAULT_KEY_SIZE;
1819 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1820 || keySize > DSA_MAX_KEY_SIZE) {
1821 ALOGI("invalid key size %d", keySize);
1822 return ::SYSTEM_ERROR;
1823 }
1824 dsa_params.key_size = keySize;
1825
1826 if (args->size() == 3) {
1827 sp<KeystoreArg> gArg = args->itemAt(0);
1828 sp<KeystoreArg> pArg = args->itemAt(1);
1829 sp<KeystoreArg> qArg = args->itemAt(2);
1830
1831 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1832 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1833 dsa_params.generator_len = gArg->size();
1834
1835 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1836 dsa_params.prime_p_len = pArg->size();
1837
1838 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1839 dsa_params.prime_q_len = qArg->size();
1840 } else {
1841 ALOGI("not all DSA parameters were read");
1842 return ::SYSTEM_ERROR;
1843 }
1844 } else if (args->size() != 0) {
1845 ALOGI("DSA args must be 3");
1846 return ::SYSTEM_ERROR;
1847 }
1848
Kenny Root1d448c02013-11-21 10:36:53 -08001849 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001850 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1851 } else {
1852 isFallback = true;
1853 rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1854 }
1855 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001856 keymaster_ec_keygen_params_t ec_params;
1857 memset(&ec_params, '\0', sizeof(ec_params));
1858
1859 if (keySize == -1) {
1860 keySize = EC_DEFAULT_KEY_SIZE;
1861 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1862 ALOGI("invalid key size %d", keySize);
1863 return ::SYSTEM_ERROR;
1864 }
1865 ec_params.field_size = keySize;
1866
Kenny Root1d448c02013-11-21 10:36:53 -08001867 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001868 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1869 } else {
1870 isFallback = true;
1871 rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1872 }
Kenny Root96427ba2013-08-16 14:02:41 -07001873 } else if (keyType == EVP_PKEY_RSA) {
1874 keymaster_rsa_keygen_params_t rsa_params;
1875 memset(&rsa_params, '\0', sizeof(rsa_params));
1876 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1877
1878 if (keySize == -1) {
1879 keySize = RSA_DEFAULT_KEY_SIZE;
1880 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1881 ALOGI("invalid key size %d", keySize);
1882 return ::SYSTEM_ERROR;
1883 }
1884 rsa_params.modulus_size = keySize;
1885
1886 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001887 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001888 return ::SYSTEM_ERROR;
1889 } else if (args->size() == 1) {
1890 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1891 if (pubExpBlob != NULL) {
1892 Unique_BIGNUM pubExpBn(
1893 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1894 pubExpBlob->size(), NULL));
1895 if (pubExpBn.get() == NULL) {
1896 ALOGI("Could not convert public exponent to BN");
1897 return ::SYSTEM_ERROR;
1898 }
1899 unsigned long pubExp = BN_get_word(pubExpBn.get());
1900 if (pubExp == 0xFFFFFFFFL) {
1901 ALOGI("cannot represent public exponent as a long value");
1902 return ::SYSTEM_ERROR;
1903 }
1904 rsa_params.public_exponent = pubExp;
1905 }
1906 }
1907
1908 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1909 } else {
1910 ALOGW("Unsupported key type %d", keyType);
1911 rc = -1;
1912 }
1913
Kenny Root07438c82012-11-02 15:41:02 -07001914 if (rc) {
1915 return ::SYSTEM_ERROR;
1916 }
1917
Kenny Root655b9582013-04-04 08:37:42 -07001918 String8 name8(name);
1919 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001920
1921 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1922 free(data);
1923
Kenny Rootee8068b2013-10-07 09:49:15 -07001924 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001925 keyBlob.setFallback(isFallback);
1926
Kenny Root655b9582013-04-04 08:37:42 -07001927 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001928 }
1929
Kenny Rootf9119d62013-04-03 09:22:15 -07001930 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1931 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001932 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001933 pid_t spid = IPCThreadState::self()->getCallingPid();
1934 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001935 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001936 return ::PERMISSION_DENIED;
1937 }
Kenny Root07438c82012-11-02 15:41:02 -07001938
Kenny Root49468902013-03-19 13:41:33 -07001939 if (targetUid == -1) {
1940 targetUid = callingUid;
1941 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001942 return ::PERMISSION_DENIED;
1943 }
1944
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001945 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001946 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001947 ALOGD("calling import in state: %d", state);
1948 return state;
1949 }
1950
1951 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001952 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001953
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001954 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001955 }
1956
Kenny Root07438c82012-11-02 15:41:02 -07001957 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1958 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001959 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001960 pid_t spid = IPCThreadState::self()->getCallingPid();
1961 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001962 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001963 return ::PERMISSION_DENIED;
1964 }
Kenny Root07438c82012-11-02 15:41:02 -07001965
Kenny Root07438c82012-11-02 15:41:02 -07001966 Blob keyBlob;
1967 String8 name8(name);
1968
Kenny Rootd38a0b02013-02-13 12:59:14 -08001969 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001970 int rc;
1971
Kenny Root655b9582013-04-04 08:37:42 -07001972 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001973 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001974 if (responseCode != ::NO_ERROR) {
1975 return responseCode;
1976 }
1977
1978 const keymaster_device_t* device = mKeyStore->getDevice();
1979 if (device == NULL) {
1980 ALOGE("no keymaster device; cannot sign");
1981 return ::SYSTEM_ERROR;
1982 }
1983
1984 if (device->sign_data == NULL) {
1985 ALOGE("device doesn't implement signing");
1986 return ::SYSTEM_ERROR;
1987 }
1988
1989 keymaster_rsa_sign_params_t params;
1990 params.digest_type = DIGEST_NONE;
1991 params.padding_type = PADDING_NONE;
1992
Kenny Root17208e02013-09-04 13:56:03 -07001993 if (keyBlob.isFallback()) {
1994 rc = openssl_sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1995 length, out, outLength);
1996 } else {
1997 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1998 length, out, outLength);
1999 }
Kenny Root07438c82012-11-02 15:41:02 -07002000 if (rc) {
2001 ALOGW("device couldn't sign data");
2002 return ::SYSTEM_ERROR;
2003 }
2004
2005 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002006 }
2007
Kenny Root07438c82012-11-02 15:41:02 -07002008 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2009 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002010 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002011 pid_t spid = IPCThreadState::self()->getCallingPid();
2012 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002013 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002014 return ::PERMISSION_DENIED;
2015 }
Kenny Root70e3a862012-02-15 17:20:23 -08002016
Kenny Root655b9582013-04-04 08:37:42 -07002017 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002018 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002019 ALOGD("calling verify in state: %d", state);
2020 return state;
2021 }
Kenny Root70e3a862012-02-15 17:20:23 -08002022
Kenny Root07438c82012-11-02 15:41:02 -07002023 Blob keyBlob;
2024 String8 name8(name);
2025 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002026
Kenny Root655b9582013-04-04 08:37:42 -07002027 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002028 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002029 if (responseCode != ::NO_ERROR) {
2030 return responseCode;
2031 }
Kenny Root70e3a862012-02-15 17:20:23 -08002032
Kenny Root07438c82012-11-02 15:41:02 -07002033 const keymaster_device_t* device = mKeyStore->getDevice();
2034 if (device == NULL) {
2035 return ::SYSTEM_ERROR;
2036 }
Kenny Root70e3a862012-02-15 17:20:23 -08002037
Kenny Root07438c82012-11-02 15:41:02 -07002038 if (device->verify_data == NULL) {
2039 return ::SYSTEM_ERROR;
2040 }
Kenny Root70e3a862012-02-15 17:20:23 -08002041
Kenny Root07438c82012-11-02 15:41:02 -07002042 keymaster_rsa_sign_params_t params;
2043 params.digest_type = DIGEST_NONE;
2044 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002045
Kenny Root17208e02013-09-04 13:56:03 -07002046 if (keyBlob.isFallback()) {
2047 rc = openssl_verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2048 dataLength, signature, signatureLength);
2049 } else {
2050 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2051 dataLength, signature, signatureLength);
2052 }
Kenny Root07438c82012-11-02 15:41:02 -07002053 if (rc) {
2054 return ::SYSTEM_ERROR;
2055 } else {
2056 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002057 }
2058 }
Kenny Root07438c82012-11-02 15:41:02 -07002059
2060 /*
2061 * TODO: The abstraction between things stored in hardware and regular blobs
2062 * of data stored on the filesystem should be moved down to keystore itself.
2063 * Unfortunately the Java code that calls this has naming conventions that it
2064 * knows about. Ideally keystore shouldn't be used to store random blobs of
2065 * data.
2066 *
2067 * Until that happens, it's necessary to have a separate "get_pubkey" and
2068 * "del_key" since the Java code doesn't really communicate what it's
2069 * intentions are.
2070 */
2071 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002072 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002073 pid_t spid = IPCThreadState::self()->getCallingPid();
2074 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002075 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002076 return ::PERMISSION_DENIED;
2077 }
Kenny Root07438c82012-11-02 15:41:02 -07002078
Kenny Root07438c82012-11-02 15:41:02 -07002079 Blob keyBlob;
2080 String8 name8(name);
2081
Kenny Rootd38a0b02013-02-13 12:59:14 -08002082 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002083
Kenny Root655b9582013-04-04 08:37:42 -07002084 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002085 TYPE_KEY_PAIR);
2086 if (responseCode != ::NO_ERROR) {
2087 return responseCode;
2088 }
2089
2090 const keymaster_device_t* device = mKeyStore->getDevice();
2091 if (device == NULL) {
2092 return ::SYSTEM_ERROR;
2093 }
2094
2095 if (device->get_keypair_public == NULL) {
2096 ALOGE("device has no get_keypair_public implementation!");
2097 return ::SYSTEM_ERROR;
2098 }
2099
Kenny Root17208e02013-09-04 13:56:03 -07002100 int rc;
2101 if (keyBlob.isFallback()) {
2102 rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2103 pubkeyLength);
2104 } else {
2105 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2106 pubkeyLength);
2107 }
Kenny Root07438c82012-11-02 15:41:02 -07002108 if (rc) {
2109 return ::SYSTEM_ERROR;
2110 }
2111
2112 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002113 }
Kenny Root07438c82012-11-02 15:41:02 -07002114
Kenny Root49468902013-03-19 13:41:33 -07002115 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002116 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002117 pid_t spid = IPCThreadState::self()->getCallingPid();
2118 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002119 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002120 return ::PERMISSION_DENIED;
2121 }
Kenny Root07438c82012-11-02 15:41:02 -07002122
Kenny Root49468902013-03-19 13:41:33 -07002123 if (targetUid == -1) {
2124 targetUid = callingUid;
2125 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002126 return ::PERMISSION_DENIED;
2127 }
2128
Kenny Root07438c82012-11-02 15:41:02 -07002129 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002130 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002131
2132 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002133 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002134 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002135 if (responseCode != ::NO_ERROR) {
2136 return responseCode;
2137 }
2138
2139 ResponseCode rc = ::NO_ERROR;
2140
2141 const keymaster_device_t* device = mKeyStore->getDevice();
2142 if (device == NULL) {
2143 rc = ::SYSTEM_ERROR;
2144 } else {
2145 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002146 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Root07438c82012-11-02 15:41:02 -07002147 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2148 rc = ::SYSTEM_ERROR;
2149 }
2150 }
2151 }
2152
2153 if (rc != ::NO_ERROR) {
2154 return rc;
2155 }
2156
2157 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
2158 }
2159
2160 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002161 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002162 pid_t spid = IPCThreadState::self()->getCallingPid();
2163 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002164 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002165 return ::PERMISSION_DENIED;
2166 }
Kenny Root07438c82012-11-02 15:41:02 -07002167
Kenny Root655b9582013-04-04 08:37:42 -07002168 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002169 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002170 ALOGD("calling grant in state: %d", state);
2171 return state;
2172 }
2173
2174 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002175 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002176
Kenny Root655b9582013-04-04 08:37:42 -07002177 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002178 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2179 }
2180
Kenny Root655b9582013-04-04 08:37:42 -07002181 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002182 return ::NO_ERROR;
2183 }
2184
2185 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002186 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002187 pid_t spid = IPCThreadState::self()->getCallingPid();
2188 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002189 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002190 return ::PERMISSION_DENIED;
2191 }
Kenny Root07438c82012-11-02 15:41:02 -07002192
Kenny Root655b9582013-04-04 08:37:42 -07002193 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002194 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002195 ALOGD("calling ungrant in state: %d", state);
2196 return state;
2197 }
2198
2199 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002200 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002201
Kenny Root655b9582013-04-04 08:37:42 -07002202 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002203 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2204 }
2205
Kenny Root655b9582013-04-04 08:37:42 -07002206 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002207 }
2208
2209 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002210 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002211 pid_t spid = IPCThreadState::self()->getCallingPid();
2212 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002213 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002214 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002215 }
Kenny Root07438c82012-11-02 15:41:02 -07002216
2217 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002218 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002219
Kenny Root655b9582013-04-04 08:37:42 -07002220 if (access(filename.string(), R_OK) == -1) {
2221 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002222 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002223 }
2224
Kenny Root655b9582013-04-04 08:37:42 -07002225 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002226 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002227 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002228 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002229 }
2230
2231 struct stat s;
2232 int ret = fstat(fd, &s);
2233 close(fd);
2234 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002235 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002236 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002237 }
2238
Kenny Root36a9e232013-02-04 14:24:15 -08002239 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002240 }
2241
Kenny Rootd53bc922013-03-21 14:10:15 -07002242 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2243 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002244 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002245 pid_t spid = IPCThreadState::self()->getCallingPid();
2246 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002247 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002248 return -1L;
2249 }
2250
Kenny Root655b9582013-04-04 08:37:42 -07002251 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002252 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002253 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002254 return state;
2255 }
2256
Kenny Rootd53bc922013-03-21 14:10:15 -07002257 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2258 srcUid = callingUid;
2259 } else if (!is_granted_to(callingUid, srcUid)) {
2260 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002261 return ::PERMISSION_DENIED;
2262 }
2263
Kenny Rootd53bc922013-03-21 14:10:15 -07002264 if (destUid == -1) {
2265 destUid = callingUid;
2266 }
2267
2268 if (srcUid != destUid) {
2269 if (static_cast<uid_t>(srcUid) != callingUid) {
2270 ALOGD("can only duplicate from caller to other or to same uid: "
2271 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2272 return ::PERMISSION_DENIED;
2273 }
2274
2275 if (!is_granted_to(callingUid, destUid)) {
2276 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2277 return ::PERMISSION_DENIED;
2278 }
2279 }
2280
2281 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002282 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002283
Kenny Rootd53bc922013-03-21 14:10:15 -07002284 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002285 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002286
Kenny Root655b9582013-04-04 08:37:42 -07002287 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2288 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002289 return ::SYSTEM_ERROR;
2290 }
2291
Kenny Rootd53bc922013-03-21 14:10:15 -07002292 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002293 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002294 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002295 if (responseCode != ::NO_ERROR) {
2296 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002297 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002298
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002299 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002300 }
2301
Kenny Root1b0e3932013-09-05 13:06:32 -07002302 int32_t is_hardware_backed(const String16& keyType) {
2303 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002304 }
2305
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002306 int32_t clear_uid(int64_t targetUid64) {
2307 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002308 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002309 pid_t spid = IPCThreadState::self()->getCallingPid();
2310 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002311 ALOGW("permission denied for %d: clear_uid", callingUid);
2312 return ::PERMISSION_DENIED;
2313 }
2314
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002315 if (targetUid64 == -1) {
2316 targetUid = callingUid;
Kenny Roote17c2542014-07-30 16:59:42 -07002317 } else if (!is_self_or_system(callingUid, targetUid)) {
2318 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002319 return ::PERMISSION_DENIED;
2320 }
2321
Kenny Roota9bb5492013-04-01 16:29:11 -07002322 const keymaster_device_t* device = mKeyStore->getDevice();
2323 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002324 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002325 return ::SYSTEM_ERROR;
2326 }
2327
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002328 UserState* userState = mKeyStore->getUserState(targetUid);
Kenny Root655b9582013-04-04 08:37:42 -07002329 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota9bb5492013-04-01 16:29:11 -07002330 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07002331 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Roota9bb5492013-04-01 16:29:11 -07002332 return ::SYSTEM_ERROR;
2333 }
2334
Kenny Root655b9582013-04-04 08:37:42 -07002335 char prefix[NAME_MAX];
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002336 int n = snprintf(prefix, NAME_MAX, "%u_", targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002337
2338 ResponseCode rc = ::NO_ERROR;
2339
2340 struct dirent* file;
2341 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002342 // We only care about files.
2343 if (file->d_type != DT_REG) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002344 continue;
2345 }
2346
Kenny Root655b9582013-04-04 08:37:42 -07002347 // Skip anything that starts with a "."
2348 if (file->d_name[0] == '.') {
2349 continue;
2350 }
Kenny Roota9bb5492013-04-01 16:29:11 -07002351
Kenny Root655b9582013-04-04 08:37:42 -07002352 if (strncmp(prefix, file->d_name, n)) {
2353 continue;
2354 }
2355
2356 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Roota9bb5492013-04-01 16:29:11 -07002357 Blob keyBlob;
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002358 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, targetUid)
Kenny Root655b9582013-04-04 08:37:42 -07002359 != ::NO_ERROR) {
2360 ALOGW("couldn't open %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002361 continue;
2362 }
2363
2364 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2365 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002366 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002367 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2368 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002369 ALOGW("device couldn't remove %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002370 }
2371 }
2372 }
2373
Kenny Root5f531242013-04-12 11:31:50 -07002374 if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002375 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002376 ALOGW("couldn't unlink %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002377 }
2378 }
2379 closedir(dir);
2380
2381 return rc;
2382 }
2383
Kenny Root07438c82012-11-02 15:41:02 -07002384private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002385 inline bool isKeystoreUnlocked(State state) {
2386 switch (state) {
2387 case ::STATE_NO_ERROR:
2388 return true;
2389 case ::STATE_UNINITIALIZED:
2390 case ::STATE_LOCKED:
2391 return false;
2392 }
2393 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002394 }
2395
Kenny Root1d448c02013-11-21 10:36:53 -08002396 bool isKeyTypeSupported(const keymaster_device_t* device, keymaster_keypair_t keyType) {
2397 const int32_t device_api = device->common.module->module_api_version;
2398 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2399 switch (keyType) {
2400 case TYPE_RSA:
2401 case TYPE_DSA:
2402 case TYPE_EC:
2403 return true;
2404 default:
2405 return false;
2406 }
2407 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2408 switch (keyType) {
2409 case TYPE_RSA:
2410 return true;
2411 case TYPE_DSA:
2412 return device->flags & KEYMASTER_SUPPORTS_DSA;
2413 case TYPE_EC:
2414 return device->flags & KEYMASTER_SUPPORTS_EC;
2415 default:
2416 return false;
2417 }
2418 } else {
2419 return keyType == TYPE_RSA;
2420 }
2421 }
2422
Kenny Root07438c82012-11-02 15:41:02 -07002423 ::KeyStore* mKeyStore;
2424};
2425
2426}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002427
2428int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002429 if (argc < 2) {
2430 ALOGE("A directory must be specified!");
2431 return 1;
2432 }
2433 if (chdir(argv[1]) == -1) {
2434 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2435 return 1;
2436 }
2437
2438 Entropy entropy;
2439 if (!entropy.open()) {
2440 return 1;
2441 }
Kenny Root70e3a862012-02-15 17:20:23 -08002442
2443 keymaster_device_t* dev;
2444 if (keymaster_device_initialize(&dev)) {
2445 ALOGE("keystore keymaster could not be initialized; exiting");
2446 return 1;
2447 }
2448
Riley Spahneaabae92014-06-30 12:39:52 -07002449 ks_is_selinux_enabled = is_selinux_enabled();
2450 if (ks_is_selinux_enabled) {
2451 union selinux_callback cb;
2452 cb.func_log = selinux_log_callback;
2453 selinux_set_callback(SELINUX_CB_LOG, cb);
2454 if (getcon(&tctx) != 0) {
2455 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2456 return -1;
2457 }
2458 } else {
2459 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2460 }
2461
Kenny Root70e3a862012-02-15 17:20:23 -08002462 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002463 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002464 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2465 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2466 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2467 if (ret != android::OK) {
2468 ALOGE("Couldn't register binder service!");
2469 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002470 }
Kenny Root07438c82012-11-02 15:41:02 -07002471
2472 /*
2473 * We're the only thread in existence, so we're just going to process
2474 * Binder transaction as a single-threaded program.
2475 */
2476 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002477
2478 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002479 return 1;
2480}