blob: 50dac74a79f3ba51bb252a8ec90f9bf55d1f1dfc [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
Riley Spahneaabae92014-06-30 12:39:52 -0700228static bool keystore_selinux_check_access(uid_t uid, perm_t perm, pid_t spid) {
229 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 Root007cb232014-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 "."
854 if (file->d_name[0] == '.') {
855 continue;
856 }
857
858 // Find the current file's UID.
859 char* end;
860 unsigned long thisUid = strtoul(file->d_name, &end, 10);
861 if (end[0] != '_' || end[1] == 0) {
862 continue;
863 }
864
865 // Skip if this is not our user.
866 if (get_user_id(thisUid) != mUserId) {
867 continue;
868 }
869
870 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800871 }
872 closedir(dir);
873 return true;
874 }
875
Kenny Root655b9582013-04-04 08:37:42 -0700876private:
877 static const int MASTER_KEY_SIZE_BYTES = 16;
878 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
879
880 static const int MAX_RETRY = 4;
881 static const size_t SALT_SIZE = 16;
882
883 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
884 uint8_t* salt) {
885 size_t saltSize;
886 if (salt != NULL) {
887 saltSize = SALT_SIZE;
888 } else {
889 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
890 salt = (uint8_t*) "keystore";
891 // sizeof = 9, not strlen = 8
892 saltSize = sizeof("keystore");
893 }
894
895 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
896 saltSize, 8192, keySize, key);
897 }
898
899 bool generateSalt(Entropy* entropy) {
900 return entropy->generate_random_data(mSalt, sizeof(mSalt));
901 }
902
903 bool generateMasterKey(Entropy* entropy) {
904 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
905 return false;
906 }
907 if (!generateSalt(entropy)) {
908 return false;
909 }
910 return true;
911 }
912
913 void setupMasterKeys() {
914 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
915 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
916 setState(STATE_NO_ERROR);
917 }
918
919 uid_t mUserId;
920
921 char* mUserDir;
922 char* mMasterKeyFile;
923
924 State mState;
925 int8_t mRetry;
926
927 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
928 uint8_t mSalt[SALT_SIZE];
929
930 AES_KEY mMasterKeyEncryption;
931 AES_KEY mMasterKeyDecryption;
932};
933
934typedef struct {
935 uint32_t uid;
936 const uint8_t* filename;
937} grant_t;
938
939class KeyStore {
940public:
941 KeyStore(Entropy* entropy, keymaster_device_t* device)
942 : mEntropy(entropy)
943 , mDevice(device)
944 {
945 memset(&mMetaData, '\0', sizeof(mMetaData));
946 }
947
948 ~KeyStore() {
949 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
950 it != mGrants.end(); it++) {
951 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700952 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800953 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700954
955 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
956 it != mMasterKeys.end(); it++) {
957 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700958 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800959 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700960 }
961
962 keymaster_device_t* getDevice() const {
963 return mDevice;
964 }
965
966 ResponseCode initialize() {
967 readMetaData();
968 if (upgradeKeystore()) {
969 writeMetaData();
970 }
971
972 return ::NO_ERROR;
973 }
974
975 State getState(uid_t uid) {
976 return getUserState(uid)->getState();
977 }
978
979 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
980 UserState* userState = getUserState(uid);
981 return userState->initialize(pw, mEntropy);
982 }
983
984 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
985 uid_t user_id = get_user_id(uid);
986 UserState* userState = getUserState(user_id);
987 return userState->writeMasterKey(pw, mEntropy);
988 }
989
990 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
991 uid_t user_id = get_user_id(uid);
992 UserState* userState = getUserState(user_id);
993 return userState->readMasterKey(pw, mEntropy);
994 }
995
996 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700997 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700998 encode_key(encoded, keyName);
999 return android::String8(encoded);
1000 }
1001
1002 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001003 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001004 encode_key(encoded, keyName);
1005 return android::String8::format("%u_%s", uid, encoded);
1006 }
1007
1008 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001009 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001010 encode_key(encoded, keyName);
1011 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1012 encoded);
1013 }
1014
1015 bool reset(uid_t uid) {
1016 UserState* userState = getUserState(uid);
1017 userState->zeroizeMasterKeysInMemory();
1018 userState->setState(STATE_UNINITIALIZED);
1019 return userState->reset();
1020 }
1021
1022 bool isEmpty(uid_t uid) const {
1023 const UserState* userState = getUserState(uid);
1024 if (userState == NULL) {
1025 return true;
1026 }
1027
1028 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001029 struct dirent* file;
1030 if (!dir) {
1031 return true;
1032 }
1033 bool result = true;
Kenny Root655b9582013-04-04 08:37:42 -07001034
1035 char filename[NAME_MAX];
1036 int n = snprintf(filename, sizeof(filename), "%u_", uid);
1037
Kenny Roota91203b2012-02-15 15:00:46 -08001038 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001039 // We only care about files.
1040 if (file->d_type != DT_REG) {
1041 continue;
1042 }
1043
1044 // Skip anything that starts with a "."
1045 if (file->d_name[0] == '.') {
1046 continue;
1047 }
1048
1049 if (!strncmp(file->d_name, filename, n)) {
Kenny Roota91203b2012-02-15 15:00:46 -08001050 result = false;
1051 break;
1052 }
1053 }
1054 closedir(dir);
1055 return result;
1056 }
1057
Kenny Root655b9582013-04-04 08:37:42 -07001058 void lock(uid_t uid) {
1059 UserState* userState = getUserState(uid);
1060 userState->zeroizeMasterKeysInMemory();
1061 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001062 }
1063
Kenny Root655b9582013-04-04 08:37:42 -07001064 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1065 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001066 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1067 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001068 if (rc != NO_ERROR) {
1069 return rc;
1070 }
1071
1072 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001073 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001074 /* If we upgrade the key, we need to write it to disk again. Then
1075 * it must be read it again since the blob is encrypted each time
1076 * it's written.
1077 */
Kenny Root655b9582013-04-04 08:37:42 -07001078 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1079 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001080 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1081 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001082 return rc;
1083 }
1084 }
Kenny Root822c3a92012-03-23 16:34:39 -07001085 }
1086
Kenny Root17208e02013-09-04 13:56:03 -07001087 /*
1088 * This will upgrade software-backed keys to hardware-backed keys when
1089 * the HAL for the device supports the newer key types.
1090 */
1091 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1092 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1093 && keyBlob->isFallback()) {
1094 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1095 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1096
1097 // The HAL allowed the import, reget the key to have the "fresh"
1098 // version.
1099 if (imported == NO_ERROR) {
1100 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1101 }
1102 }
1103
Kenny Rootd53bc922013-03-21 14:10:15 -07001104 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001105 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1106 return KEY_NOT_FOUND;
1107 }
1108
1109 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001110 }
1111
Kenny Root655b9582013-04-04 08:37:42 -07001112 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1113 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001114 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1115 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001116 }
1117
Kenny Root07438c82012-11-02 15:41:02 -07001118 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001119 const grant_t* existing = getGrant(filename, granteeUid);
1120 if (existing == NULL) {
1121 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001122 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001123 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001124 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001125 }
1126 }
1127
Kenny Root07438c82012-11-02 15:41:02 -07001128 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001129 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1130 it != mGrants.end(); it++) {
1131 grant_t* grant = *it;
1132 if (grant->uid == granteeUid
1133 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1134 mGrants.erase(it);
1135 return true;
1136 }
Kenny Root70e3a862012-02-15 17:20:23 -08001137 }
Kenny Root70e3a862012-02-15 17:20:23 -08001138 return false;
1139 }
1140
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001141 bool hasGrant(const char* filename, const uid_t uid) const {
1142 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001143 }
1144
Kenny Rootf9119d62013-04-03 09:22:15 -07001145 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1146 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001147 uint8_t* data;
1148 size_t dataLength;
1149 int rc;
1150
1151 if (mDevice->import_keypair == NULL) {
1152 ALOGE("Keymaster doesn't support import!");
1153 return SYSTEM_ERROR;
1154 }
1155
Kenny Root17208e02013-09-04 13:56:03 -07001156 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001157 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001158 if (rc) {
Kenny Root17208e02013-09-04 13:56:03 -07001159 // If this is an old device HAL, try to fall back to an old version
1160 if (mDevice->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_2) {
1161 rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength);
1162 isFallback = true;
1163 }
1164
1165 if (rc) {
1166 ALOGE("Error while importing keypair: %d", rc);
1167 return SYSTEM_ERROR;
1168 }
Kenny Root822c3a92012-03-23 16:34:39 -07001169 }
1170
1171 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1172 free(data);
1173
Kenny Rootf9119d62013-04-03 09:22:15 -07001174 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001175 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001176
Kenny Root655b9582013-04-04 08:37:42 -07001177 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001178 }
1179
Kenny Root1b0e3932013-09-05 13:06:32 -07001180 bool isHardwareBacked(const android::String16& keyType) const {
1181 if (mDevice == NULL) {
1182 ALOGW("can't get keymaster device");
1183 return false;
1184 }
1185
1186 if (sRSAKeyType == keyType) {
1187 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1188 } else {
1189 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1190 && (mDevice->common.module->module_api_version
1191 >= KEYMASTER_MODULE_API_VERSION_0_2);
1192 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001193 }
1194
Kenny Root655b9582013-04-04 08:37:42 -07001195 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1196 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001197 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001198
1199 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1200 if (responseCode == NO_ERROR) {
1201 return responseCode;
1202 }
1203
1204 // If this is one of the legacy UID->UID mappings, use it.
1205 uid_t euid = get_keystore_euid(uid);
1206 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001207 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001208 responseCode = get(filepath8.string(), keyBlob, type, uid);
1209 if (responseCode == NO_ERROR) {
1210 return responseCode;
1211 }
1212 }
1213
1214 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001215 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001216 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001217 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001218 if (end[0] != '_' || end[1] == 0) {
1219 return KEY_NOT_FOUND;
1220 }
Kenny Root86b16e82013-09-09 11:15:54 -07001221 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1222 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001223 if (!hasGrant(filepath8.string(), uid)) {
1224 return responseCode;
1225 }
1226
1227 // It is a granted key. Try to load it.
1228 return get(filepath8.string(), keyBlob, type, uid);
1229 }
1230
1231 /**
1232 * Returns any existing UserState or creates it if it doesn't exist.
1233 */
1234 UserState* getUserState(uid_t uid) {
1235 uid_t userId = get_user_id(uid);
1236
1237 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1238 it != mMasterKeys.end(); it++) {
1239 UserState* state = *it;
1240 if (state->getUserId() == userId) {
1241 return state;
1242 }
1243 }
1244
1245 UserState* userState = new UserState(userId);
1246 if (!userState->initialize()) {
1247 /* There's not much we can do if initialization fails. Trying to
1248 * unlock the keystore for that user will fail as well, so any
1249 * subsequent request for this user will just return SYSTEM_ERROR.
1250 */
1251 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1252 }
1253 mMasterKeys.add(userState);
1254 return userState;
1255 }
1256
1257 /**
1258 * Returns NULL if the UserState doesn't already exist.
1259 */
1260 const UserState* getUserState(uid_t uid) const {
1261 uid_t userId = get_user_id(uid);
1262
1263 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1264 it != mMasterKeys.end(); it++) {
1265 UserState* state = *it;
1266 if (state->getUserId() == userId) {
1267 return state;
1268 }
1269 }
1270
1271 return NULL;
1272 }
1273
Kenny Roota91203b2012-02-15 15:00:46 -08001274private:
Kenny Root655b9582013-04-04 08:37:42 -07001275 static const char* sOldMasterKey;
1276 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001277 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001278 Entropy* mEntropy;
1279
Kenny Root70e3a862012-02-15 17:20:23 -08001280 keymaster_device_t* mDevice;
1281
Kenny Root655b9582013-04-04 08:37:42 -07001282 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001283
Kenny Root655b9582013-04-04 08:37:42 -07001284 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001285
Kenny Root655b9582013-04-04 08:37:42 -07001286 typedef struct {
1287 uint32_t version;
1288 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001289
Kenny Root655b9582013-04-04 08:37:42 -07001290 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001291
Kenny Root655b9582013-04-04 08:37:42 -07001292 const grant_t* getGrant(const char* filename, uid_t uid) const {
1293 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1294 it != mGrants.end(); it++) {
1295 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001296 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001297 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001298 return grant;
1299 }
1300 }
Kenny Root70e3a862012-02-15 17:20:23 -08001301 return NULL;
1302 }
1303
Kenny Root822c3a92012-03-23 16:34:39 -07001304 /**
1305 * Upgrade code. This will upgrade the key from the current version
1306 * to whatever is newest.
1307 */
Kenny Root655b9582013-04-04 08:37:42 -07001308 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1309 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001310 bool updated = false;
1311 uint8_t version = oldVersion;
1312
1313 /* From V0 -> V1: All old types were unknown */
1314 if (version == 0) {
1315 ALOGV("upgrading to version 1 and setting type %d", type);
1316
1317 blob->setType(type);
1318 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001319 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001320 }
1321 version = 1;
1322 updated = true;
1323 }
1324
Kenny Rootf9119d62013-04-03 09:22:15 -07001325 /* From V1 -> V2: All old keys were encrypted */
1326 if (version == 1) {
1327 ALOGV("upgrading to version 2");
1328
1329 blob->setEncrypted(true);
1330 version = 2;
1331 updated = true;
1332 }
1333
Kenny Root822c3a92012-03-23 16:34:39 -07001334 /*
1335 * If we've updated, set the key blob to the right version
1336 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001337 */
Kenny Root822c3a92012-03-23 16:34:39 -07001338 if (updated) {
1339 ALOGV("updated and writing file %s", filename);
1340 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001341 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001342
1343 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001344 }
1345
1346 /**
1347 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1348 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1349 * Then it overwrites the original blob with the new blob
1350 * format that is returned from the keymaster.
1351 */
Kenny Root655b9582013-04-04 08:37:42 -07001352 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001353 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1354 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1355 if (b.get() == NULL) {
1356 ALOGE("Problem instantiating BIO");
1357 return SYSTEM_ERROR;
1358 }
1359
1360 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1361 if (pkey.get() == NULL) {
1362 ALOGE("Couldn't read old PEM file");
1363 return SYSTEM_ERROR;
1364 }
1365
1366 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1367 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1368 if (len < 0) {
1369 ALOGE("Couldn't measure PKCS#8 length");
1370 return SYSTEM_ERROR;
1371 }
1372
Kenny Root70c98892013-02-07 09:10:36 -08001373 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1374 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001375 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1376 ALOGE("Couldn't convert to PKCS#8");
1377 return SYSTEM_ERROR;
1378 }
1379
Kenny Rootf9119d62013-04-03 09:22:15 -07001380 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1381 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001382 if (rc != NO_ERROR) {
1383 return rc;
1384 }
1385
Kenny Root655b9582013-04-04 08:37:42 -07001386 return get(filename, blob, TYPE_KEY_PAIR, uid);
1387 }
1388
1389 void readMetaData() {
1390 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1391 if (in < 0) {
1392 return;
1393 }
1394 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1395 if (fileLength != sizeof(mMetaData)) {
1396 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1397 sizeof(mMetaData));
1398 }
1399 close(in);
1400 }
1401
1402 void writeMetaData() {
1403 const char* tmpFileName = ".metadata.tmp";
1404 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1405 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1406 if (out < 0) {
1407 ALOGE("couldn't write metadata file: %s", strerror(errno));
1408 return;
1409 }
1410 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1411 if (fileLength != sizeof(mMetaData)) {
1412 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1413 sizeof(mMetaData));
1414 }
1415 close(out);
1416 rename(tmpFileName, sMetaDataFile);
1417 }
1418
1419 bool upgradeKeystore() {
1420 bool upgraded = false;
1421
1422 if (mMetaData.version == 0) {
1423 UserState* userState = getUserState(0);
1424
1425 // Initialize first so the directory is made.
1426 userState->initialize();
1427
1428 // Migrate the old .masterkey file to user 0.
1429 if (access(sOldMasterKey, R_OK) == 0) {
1430 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1431 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1432 return false;
1433 }
1434 }
1435
1436 // Initialize again in case we had a key.
1437 userState->initialize();
1438
1439 // Try to migrate existing keys.
1440 DIR* dir = opendir(".");
1441 if (!dir) {
1442 // Give up now; maybe we can upgrade later.
1443 ALOGE("couldn't open keystore's directory; something is wrong");
1444 return false;
1445 }
1446
1447 struct dirent* file;
1448 while ((file = readdir(dir)) != NULL) {
1449 // We only care about files.
1450 if (file->d_type != DT_REG) {
1451 continue;
1452 }
1453
1454 // Skip anything that starts with a "."
1455 if (file->d_name[0] == '.') {
1456 continue;
1457 }
1458
1459 // Find the current file's user.
1460 char* end;
1461 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1462 if (end[0] != '_' || end[1] == 0) {
1463 continue;
1464 }
1465 UserState* otherUser = getUserState(thisUid);
1466 if (otherUser->getUserId() != 0) {
1467 unlinkat(dirfd(dir), file->d_name, 0);
1468 }
1469
1470 // Rename the file into user directory.
1471 DIR* otherdir = opendir(otherUser->getUserDirName());
1472 if (otherdir == NULL) {
1473 ALOGW("couldn't open user directory for rename");
1474 continue;
1475 }
1476 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1477 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1478 }
1479 closedir(otherdir);
1480 }
1481 closedir(dir);
1482
1483 mMetaData.version = 1;
1484 upgraded = true;
1485 }
1486
1487 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001488 }
Kenny Roota91203b2012-02-15 15:00:46 -08001489};
1490
Kenny Root655b9582013-04-04 08:37:42 -07001491const char* KeyStore::sOldMasterKey = ".masterkey";
1492const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001493
Kenny Root1b0e3932013-09-05 13:06:32 -07001494const android::String16 KeyStore::sRSAKeyType("RSA");
1495
Kenny Root07438c82012-11-02 15:41:02 -07001496namespace android {
1497class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1498public:
1499 KeyStoreProxy(KeyStore* keyStore)
1500 : mKeyStore(keyStore)
1501 {
Kenny Roota91203b2012-02-15 15:00:46 -08001502 }
Kenny Roota91203b2012-02-15 15:00:46 -08001503
Kenny Root07438c82012-11-02 15:41:02 -07001504 void binderDied(const wp<IBinder>&) {
1505 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001506 }
Kenny Roota91203b2012-02-15 15:00:46 -08001507
Kenny Root07438c82012-11-02 15:41:02 -07001508 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001509 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001510 pid_t spid = IPCThreadState::self()->getCallingPid();
1511 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001512 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001513 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001514 }
Kenny Roota91203b2012-02-15 15:00:46 -08001515
Kenny Root655b9582013-04-04 08:37:42 -07001516 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001517 }
1518
Kenny Root07438c82012-11-02 15:41:02 -07001519 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001520 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001521 pid_t spid = IPCThreadState::self()->getCallingPid();
1522 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001523 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001524 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001525 }
Kenny Root07438c82012-11-02 15:41:02 -07001526
Kenny Root07438c82012-11-02 15:41:02 -07001527 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001528 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001529
Kenny Root655b9582013-04-04 08:37:42 -07001530 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001531 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001532 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001533 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001534 *item = NULL;
1535 *itemLength = 0;
1536 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001537 }
Kenny Roota91203b2012-02-15 15:00:46 -08001538
Kenny Root07438c82012-11-02 15:41:02 -07001539 *item = (uint8_t*) malloc(keyBlob.getLength());
1540 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1541 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001542
Kenny Root07438c82012-11-02 15:41:02 -07001543 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001544 }
1545
Kenny Rootf9119d62013-04-03 09:22:15 -07001546 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1547 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001548 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001549 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001550 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001551 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001552 return ::PERMISSION_DENIED;
1553 }
Kenny Root07438c82012-11-02 15:41:02 -07001554
Kenny Rootf9119d62013-04-03 09:22:15 -07001555 State state = mKeyStore->getState(callingUid);
1556 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1557 ALOGD("calling get in state: %d", state);
1558 return state;
1559 }
1560
Kenny Root49468902013-03-19 13:41:33 -07001561 if (targetUid == -1) {
1562 targetUid = callingUid;
1563 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001564 return ::PERMISSION_DENIED;
1565 }
1566
Kenny Root07438c82012-11-02 15:41:02 -07001567 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001568 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001569
1570 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001571 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1572
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001573 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001574 }
1575
Kenny Root49468902013-03-19 13:41:33 -07001576 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001577 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001578 pid_t spid = IPCThreadState::self()->getCallingPid();
1579 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001580 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001581 return ::PERMISSION_DENIED;
1582 }
Kenny Root70e3a862012-02-15 17:20:23 -08001583
Kenny Root49468902013-03-19 13:41:33 -07001584 if (targetUid == -1) {
1585 targetUid = callingUid;
1586 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001587 return ::PERMISSION_DENIED;
1588 }
1589
Kenny Root07438c82012-11-02 15:41:02 -07001590 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001591 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001592
1593 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001594 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001595 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07001596 if (responseCode != ::NO_ERROR) {
1597 return responseCode;
1598 }
1599 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001600 }
1601
Kenny Root49468902013-03-19 13:41:33 -07001602 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001603 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001604 pid_t spid = IPCThreadState::self()->getCallingPid();
1605 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001606 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001607 return ::PERMISSION_DENIED;
1608 }
Kenny Root70e3a862012-02-15 17:20:23 -08001609
Kenny Root49468902013-03-19 13:41:33 -07001610 if (targetUid == -1) {
1611 targetUid = callingUid;
1612 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001613 return ::PERMISSION_DENIED;
1614 }
1615
Kenny Root07438c82012-11-02 15:41:02 -07001616 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001617 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001618
Kenny Root655b9582013-04-04 08:37:42 -07001619 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001620 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1621 }
1622 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001623 }
1624
Kenny Root49468902013-03-19 13:41:33 -07001625 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001626 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001627 pid_t spid = IPCThreadState::self()->getCallingPid();
1628 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001629 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001630 return ::PERMISSION_DENIED;
1631 }
Kenny Root70e3a862012-02-15 17:20:23 -08001632
Kenny Root49468902013-03-19 13:41:33 -07001633 if (targetUid == -1) {
1634 targetUid = callingUid;
1635 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001636 return ::PERMISSION_DENIED;
1637 }
1638
Kenny Root655b9582013-04-04 08:37:42 -07001639 UserState* userState = mKeyStore->getUserState(targetUid);
1640 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001641 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07001642 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001643 return ::SYSTEM_ERROR;
1644 }
Kenny Root70e3a862012-02-15 17:20:23 -08001645
Kenny Root07438c82012-11-02 15:41:02 -07001646 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001647 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1648 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001649
Kenny Root07438c82012-11-02 15:41:02 -07001650 struct dirent* file;
1651 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001652 // We only care about files.
1653 if (file->d_type != DT_REG) {
1654 continue;
1655 }
1656
1657 // Skip anything that starts with a "."
1658 if (file->d_name[0] == '.') {
1659 continue;
1660 }
1661
1662 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001663 const char* p = &file->d_name[n];
1664 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001665
Kenny Root07438c82012-11-02 15:41:02 -07001666 size_t extra = decode_key_length(p, plen);
1667 char *match = (char*) malloc(extra + 1);
1668 if (match != NULL) {
1669 decode_key(match, p, plen);
1670 matches->push(String16(match, extra));
1671 free(match);
1672 } else {
1673 ALOGW("could not allocate match of size %zd", extra);
1674 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001675 }
1676 }
Kenny Root07438c82012-11-02 15:41:02 -07001677 closedir(dir);
1678
1679 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001680 }
1681
Kenny Root07438c82012-11-02 15:41:02 -07001682 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001683 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001684 pid_t spid = IPCThreadState::self()->getCallingPid();
1685 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001686 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001687 return ::PERMISSION_DENIED;
1688 }
1689
Kenny Root655b9582013-04-04 08:37:42 -07001690 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001691
1692 const keymaster_device_t* device = mKeyStore->getDevice();
1693 if (device == NULL) {
1694 ALOGE("No keymaster device!");
1695 return ::SYSTEM_ERROR;
1696 }
1697
1698 if (device->delete_all == NULL) {
1699 ALOGV("keymaster device doesn't implement delete_all");
1700 return rc;
1701 }
1702
1703 if (device->delete_all(device)) {
1704 ALOGE("Problem calling keymaster's delete_all");
1705 return ::SYSTEM_ERROR;
1706 }
1707
Kenny Root9a53d3e2012-08-14 10:47:54 -07001708 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001709 }
1710
Kenny Root07438c82012-11-02 15:41:02 -07001711 /*
1712 * Here is the history. To improve the security, the parameters to generate the
1713 * master key has been changed. To make a seamless transition, we update the
1714 * file using the same password when the user unlock it for the first time. If
1715 * any thing goes wrong during the transition, the new file will not overwrite
1716 * the old one. This avoids permanent damages of the existing data.
1717 */
1718 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001719 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001720 pid_t spid = IPCThreadState::self()->getCallingPid();
1721 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001722 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001723 return ::PERMISSION_DENIED;
1724 }
Kenny Root70e3a862012-02-15 17:20:23 -08001725
Kenny Root07438c82012-11-02 15:41:02 -07001726 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001727
Kenny Root655b9582013-04-04 08:37:42 -07001728 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001729 case ::STATE_UNINITIALIZED: {
1730 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001731 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001732 }
1733 case ::STATE_NO_ERROR: {
1734 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001735 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001736 }
1737 case ::STATE_LOCKED: {
1738 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001739 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001740 }
1741 }
1742 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001743 }
1744
Kenny Root07438c82012-11-02 15:41:02 -07001745 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001746 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001747 pid_t spid = IPCThreadState::self()->getCallingPid();
1748 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001749 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001750 return ::PERMISSION_DENIED;
1751 }
Kenny Root70e3a862012-02-15 17:20:23 -08001752
Kenny Root655b9582013-04-04 08:37:42 -07001753 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001754 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001755 ALOGD("calling lock in state: %d", state);
1756 return state;
1757 }
1758
Kenny Root655b9582013-04-04 08:37:42 -07001759 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001760 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001761 }
1762
Kenny Root07438c82012-11-02 15:41:02 -07001763 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001764 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001765 pid_t spid = IPCThreadState::self()->getCallingPid();
1766 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001767 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001768 return ::PERMISSION_DENIED;
1769 }
1770
Kenny Root655b9582013-04-04 08:37:42 -07001771 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001772 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001773 ALOGD("calling unlock when not locked");
1774 return state;
1775 }
1776
1777 const String8 password8(pw);
1778 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001779 }
1780
Kenny Root07438c82012-11-02 15:41:02 -07001781 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001782 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001783 pid_t spid = IPCThreadState::self()->getCallingPid();
1784 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001785 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001786 return -1;
1787 }
Kenny Root70e3a862012-02-15 17:20:23 -08001788
Kenny Root655b9582013-04-04 08:37:42 -07001789 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001790 }
1791
Kenny Root96427ba2013-08-16 14:02:41 -07001792 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1793 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001794 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001795 pid_t spid = IPCThreadState::self()->getCallingPid();
1796 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001797 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001798 return ::PERMISSION_DENIED;
1799 }
Kenny Root70e3a862012-02-15 17:20:23 -08001800
Kenny Root49468902013-03-19 13:41:33 -07001801 if (targetUid == -1) {
1802 targetUid = callingUid;
1803 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001804 return ::PERMISSION_DENIED;
1805 }
1806
Kenny Root655b9582013-04-04 08:37:42 -07001807 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001808 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1809 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001810 return state;
1811 }
Kenny Root70e3a862012-02-15 17:20:23 -08001812
Kenny Root07438c82012-11-02 15:41:02 -07001813 uint8_t* data;
1814 size_t dataLength;
1815 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001816 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001817
1818 const keymaster_device_t* device = mKeyStore->getDevice();
1819 if (device == NULL) {
1820 return ::SYSTEM_ERROR;
1821 }
1822
1823 if (device->generate_keypair == NULL) {
1824 return ::SYSTEM_ERROR;
1825 }
1826
Kenny Root17208e02013-09-04 13:56:03 -07001827 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001828 keymaster_dsa_keygen_params_t dsa_params;
1829 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001830
Kenny Root96427ba2013-08-16 14:02:41 -07001831 if (keySize == -1) {
1832 keySize = DSA_DEFAULT_KEY_SIZE;
1833 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1834 || keySize > DSA_MAX_KEY_SIZE) {
1835 ALOGI("invalid key size %d", keySize);
1836 return ::SYSTEM_ERROR;
1837 }
1838 dsa_params.key_size = keySize;
1839
1840 if (args->size() == 3) {
1841 sp<KeystoreArg> gArg = args->itemAt(0);
1842 sp<KeystoreArg> pArg = args->itemAt(1);
1843 sp<KeystoreArg> qArg = args->itemAt(2);
1844
1845 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1846 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1847 dsa_params.generator_len = gArg->size();
1848
1849 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1850 dsa_params.prime_p_len = pArg->size();
1851
1852 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1853 dsa_params.prime_q_len = qArg->size();
1854 } else {
1855 ALOGI("not all DSA parameters were read");
1856 return ::SYSTEM_ERROR;
1857 }
1858 } else if (args->size() != 0) {
1859 ALOGI("DSA args must be 3");
1860 return ::SYSTEM_ERROR;
1861 }
1862
Kenny Root1d448c02013-11-21 10:36:53 -08001863 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001864 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1865 } else {
1866 isFallback = true;
1867 rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1868 }
1869 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001870 keymaster_ec_keygen_params_t ec_params;
1871 memset(&ec_params, '\0', sizeof(ec_params));
1872
1873 if (keySize == -1) {
1874 keySize = EC_DEFAULT_KEY_SIZE;
1875 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1876 ALOGI("invalid key size %d", keySize);
1877 return ::SYSTEM_ERROR;
1878 }
1879 ec_params.field_size = keySize;
1880
Kenny Root1d448c02013-11-21 10:36:53 -08001881 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001882 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1883 } else {
1884 isFallback = true;
1885 rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1886 }
Kenny Root96427ba2013-08-16 14:02:41 -07001887 } else if (keyType == EVP_PKEY_RSA) {
1888 keymaster_rsa_keygen_params_t rsa_params;
1889 memset(&rsa_params, '\0', sizeof(rsa_params));
1890 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1891
1892 if (keySize == -1) {
1893 keySize = RSA_DEFAULT_KEY_SIZE;
1894 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1895 ALOGI("invalid key size %d", keySize);
1896 return ::SYSTEM_ERROR;
1897 }
1898 rsa_params.modulus_size = keySize;
1899
1900 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001901 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001902 return ::SYSTEM_ERROR;
1903 } else if (args->size() == 1) {
1904 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1905 if (pubExpBlob != NULL) {
1906 Unique_BIGNUM pubExpBn(
1907 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1908 pubExpBlob->size(), NULL));
1909 if (pubExpBn.get() == NULL) {
1910 ALOGI("Could not convert public exponent to BN");
1911 return ::SYSTEM_ERROR;
1912 }
1913 unsigned long pubExp = BN_get_word(pubExpBn.get());
1914 if (pubExp == 0xFFFFFFFFL) {
1915 ALOGI("cannot represent public exponent as a long value");
1916 return ::SYSTEM_ERROR;
1917 }
1918 rsa_params.public_exponent = pubExp;
1919 }
1920 }
1921
1922 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1923 } else {
1924 ALOGW("Unsupported key type %d", keyType);
1925 rc = -1;
1926 }
1927
Kenny Root07438c82012-11-02 15:41:02 -07001928 if (rc) {
1929 return ::SYSTEM_ERROR;
1930 }
1931
Kenny Root655b9582013-04-04 08:37:42 -07001932 String8 name8(name);
1933 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001934
1935 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1936 free(data);
1937
Kenny Rootee8068b2013-10-07 09:49:15 -07001938 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001939 keyBlob.setFallback(isFallback);
1940
Kenny Root655b9582013-04-04 08:37:42 -07001941 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001942 }
1943
Kenny Rootf9119d62013-04-03 09:22:15 -07001944 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1945 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001946 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001947 pid_t spid = IPCThreadState::self()->getCallingPid();
1948 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001949 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001950 return ::PERMISSION_DENIED;
1951 }
Kenny Root07438c82012-11-02 15:41:02 -07001952
Kenny Root49468902013-03-19 13:41:33 -07001953 if (targetUid == -1) {
1954 targetUid = callingUid;
1955 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001956 return ::PERMISSION_DENIED;
1957 }
1958
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001959 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001960 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001961 ALOGD("calling import in state: %d", state);
1962 return state;
1963 }
1964
1965 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001966 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001967
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001968 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001969 }
1970
Kenny Root07438c82012-11-02 15:41:02 -07001971 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1972 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001973 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001974 pid_t spid = IPCThreadState::self()->getCallingPid();
1975 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001976 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001977 return ::PERMISSION_DENIED;
1978 }
Kenny Root07438c82012-11-02 15:41:02 -07001979
Kenny Root07438c82012-11-02 15:41:02 -07001980 Blob keyBlob;
1981 String8 name8(name);
1982
Kenny Rootd38a0b02013-02-13 12:59:14 -08001983 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001984 int rc;
1985
Kenny Root655b9582013-04-04 08:37:42 -07001986 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001987 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001988 if (responseCode != ::NO_ERROR) {
1989 return responseCode;
1990 }
1991
1992 const keymaster_device_t* device = mKeyStore->getDevice();
1993 if (device == NULL) {
1994 ALOGE("no keymaster device; cannot sign");
1995 return ::SYSTEM_ERROR;
1996 }
1997
1998 if (device->sign_data == NULL) {
1999 ALOGE("device doesn't implement signing");
2000 return ::SYSTEM_ERROR;
2001 }
2002
2003 keymaster_rsa_sign_params_t params;
2004 params.digest_type = DIGEST_NONE;
2005 params.padding_type = PADDING_NONE;
2006
Kenny Root17208e02013-09-04 13:56:03 -07002007 if (keyBlob.isFallback()) {
2008 rc = openssl_sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2009 length, out, outLength);
2010 } else {
2011 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2012 length, out, outLength);
2013 }
Kenny Root07438c82012-11-02 15:41:02 -07002014 if (rc) {
2015 ALOGW("device couldn't sign data");
2016 return ::SYSTEM_ERROR;
2017 }
2018
2019 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002020 }
2021
Kenny Root07438c82012-11-02 15:41:02 -07002022 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2023 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002024 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002025 pid_t spid = IPCThreadState::self()->getCallingPid();
2026 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002027 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002028 return ::PERMISSION_DENIED;
2029 }
Kenny Root70e3a862012-02-15 17:20:23 -08002030
Kenny Root655b9582013-04-04 08:37:42 -07002031 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002032 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002033 ALOGD("calling verify in state: %d", state);
2034 return state;
2035 }
Kenny Root70e3a862012-02-15 17:20:23 -08002036
Kenny Root07438c82012-11-02 15:41:02 -07002037 Blob keyBlob;
2038 String8 name8(name);
2039 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002040
Kenny Root655b9582013-04-04 08:37:42 -07002041 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002042 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002043 if (responseCode != ::NO_ERROR) {
2044 return responseCode;
2045 }
Kenny Root70e3a862012-02-15 17:20:23 -08002046
Kenny Root07438c82012-11-02 15:41:02 -07002047 const keymaster_device_t* device = mKeyStore->getDevice();
2048 if (device == NULL) {
2049 return ::SYSTEM_ERROR;
2050 }
Kenny Root70e3a862012-02-15 17:20:23 -08002051
Kenny Root07438c82012-11-02 15:41:02 -07002052 if (device->verify_data == NULL) {
2053 return ::SYSTEM_ERROR;
2054 }
Kenny Root70e3a862012-02-15 17:20:23 -08002055
Kenny Root07438c82012-11-02 15:41:02 -07002056 keymaster_rsa_sign_params_t params;
2057 params.digest_type = DIGEST_NONE;
2058 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002059
Kenny Root17208e02013-09-04 13:56:03 -07002060 if (keyBlob.isFallback()) {
2061 rc = openssl_verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2062 dataLength, signature, signatureLength);
2063 } else {
2064 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2065 dataLength, signature, signatureLength);
2066 }
Kenny Root07438c82012-11-02 15:41:02 -07002067 if (rc) {
2068 return ::SYSTEM_ERROR;
2069 } else {
2070 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002071 }
2072 }
Kenny Root07438c82012-11-02 15:41:02 -07002073
2074 /*
2075 * TODO: The abstraction between things stored in hardware and regular blobs
2076 * of data stored on the filesystem should be moved down to keystore itself.
2077 * Unfortunately the Java code that calls this has naming conventions that it
2078 * knows about. Ideally keystore shouldn't be used to store random blobs of
2079 * data.
2080 *
2081 * Until that happens, it's necessary to have a separate "get_pubkey" and
2082 * "del_key" since the Java code doesn't really communicate what it's
2083 * intentions are.
2084 */
2085 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002086 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002087 pid_t spid = IPCThreadState::self()->getCallingPid();
2088 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002089 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002090 return ::PERMISSION_DENIED;
2091 }
Kenny Root07438c82012-11-02 15:41:02 -07002092
Kenny Root07438c82012-11-02 15:41:02 -07002093 Blob keyBlob;
2094 String8 name8(name);
2095
Kenny Rootd38a0b02013-02-13 12:59:14 -08002096 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002097
Kenny Root655b9582013-04-04 08:37:42 -07002098 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002099 TYPE_KEY_PAIR);
2100 if (responseCode != ::NO_ERROR) {
2101 return responseCode;
2102 }
2103
2104 const keymaster_device_t* device = mKeyStore->getDevice();
2105 if (device == NULL) {
2106 return ::SYSTEM_ERROR;
2107 }
2108
2109 if (device->get_keypair_public == NULL) {
2110 ALOGE("device has no get_keypair_public implementation!");
2111 return ::SYSTEM_ERROR;
2112 }
2113
Kenny Root17208e02013-09-04 13:56:03 -07002114 int rc;
2115 if (keyBlob.isFallback()) {
2116 rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2117 pubkeyLength);
2118 } else {
2119 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2120 pubkeyLength);
2121 }
Kenny Root07438c82012-11-02 15:41:02 -07002122 if (rc) {
2123 return ::SYSTEM_ERROR;
2124 }
2125
2126 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002127 }
Kenny Root07438c82012-11-02 15:41:02 -07002128
Kenny Root49468902013-03-19 13:41:33 -07002129 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002130 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002131 pid_t spid = IPCThreadState::self()->getCallingPid();
2132 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002133 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002134 return ::PERMISSION_DENIED;
2135 }
Kenny Root07438c82012-11-02 15:41:02 -07002136
Kenny Root49468902013-03-19 13:41:33 -07002137 if (targetUid == -1) {
2138 targetUid = callingUid;
2139 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002140 return ::PERMISSION_DENIED;
2141 }
2142
Kenny Root07438c82012-11-02 15:41:02 -07002143 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002144 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002145
2146 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002147 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002148 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002149 if (responseCode != ::NO_ERROR) {
2150 return responseCode;
2151 }
2152
2153 ResponseCode rc = ::NO_ERROR;
2154
2155 const keymaster_device_t* device = mKeyStore->getDevice();
2156 if (device == NULL) {
2157 rc = ::SYSTEM_ERROR;
2158 } else {
2159 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002160 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Root07438c82012-11-02 15:41:02 -07002161 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2162 rc = ::SYSTEM_ERROR;
2163 }
2164 }
2165 }
2166
2167 if (rc != ::NO_ERROR) {
2168 return rc;
2169 }
2170
2171 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
2172 }
2173
2174 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002175 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002176 pid_t spid = IPCThreadState::self()->getCallingPid();
2177 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002178 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002179 return ::PERMISSION_DENIED;
2180 }
Kenny Root07438c82012-11-02 15:41:02 -07002181
Kenny Root655b9582013-04-04 08:37:42 -07002182 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002183 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002184 ALOGD("calling grant in state: %d", state);
2185 return state;
2186 }
2187
2188 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002189 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002190
Kenny Root655b9582013-04-04 08:37:42 -07002191 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002192 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2193 }
2194
Kenny Root655b9582013-04-04 08:37:42 -07002195 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002196 return ::NO_ERROR;
2197 }
2198
2199 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002200 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002201 pid_t spid = IPCThreadState::self()->getCallingPid();
2202 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002203 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002204 return ::PERMISSION_DENIED;
2205 }
Kenny Root07438c82012-11-02 15:41:02 -07002206
Kenny Root655b9582013-04-04 08:37:42 -07002207 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002208 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002209 ALOGD("calling ungrant in state: %d", state);
2210 return state;
2211 }
2212
2213 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002214 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002215
Kenny Root655b9582013-04-04 08:37:42 -07002216 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002217 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2218 }
2219
Kenny Root655b9582013-04-04 08:37:42 -07002220 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002221 }
2222
2223 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002224 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002225 pid_t spid = IPCThreadState::self()->getCallingPid();
2226 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002227 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002228 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002229 }
Kenny Root07438c82012-11-02 15:41:02 -07002230
2231 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002232 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002233
Kenny Root655b9582013-04-04 08:37:42 -07002234 if (access(filename.string(), R_OK) == -1) {
2235 ALOGW("could not access %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 Root655b9582013-04-04 08:37:42 -07002239 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002240 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002241 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002242 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002243 }
2244
2245 struct stat s;
2246 int ret = fstat(fd, &s);
2247 close(fd);
2248 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002249 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002250 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002251 }
2252
Kenny Root36a9e232013-02-04 14:24:15 -08002253 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002254 }
2255
Kenny Rootd53bc922013-03-21 14:10:15 -07002256 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2257 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002258 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002259 pid_t spid = IPCThreadState::self()->getCallingPid();
2260 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002261 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002262 return -1L;
2263 }
2264
Kenny Root655b9582013-04-04 08:37:42 -07002265 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002266 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002267 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002268 return state;
2269 }
2270
Kenny Rootd53bc922013-03-21 14:10:15 -07002271 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2272 srcUid = callingUid;
2273 } else if (!is_granted_to(callingUid, srcUid)) {
2274 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002275 return ::PERMISSION_DENIED;
2276 }
2277
Kenny Rootd53bc922013-03-21 14:10:15 -07002278 if (destUid == -1) {
2279 destUid = callingUid;
2280 }
2281
2282 if (srcUid != destUid) {
2283 if (static_cast<uid_t>(srcUid) != callingUid) {
2284 ALOGD("can only duplicate from caller to other or to same uid: "
2285 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2286 return ::PERMISSION_DENIED;
2287 }
2288
2289 if (!is_granted_to(callingUid, destUid)) {
2290 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2291 return ::PERMISSION_DENIED;
2292 }
2293 }
2294
2295 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002296 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002297
Kenny Rootd53bc922013-03-21 14:10:15 -07002298 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002299 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002300
Kenny Root655b9582013-04-04 08:37:42 -07002301 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2302 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002303 return ::SYSTEM_ERROR;
2304 }
2305
Kenny Rootd53bc922013-03-21 14:10:15 -07002306 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002307 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002308 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002309 if (responseCode != ::NO_ERROR) {
2310 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002311 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002312
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002313 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002314 }
2315
Kenny Root1b0e3932013-09-05 13:06:32 -07002316 int32_t is_hardware_backed(const String16& keyType) {
2317 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002318 }
2319
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002320 int32_t clear_uid(int64_t targetUid64) {
2321 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002322 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002323 pid_t spid = IPCThreadState::self()->getCallingPid();
2324 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002325 ALOGW("permission denied for %d: clear_uid", callingUid);
2326 return ::PERMISSION_DENIED;
2327 }
2328
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002329 if (targetUid64 == -1) {
2330 targetUid = callingUid;
Kenny Root007cb232014-07-30 16:59:42 -07002331 } else if (!is_self_or_system(callingUid, targetUid)) {
2332 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002333 return ::PERMISSION_DENIED;
2334 }
2335
Kenny Roota9bb5492013-04-01 16:29:11 -07002336 const keymaster_device_t* device = mKeyStore->getDevice();
2337 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002338 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002339 return ::SYSTEM_ERROR;
2340 }
2341
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002342 UserState* userState = mKeyStore->getUserState(targetUid);
Kenny Root655b9582013-04-04 08:37:42 -07002343 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota9bb5492013-04-01 16:29:11 -07002344 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07002345 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Roota9bb5492013-04-01 16:29:11 -07002346 return ::SYSTEM_ERROR;
2347 }
2348
Kenny Root655b9582013-04-04 08:37:42 -07002349 char prefix[NAME_MAX];
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002350 int n = snprintf(prefix, NAME_MAX, "%u_", targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002351
2352 ResponseCode rc = ::NO_ERROR;
2353
2354 struct dirent* file;
2355 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002356 // We only care about files.
2357 if (file->d_type != DT_REG) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002358 continue;
2359 }
2360
Kenny Root655b9582013-04-04 08:37:42 -07002361 // Skip anything that starts with a "."
2362 if (file->d_name[0] == '.') {
2363 continue;
2364 }
Kenny Roota9bb5492013-04-01 16:29:11 -07002365
Kenny Root655b9582013-04-04 08:37:42 -07002366 if (strncmp(prefix, file->d_name, n)) {
2367 continue;
2368 }
2369
2370 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Roota9bb5492013-04-01 16:29:11 -07002371 Blob keyBlob;
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002372 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, targetUid)
Kenny Root655b9582013-04-04 08:37:42 -07002373 != ::NO_ERROR) {
2374 ALOGW("couldn't open %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002375 continue;
2376 }
2377
2378 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2379 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002380 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002381 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2382 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002383 ALOGW("device couldn't remove %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002384 }
2385 }
2386 }
2387
Kenny Root5f531242013-04-12 11:31:50 -07002388 if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002389 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002390 ALOGW("couldn't unlink %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002391 }
2392 }
2393 closedir(dir);
2394
2395 return rc;
2396 }
2397
Kenny Root07438c82012-11-02 15:41:02 -07002398private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002399 inline bool isKeystoreUnlocked(State state) {
2400 switch (state) {
2401 case ::STATE_NO_ERROR:
2402 return true;
2403 case ::STATE_UNINITIALIZED:
2404 case ::STATE_LOCKED:
2405 return false;
2406 }
2407 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002408 }
2409
Kenny Root1d448c02013-11-21 10:36:53 -08002410 bool isKeyTypeSupported(const keymaster_device_t* device, keymaster_keypair_t keyType) {
2411 const int32_t device_api = device->common.module->module_api_version;
2412 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2413 switch (keyType) {
2414 case TYPE_RSA:
2415 case TYPE_DSA:
2416 case TYPE_EC:
2417 return true;
2418 default:
2419 return false;
2420 }
2421 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2422 switch (keyType) {
2423 case TYPE_RSA:
2424 return true;
2425 case TYPE_DSA:
2426 return device->flags & KEYMASTER_SUPPORTS_DSA;
2427 case TYPE_EC:
2428 return device->flags & KEYMASTER_SUPPORTS_EC;
2429 default:
2430 return false;
2431 }
2432 } else {
2433 return keyType == TYPE_RSA;
2434 }
2435 }
2436
Kenny Root07438c82012-11-02 15:41:02 -07002437 ::KeyStore* mKeyStore;
2438};
2439
2440}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002441
2442int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002443 if (argc < 2) {
2444 ALOGE("A directory must be specified!");
2445 return 1;
2446 }
2447 if (chdir(argv[1]) == -1) {
2448 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2449 return 1;
2450 }
2451
2452 Entropy entropy;
2453 if (!entropy.open()) {
2454 return 1;
2455 }
Kenny Root70e3a862012-02-15 17:20:23 -08002456
2457 keymaster_device_t* dev;
2458 if (keymaster_device_initialize(&dev)) {
2459 ALOGE("keystore keymaster could not be initialized; exiting");
2460 return 1;
2461 }
2462
Riley Spahneaabae92014-06-30 12:39:52 -07002463 ks_is_selinux_enabled = is_selinux_enabled();
2464 if (ks_is_selinux_enabled) {
2465 union selinux_callback cb;
2466 cb.func_log = selinux_log_callback;
2467 selinux_set_callback(SELINUX_CB_LOG, cb);
2468 if (getcon(&tctx) != 0) {
2469 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2470 return -1;
2471 }
2472 } else {
2473 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2474 }
2475
Kenny Root70e3a862012-02-15 17:20:23 -08002476 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002477 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002478 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2479 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2480 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2481 if (ret != android::OK) {
2482 ALOGE("Couldn't register binder service!");
2483 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002484 }
Kenny Root07438c82012-11-02 15:41:02 -07002485
2486 /*
2487 * We're the only thread in existence, so we're just going to process
2488 * Binder transaction as a single-threaded program.
2489 */
2490 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002491
2492 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002493 return 1;
2494}