blob: fd6af0dd79dadb9eb035256bb208131c1b5b1631 [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 Roota91203b2012-02-15 15:00:46 -0800301/* Here is the encoding of keys. This is necessary in order to allow arbitrary
302 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
303 * into two bytes. The first byte is one of [+-.] which represents the first
304 * two bits of the character. The second byte encodes the rest of the bits into
305 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
306 * that Base64 cannot be used here due to the need of prefix match on keys. */
307
Kenny Root655b9582013-04-04 08:37:42 -0700308static size_t encode_key_length(const android::String8& keyName) {
309 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
310 size_t length = keyName.length();
311 for (int i = length; i > 0; --i, ++in) {
312 if (*in < '0' || *in > '~') {
313 ++length;
314 }
315 }
316 return length;
317}
318
Kenny Root07438c82012-11-02 15:41:02 -0700319static int encode_key(char* out, const android::String8& keyName) {
320 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
321 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800322 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700323 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800324 *out = '+' + (*in >> 6);
325 *++out = '0' + (*in & 0x3F);
326 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700327 } else {
328 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800329 }
330 }
331 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800332 return length;
333}
334
Kenny Root07438c82012-11-02 15:41:02 -0700335/*
336 * Converts from the "escaped" format on disk to actual name.
337 * This will be smaller than the input string.
338 *
339 * Characters that should combine with the next at the end will be truncated.
340 */
341static size_t decode_key_length(const char* in, size_t length) {
342 size_t outLength = 0;
343
344 for (const char* end = in + length; in < end; in++) {
345 /* This combines with the next character. */
346 if (*in < '0' || *in > '~') {
347 continue;
348 }
349
350 outLength++;
351 }
352 return outLength;
353}
354
355static void decode_key(char* out, const char* in, size_t length) {
356 for (const char* end = in + length; in < end; in++) {
357 if (*in < '0' || *in > '~') {
358 /* Truncate combining characters at the end. */
359 if (in + 1 >= end) {
360 break;
361 }
362
363 *out = (*in++ - '+') << 6;
364 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800365 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700366 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800367 }
368 }
369 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800370}
371
372static size_t readFully(int fd, uint8_t* data, size_t size) {
373 size_t remaining = size;
374 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800375 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800376 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800377 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800378 }
379 data += n;
380 remaining -= n;
381 }
382 return size;
383}
384
385static size_t writeFully(int fd, uint8_t* data, size_t size) {
386 size_t remaining = size;
387 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800388 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
389 if (n < 0) {
390 ALOGW("write failed: %s", strerror(errno));
391 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800392 }
393 data += n;
394 remaining -= n;
395 }
396 return size;
397}
398
399class Entropy {
400public:
401 Entropy() : mRandom(-1) {}
402 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800403 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800404 close(mRandom);
405 }
406 }
407
408 bool open() {
409 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800410 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
411 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800412 ALOGE("open: %s: %s", randomDevice, strerror(errno));
413 return false;
414 }
415 return true;
416 }
417
Kenny Root51878182012-03-13 12:53:19 -0700418 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800419 return (readFully(mRandom, data, size) == size);
420 }
421
422private:
423 int mRandom;
424};
425
426/* Here is the file format. There are two parts in blob.value, the secret and
427 * the description. The secret is stored in ciphertext, and its original size
428 * can be found in blob.length. The description is stored after the secret in
429 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700430 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700431 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800432 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
433 * and decryptBlob(). Thus they should not be accessed from outside. */
434
Kenny Root822c3a92012-03-23 16:34:39 -0700435/* ** Note to future implementors of encryption: **
436 * Currently this is the construction:
437 * metadata || Enc(MD5(data) || data)
438 *
439 * This should be the construction used for encrypting if re-implementing:
440 *
441 * Derive independent keys for encryption and MAC:
442 * Kenc = AES_encrypt(masterKey, "Encrypt")
443 * Kmac = AES_encrypt(masterKey, "MAC")
444 *
445 * Store this:
446 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
447 * HMAC(Kmac, metadata || Enc(data))
448 */
Kenny Roota91203b2012-02-15 15:00:46 -0800449struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700450 uint8_t version;
451 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700452 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800453 uint8_t info;
454 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700455 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800456 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700457 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800458 int32_t length; // in network byte order when encrypted
459 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
460};
461
Kenny Root822c3a92012-03-23 16:34:39 -0700462typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700463 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700464 TYPE_GENERIC = 1,
465 TYPE_MASTER_KEY = 2,
466 TYPE_KEY_PAIR = 3,
467} BlobType;
468
Kenny Rootf9119d62013-04-03 09:22:15 -0700469static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700470
Kenny Roota91203b2012-02-15 15:00:46 -0800471class Blob {
472public:
Kenny Root07438c82012-11-02 15:41:02 -0700473 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
474 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800475 mBlob.length = valueLength;
476 memcpy(mBlob.value, value, valueLength);
477
478 mBlob.info = infoLength;
479 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700480
Kenny Root07438c82012-11-02 15:41:02 -0700481 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700482 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700483
Kenny Rootee8068b2013-10-07 09:49:15 -0700484 if (type == TYPE_MASTER_KEY) {
485 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
486 } else {
487 mBlob.flags = KEYSTORE_FLAG_NONE;
488 }
Kenny Roota91203b2012-02-15 15:00:46 -0800489 }
490
491 Blob(blob b) {
492 mBlob = b;
493 }
494
495 Blob() {}
496
Kenny Root51878182012-03-13 12:53:19 -0700497 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800498 return mBlob.value;
499 }
500
Kenny Root51878182012-03-13 12:53:19 -0700501 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800502 return mBlob.length;
503 }
504
Kenny Root51878182012-03-13 12:53:19 -0700505 const uint8_t* getInfo() const {
506 return mBlob.value + mBlob.length;
507 }
508
509 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800510 return mBlob.info;
511 }
512
Kenny Root822c3a92012-03-23 16:34:39 -0700513 uint8_t getVersion() const {
514 return mBlob.version;
515 }
516
Kenny Rootf9119d62013-04-03 09:22:15 -0700517 bool isEncrypted() const {
518 if (mBlob.version < 2) {
519 return true;
520 }
521
522 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
523 }
524
525 void setEncrypted(bool encrypted) {
526 if (encrypted) {
527 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
528 } else {
529 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
530 }
531 }
532
Kenny Root17208e02013-09-04 13:56:03 -0700533 bool isFallback() const {
534 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
535 }
536
537 void setFallback(bool fallback) {
538 if (fallback) {
539 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
540 } else {
541 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
542 }
543 }
544
Kenny Root822c3a92012-03-23 16:34:39 -0700545 void setVersion(uint8_t version) {
546 mBlob.version = version;
547 }
548
549 BlobType getType() const {
550 return BlobType(mBlob.type);
551 }
552
553 void setType(BlobType type) {
554 mBlob.type = uint8_t(type);
555 }
556
Kenny Rootf9119d62013-04-03 09:22:15 -0700557 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
558 ALOGV("writing blob %s", filename);
559 if (isEncrypted()) {
560 if (state != STATE_NO_ERROR) {
561 ALOGD("couldn't insert encrypted blob while not unlocked");
562 return LOCKED;
563 }
564
565 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
566 ALOGW("Could not read random data for: %s", filename);
567 return SYSTEM_ERROR;
568 }
Kenny Roota91203b2012-02-15 15:00:46 -0800569 }
570
571 // data includes the value and the value's length
572 size_t dataLength = mBlob.length + sizeof(mBlob.length);
573 // pad data to the AES_BLOCK_SIZE
574 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
575 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
576 // encrypted data includes the digest value
577 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
578 // move info after space for padding
579 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
580 // zero padding area
581 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
582
583 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800584
Kenny Rootf9119d62013-04-03 09:22:15 -0700585 if (isEncrypted()) {
586 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800587
Kenny Rootf9119d62013-04-03 09:22:15 -0700588 uint8_t vector[AES_BLOCK_SIZE];
589 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
590 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
591 aes_key, vector, AES_ENCRYPT);
592 }
593
Kenny Roota91203b2012-02-15 15:00:46 -0800594 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
595 size_t fileLength = encryptedLength + headerLength + mBlob.info;
596
597 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800598 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
599 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
600 if (out < 0) {
601 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800602 return SYSTEM_ERROR;
603 }
604 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
605 if (close(out) != 0) {
606 return SYSTEM_ERROR;
607 }
608 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800609 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800610 unlink(tmpFileName);
611 return SYSTEM_ERROR;
612 }
Kenny Root150ca932012-11-14 14:29:02 -0800613 if (rename(tmpFileName, filename) == -1) {
614 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
615 return SYSTEM_ERROR;
616 }
617 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800618 }
619
Kenny Rootf9119d62013-04-03 09:22:15 -0700620 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
621 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800622 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
623 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800624 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
625 }
626 // fileLength may be less than sizeof(mBlob) since the in
627 // memory version has extra padding to tolerate rounding up to
628 // the AES_BLOCK_SIZE
629 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
630 if (close(in) != 0) {
631 return SYSTEM_ERROR;
632 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700633
634 if (isEncrypted() && (state != STATE_NO_ERROR)) {
635 return LOCKED;
636 }
637
Kenny Roota91203b2012-02-15 15:00:46 -0800638 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
639 if (fileLength < headerLength) {
640 return VALUE_CORRUPTED;
641 }
642
643 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700644 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800645 return VALUE_CORRUPTED;
646 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700647
648 ssize_t digestedLength;
649 if (isEncrypted()) {
650 if (encryptedLength % AES_BLOCK_SIZE != 0) {
651 return VALUE_CORRUPTED;
652 }
653
654 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
655 mBlob.vector, AES_DECRYPT);
656 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
657 uint8_t computedDigest[MD5_DIGEST_LENGTH];
658 MD5(mBlob.digested, digestedLength, computedDigest);
659 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
660 return VALUE_CORRUPTED;
661 }
662 } else {
663 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800664 }
665
666 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
667 mBlob.length = ntohl(mBlob.length);
668 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
669 return VALUE_CORRUPTED;
670 }
671 if (mBlob.info != 0) {
672 // move info from after padding to after data
673 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
674 }
Kenny Root07438c82012-11-02 15:41:02 -0700675 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800676 }
677
678private:
679 struct blob mBlob;
680};
681
Kenny Root655b9582013-04-04 08:37:42 -0700682class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800683public:
Kenny Root655b9582013-04-04 08:37:42 -0700684 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
685 asprintf(&mUserDir, "user_%u", mUserId);
686 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
687 }
688
689 ~UserState() {
690 free(mUserDir);
691 free(mMasterKeyFile);
692 }
693
694 bool initialize() {
695 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
696 ALOGE("Could not create directory '%s'", mUserDir);
697 return false;
698 }
699
700 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800701 setState(STATE_LOCKED);
702 } else {
703 setState(STATE_UNINITIALIZED);
704 }
Kenny Root70e3a862012-02-15 17:20:23 -0800705
Kenny Root655b9582013-04-04 08:37:42 -0700706 return true;
707 }
708
709 uid_t getUserId() const {
710 return mUserId;
711 }
712
713 const char* getUserDirName() const {
714 return mUserDir;
715 }
716
717 const char* getMasterKeyFileName() const {
718 return mMasterKeyFile;
719 }
720
721 void setState(State state) {
722 mState = state;
723 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
724 mRetry = MAX_RETRY;
725 }
Kenny Roota91203b2012-02-15 15:00:46 -0800726 }
727
Kenny Root51878182012-03-13 12:53:19 -0700728 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800729 return mState;
730 }
731
Kenny Root51878182012-03-13 12:53:19 -0700732 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800733 return mRetry;
734 }
735
Kenny Root655b9582013-04-04 08:37:42 -0700736 void zeroizeMasterKeysInMemory() {
737 memset(mMasterKey, 0, sizeof(mMasterKey));
738 memset(mSalt, 0, sizeof(mSalt));
739 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
740 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800741 }
742
Kenny Root655b9582013-04-04 08:37:42 -0700743 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
744 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800745 return SYSTEM_ERROR;
746 }
Kenny Root655b9582013-04-04 08:37:42 -0700747 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800748 if (response != NO_ERROR) {
749 return response;
750 }
751 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700752 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800753 }
754
Kenny Root655b9582013-04-04 08:37:42 -0700755 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800756 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
757 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
758 AES_KEY passwordAesKey;
759 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700760 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700761 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800762 }
763
Kenny Root655b9582013-04-04 08:37:42 -0700764 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
765 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800766 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800767 return SYSTEM_ERROR;
768 }
769
770 // we read the raw blob to just to get the salt to generate
771 // the AES key, then we create the Blob to use with decryptBlob
772 blob rawBlob;
773 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
774 if (close(in) != 0) {
775 return SYSTEM_ERROR;
776 }
777 // find salt at EOF if present, otherwise we have an old file
778 uint8_t* salt;
779 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
780 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
781 } else {
782 salt = NULL;
783 }
784 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
785 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
786 AES_KEY passwordAesKey;
787 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
788 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700789 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
790 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800791 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700792 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800793 }
794 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
795 // if salt was missing, generate one and write a new master key file with the salt.
796 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700797 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800798 return SYSTEM_ERROR;
799 }
Kenny Root655b9582013-04-04 08:37:42 -0700800 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800801 }
802 if (response == NO_ERROR) {
803 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
804 setupMasterKeys();
805 }
806 return response;
807 }
808 if (mRetry <= 0) {
809 reset();
810 return UNINITIALIZED;
811 }
812 --mRetry;
813 switch (mRetry) {
814 case 0: return WRONG_PASSWORD_0;
815 case 1: return WRONG_PASSWORD_1;
816 case 2: return WRONG_PASSWORD_2;
817 case 3: return WRONG_PASSWORD_3;
818 default: return WRONG_PASSWORD_3;
819 }
820 }
821
Kenny Root655b9582013-04-04 08:37:42 -0700822 AES_KEY* getEncryptionKey() {
823 return &mMasterKeyEncryption;
824 }
825
826 AES_KEY* getDecryptionKey() {
827 return &mMasterKeyDecryption;
828 }
829
Kenny Roota91203b2012-02-15 15:00:46 -0800830 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700831 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800832 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700833 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800834 return false;
835 }
Kenny Root655b9582013-04-04 08:37:42 -0700836
837 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800838 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700839 // We only care about files.
840 if (file->d_type != DT_REG) {
841 continue;
842 }
843
844 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700845 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700846 continue;
847 }
848
849 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800850 }
851 closedir(dir);
852 return true;
853 }
854
Kenny Root655b9582013-04-04 08:37:42 -0700855private:
856 static const int MASTER_KEY_SIZE_BYTES = 16;
857 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
858
859 static const int MAX_RETRY = 4;
860 static const size_t SALT_SIZE = 16;
861
862 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
863 uint8_t* salt) {
864 size_t saltSize;
865 if (salt != NULL) {
866 saltSize = SALT_SIZE;
867 } else {
868 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
869 salt = (uint8_t*) "keystore";
870 // sizeof = 9, not strlen = 8
871 saltSize = sizeof("keystore");
872 }
873
874 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
875 saltSize, 8192, keySize, key);
876 }
877
878 bool generateSalt(Entropy* entropy) {
879 return entropy->generate_random_data(mSalt, sizeof(mSalt));
880 }
881
882 bool generateMasterKey(Entropy* entropy) {
883 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
884 return false;
885 }
886 if (!generateSalt(entropy)) {
887 return false;
888 }
889 return true;
890 }
891
892 void setupMasterKeys() {
893 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
894 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
895 setState(STATE_NO_ERROR);
896 }
897
898 uid_t mUserId;
899
900 char* mUserDir;
901 char* mMasterKeyFile;
902
903 State mState;
904 int8_t mRetry;
905
906 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
907 uint8_t mSalt[SALT_SIZE];
908
909 AES_KEY mMasterKeyEncryption;
910 AES_KEY mMasterKeyDecryption;
911};
912
913typedef struct {
914 uint32_t uid;
915 const uint8_t* filename;
916} grant_t;
917
918class KeyStore {
919public:
920 KeyStore(Entropy* entropy, keymaster_device_t* device)
921 : mEntropy(entropy)
922 , mDevice(device)
923 {
924 memset(&mMetaData, '\0', sizeof(mMetaData));
925 }
926
927 ~KeyStore() {
928 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
929 it != mGrants.end(); it++) {
930 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700931 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800932 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700933
934 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
935 it != mMasterKeys.end(); it++) {
936 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700937 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800938 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700939 }
940
941 keymaster_device_t* getDevice() const {
942 return mDevice;
943 }
944
945 ResponseCode initialize() {
946 readMetaData();
947 if (upgradeKeystore()) {
948 writeMetaData();
949 }
950
951 return ::NO_ERROR;
952 }
953
954 State getState(uid_t uid) {
955 return getUserState(uid)->getState();
956 }
957
958 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
959 UserState* userState = getUserState(uid);
960 return userState->initialize(pw, mEntropy);
961 }
962
963 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
964 uid_t user_id = get_user_id(uid);
965 UserState* userState = getUserState(user_id);
966 return userState->writeMasterKey(pw, mEntropy);
967 }
968
969 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
970 uid_t user_id = get_user_id(uid);
971 UserState* userState = getUserState(user_id);
972 return userState->readMasterKey(pw, mEntropy);
973 }
974
975 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700976 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700977 encode_key(encoded, keyName);
978 return android::String8(encoded);
979 }
980
981 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700982 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700983 encode_key(encoded, keyName);
984 return android::String8::format("%u_%s", uid, encoded);
985 }
986
987 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700988 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700989 encode_key(encoded, keyName);
990 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
991 encoded);
992 }
993
994 bool reset(uid_t uid) {
995 UserState* userState = getUserState(uid);
996 userState->zeroizeMasterKeysInMemory();
997 userState->setState(STATE_UNINITIALIZED);
998 return userState->reset();
999 }
1000
1001 bool isEmpty(uid_t uid) const {
1002 const UserState* userState = getUserState(uid);
1003 if (userState == NULL) {
1004 return true;
1005 }
1006
1007 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001008 struct dirent* file;
1009 if (!dir) {
1010 return true;
1011 }
1012 bool result = true;
Kenny Root655b9582013-04-04 08:37:42 -07001013
1014 char filename[NAME_MAX];
1015 int n = snprintf(filename, sizeof(filename), "%u_", uid);
1016
Kenny Roota91203b2012-02-15 15:00:46 -08001017 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001018 // We only care about files.
1019 if (file->d_type != DT_REG) {
1020 continue;
1021 }
1022
1023 // Skip anything that starts with a "."
1024 if (file->d_name[0] == '.') {
1025 continue;
1026 }
1027
1028 if (!strncmp(file->d_name, filename, n)) {
Kenny Roota91203b2012-02-15 15:00:46 -08001029 result = false;
1030 break;
1031 }
1032 }
1033 closedir(dir);
1034 return result;
1035 }
1036
Kenny Root655b9582013-04-04 08:37:42 -07001037 void lock(uid_t uid) {
1038 UserState* userState = getUserState(uid);
1039 userState->zeroizeMasterKeysInMemory();
1040 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001041 }
1042
Kenny Root655b9582013-04-04 08:37:42 -07001043 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1044 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001045 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1046 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001047 if (rc != NO_ERROR) {
1048 return rc;
1049 }
1050
1051 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001052 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001053 /* If we upgrade the key, we need to write it to disk again. Then
1054 * it must be read it again since the blob is encrypted each time
1055 * it's written.
1056 */
Kenny Root655b9582013-04-04 08:37:42 -07001057 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1058 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001059 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1060 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001061 return rc;
1062 }
1063 }
Kenny Root822c3a92012-03-23 16:34:39 -07001064 }
1065
Kenny Root17208e02013-09-04 13:56:03 -07001066 /*
1067 * This will upgrade software-backed keys to hardware-backed keys when
1068 * the HAL for the device supports the newer key types.
1069 */
1070 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1071 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1072 && keyBlob->isFallback()) {
1073 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1074 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1075
1076 // The HAL allowed the import, reget the key to have the "fresh"
1077 // version.
1078 if (imported == NO_ERROR) {
1079 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1080 }
1081 }
1082
Kenny Rootd53bc922013-03-21 14:10:15 -07001083 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001084 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1085 return KEY_NOT_FOUND;
1086 }
1087
1088 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001089 }
1090
Kenny Root655b9582013-04-04 08:37:42 -07001091 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1092 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001093 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1094 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001095 }
1096
Kenny Root07438c82012-11-02 15:41:02 -07001097 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001098 const grant_t* existing = getGrant(filename, granteeUid);
1099 if (existing == NULL) {
1100 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001101 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001102 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001103 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001104 }
1105 }
1106
Kenny Root07438c82012-11-02 15:41:02 -07001107 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001108 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1109 it != mGrants.end(); it++) {
1110 grant_t* grant = *it;
1111 if (grant->uid == granteeUid
1112 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1113 mGrants.erase(it);
1114 return true;
1115 }
Kenny Root70e3a862012-02-15 17:20:23 -08001116 }
Kenny Root70e3a862012-02-15 17:20:23 -08001117 return false;
1118 }
1119
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001120 bool hasGrant(const char* filename, const uid_t uid) const {
1121 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001122 }
1123
Kenny Rootf9119d62013-04-03 09:22:15 -07001124 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1125 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001126 uint8_t* data;
1127 size_t dataLength;
1128 int rc;
1129
1130 if (mDevice->import_keypair == NULL) {
1131 ALOGE("Keymaster doesn't support import!");
1132 return SYSTEM_ERROR;
1133 }
1134
Kenny Root17208e02013-09-04 13:56:03 -07001135 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001136 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001137 if (rc) {
Kenny Root17208e02013-09-04 13:56:03 -07001138 // If this is an old device HAL, try to fall back to an old version
1139 if (mDevice->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_2) {
1140 rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength);
1141 isFallback = true;
1142 }
1143
1144 if (rc) {
1145 ALOGE("Error while importing keypair: %d", rc);
1146 return SYSTEM_ERROR;
1147 }
Kenny Root822c3a92012-03-23 16:34:39 -07001148 }
1149
1150 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1151 free(data);
1152
Kenny Rootf9119d62013-04-03 09:22:15 -07001153 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001154 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001155
Kenny Root655b9582013-04-04 08:37:42 -07001156 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001157 }
1158
Kenny Root1b0e3932013-09-05 13:06:32 -07001159 bool isHardwareBacked(const android::String16& keyType) const {
1160 if (mDevice == NULL) {
1161 ALOGW("can't get keymaster device");
1162 return false;
1163 }
1164
1165 if (sRSAKeyType == keyType) {
1166 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1167 } else {
1168 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1169 && (mDevice->common.module->module_api_version
1170 >= KEYMASTER_MODULE_API_VERSION_0_2);
1171 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001172 }
1173
Kenny Root655b9582013-04-04 08:37:42 -07001174 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1175 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001176 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001177
1178 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1179 if (responseCode == NO_ERROR) {
1180 return responseCode;
1181 }
1182
1183 // If this is one of the legacy UID->UID mappings, use it.
1184 uid_t euid = get_keystore_euid(uid);
1185 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001186 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001187 responseCode = get(filepath8.string(), keyBlob, type, uid);
1188 if (responseCode == NO_ERROR) {
1189 return responseCode;
1190 }
1191 }
1192
1193 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001194 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001195 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001196 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001197 if (end[0] != '_' || end[1] == 0) {
1198 return KEY_NOT_FOUND;
1199 }
Kenny Root86b16e82013-09-09 11:15:54 -07001200 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1201 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001202 if (!hasGrant(filepath8.string(), uid)) {
1203 return responseCode;
1204 }
1205
1206 // It is a granted key. Try to load it.
1207 return get(filepath8.string(), keyBlob, type, uid);
1208 }
1209
1210 /**
1211 * Returns any existing UserState or creates it if it doesn't exist.
1212 */
1213 UserState* getUserState(uid_t uid) {
1214 uid_t userId = get_user_id(uid);
1215
1216 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1217 it != mMasterKeys.end(); it++) {
1218 UserState* state = *it;
1219 if (state->getUserId() == userId) {
1220 return state;
1221 }
1222 }
1223
1224 UserState* userState = new UserState(userId);
1225 if (!userState->initialize()) {
1226 /* There's not much we can do if initialization fails. Trying to
1227 * unlock the keystore for that user will fail as well, so any
1228 * subsequent request for this user will just return SYSTEM_ERROR.
1229 */
1230 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1231 }
1232 mMasterKeys.add(userState);
1233 return userState;
1234 }
1235
1236 /**
1237 * Returns NULL if the UserState doesn't already exist.
1238 */
1239 const UserState* getUserState(uid_t uid) const {
1240 uid_t userId = get_user_id(uid);
1241
1242 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1243 it != mMasterKeys.end(); it++) {
1244 UserState* state = *it;
1245 if (state->getUserId() == userId) {
1246 return state;
1247 }
1248 }
1249
1250 return NULL;
1251 }
1252
Kenny Roota91203b2012-02-15 15:00:46 -08001253private:
Kenny Root655b9582013-04-04 08:37:42 -07001254 static const char* sOldMasterKey;
1255 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001256 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001257 Entropy* mEntropy;
1258
Kenny Root70e3a862012-02-15 17:20:23 -08001259 keymaster_device_t* mDevice;
1260
Kenny Root655b9582013-04-04 08:37:42 -07001261 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001262
Kenny Root655b9582013-04-04 08:37:42 -07001263 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001264
Kenny Root655b9582013-04-04 08:37:42 -07001265 typedef struct {
1266 uint32_t version;
1267 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001268
Kenny Root655b9582013-04-04 08:37:42 -07001269 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001270
Kenny Root655b9582013-04-04 08:37:42 -07001271 const grant_t* getGrant(const char* filename, uid_t uid) const {
1272 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1273 it != mGrants.end(); it++) {
1274 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001275 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001276 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001277 return grant;
1278 }
1279 }
Kenny Root70e3a862012-02-15 17:20:23 -08001280 return NULL;
1281 }
1282
Kenny Root822c3a92012-03-23 16:34:39 -07001283 /**
1284 * Upgrade code. This will upgrade the key from the current version
1285 * to whatever is newest.
1286 */
Kenny Root655b9582013-04-04 08:37:42 -07001287 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1288 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001289 bool updated = false;
1290 uint8_t version = oldVersion;
1291
1292 /* From V0 -> V1: All old types were unknown */
1293 if (version == 0) {
1294 ALOGV("upgrading to version 1 and setting type %d", type);
1295
1296 blob->setType(type);
1297 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001298 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001299 }
1300 version = 1;
1301 updated = true;
1302 }
1303
Kenny Rootf9119d62013-04-03 09:22:15 -07001304 /* From V1 -> V2: All old keys were encrypted */
1305 if (version == 1) {
1306 ALOGV("upgrading to version 2");
1307
1308 blob->setEncrypted(true);
1309 version = 2;
1310 updated = true;
1311 }
1312
Kenny Root822c3a92012-03-23 16:34:39 -07001313 /*
1314 * If we've updated, set the key blob to the right version
1315 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001316 */
Kenny Root822c3a92012-03-23 16:34:39 -07001317 if (updated) {
1318 ALOGV("updated and writing file %s", filename);
1319 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001320 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001321
1322 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001323 }
1324
1325 /**
1326 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1327 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1328 * Then it overwrites the original blob with the new blob
1329 * format that is returned from the keymaster.
1330 */
Kenny Root655b9582013-04-04 08:37:42 -07001331 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001332 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1333 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1334 if (b.get() == NULL) {
1335 ALOGE("Problem instantiating BIO");
1336 return SYSTEM_ERROR;
1337 }
1338
1339 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1340 if (pkey.get() == NULL) {
1341 ALOGE("Couldn't read old PEM file");
1342 return SYSTEM_ERROR;
1343 }
1344
1345 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1346 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1347 if (len < 0) {
1348 ALOGE("Couldn't measure PKCS#8 length");
1349 return SYSTEM_ERROR;
1350 }
1351
Kenny Root70c98892013-02-07 09:10:36 -08001352 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1353 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001354 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1355 ALOGE("Couldn't convert to PKCS#8");
1356 return SYSTEM_ERROR;
1357 }
1358
Kenny Rootf9119d62013-04-03 09:22:15 -07001359 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1360 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001361 if (rc != NO_ERROR) {
1362 return rc;
1363 }
1364
Kenny Root655b9582013-04-04 08:37:42 -07001365 return get(filename, blob, TYPE_KEY_PAIR, uid);
1366 }
1367
1368 void readMetaData() {
1369 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1370 if (in < 0) {
1371 return;
1372 }
1373 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1374 if (fileLength != sizeof(mMetaData)) {
1375 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1376 sizeof(mMetaData));
1377 }
1378 close(in);
1379 }
1380
1381 void writeMetaData() {
1382 const char* tmpFileName = ".metadata.tmp";
1383 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1384 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1385 if (out < 0) {
1386 ALOGE("couldn't write metadata file: %s", strerror(errno));
1387 return;
1388 }
1389 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1390 if (fileLength != sizeof(mMetaData)) {
1391 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1392 sizeof(mMetaData));
1393 }
1394 close(out);
1395 rename(tmpFileName, sMetaDataFile);
1396 }
1397
1398 bool upgradeKeystore() {
1399 bool upgraded = false;
1400
1401 if (mMetaData.version == 0) {
1402 UserState* userState = getUserState(0);
1403
1404 // Initialize first so the directory is made.
1405 userState->initialize();
1406
1407 // Migrate the old .masterkey file to user 0.
1408 if (access(sOldMasterKey, R_OK) == 0) {
1409 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1410 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1411 return false;
1412 }
1413 }
1414
1415 // Initialize again in case we had a key.
1416 userState->initialize();
1417
1418 // Try to migrate existing keys.
1419 DIR* dir = opendir(".");
1420 if (!dir) {
1421 // Give up now; maybe we can upgrade later.
1422 ALOGE("couldn't open keystore's directory; something is wrong");
1423 return false;
1424 }
1425
1426 struct dirent* file;
1427 while ((file = readdir(dir)) != NULL) {
1428 // We only care about files.
1429 if (file->d_type != DT_REG) {
1430 continue;
1431 }
1432
1433 // Skip anything that starts with a "."
1434 if (file->d_name[0] == '.') {
1435 continue;
1436 }
1437
1438 // Find the current file's user.
1439 char* end;
1440 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1441 if (end[0] != '_' || end[1] == 0) {
1442 continue;
1443 }
1444 UserState* otherUser = getUserState(thisUid);
1445 if (otherUser->getUserId() != 0) {
1446 unlinkat(dirfd(dir), file->d_name, 0);
1447 }
1448
1449 // Rename the file into user directory.
1450 DIR* otherdir = opendir(otherUser->getUserDirName());
1451 if (otherdir == NULL) {
1452 ALOGW("couldn't open user directory for rename");
1453 continue;
1454 }
1455 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1456 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1457 }
1458 closedir(otherdir);
1459 }
1460 closedir(dir);
1461
1462 mMetaData.version = 1;
1463 upgraded = true;
1464 }
1465
1466 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001467 }
Kenny Roota91203b2012-02-15 15:00:46 -08001468};
1469
Kenny Root655b9582013-04-04 08:37:42 -07001470const char* KeyStore::sOldMasterKey = ".masterkey";
1471const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001472
Kenny Root1b0e3932013-09-05 13:06:32 -07001473const android::String16 KeyStore::sRSAKeyType("RSA");
1474
Kenny Root07438c82012-11-02 15:41:02 -07001475namespace android {
1476class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1477public:
1478 KeyStoreProxy(KeyStore* keyStore)
1479 : mKeyStore(keyStore)
1480 {
Kenny Roota91203b2012-02-15 15:00:46 -08001481 }
Kenny Roota91203b2012-02-15 15:00:46 -08001482
Kenny Root07438c82012-11-02 15:41:02 -07001483 void binderDied(const wp<IBinder>&) {
1484 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001485 }
Kenny Roota91203b2012-02-15 15:00:46 -08001486
Kenny Root07438c82012-11-02 15:41:02 -07001487 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001488 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001489 pid_t spid = IPCThreadState::self()->getCallingPid();
1490 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001491 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001492 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001493 }
Kenny Roota91203b2012-02-15 15:00:46 -08001494
Kenny Root655b9582013-04-04 08:37:42 -07001495 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001496 }
1497
Kenny Root07438c82012-11-02 15:41:02 -07001498 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001499 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001500 pid_t spid = IPCThreadState::self()->getCallingPid();
1501 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001502 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001503 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001504 }
Kenny Root07438c82012-11-02 15:41:02 -07001505
Kenny Root07438c82012-11-02 15:41:02 -07001506 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001507 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001508
Kenny Root655b9582013-04-04 08:37:42 -07001509 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001510 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001511 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001512 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001513 *item = NULL;
1514 *itemLength = 0;
1515 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001516 }
Kenny Roota91203b2012-02-15 15:00:46 -08001517
Kenny Root07438c82012-11-02 15:41:02 -07001518 *item = (uint8_t*) malloc(keyBlob.getLength());
1519 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1520 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001521
Kenny Root07438c82012-11-02 15:41:02 -07001522 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001523 }
1524
Kenny Rootf9119d62013-04-03 09:22:15 -07001525 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1526 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001527 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001528 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001529 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001530 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001531 return ::PERMISSION_DENIED;
1532 }
Kenny Root07438c82012-11-02 15:41:02 -07001533
Kenny Rootf9119d62013-04-03 09:22:15 -07001534 State state = mKeyStore->getState(callingUid);
1535 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1536 ALOGD("calling get in state: %d", state);
1537 return state;
1538 }
1539
Kenny Root49468902013-03-19 13:41:33 -07001540 if (targetUid == -1) {
1541 targetUid = callingUid;
1542 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001543 return ::PERMISSION_DENIED;
1544 }
1545
Kenny Root07438c82012-11-02 15:41:02 -07001546 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001547 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001548
1549 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001550 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1551
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001552 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001553 }
1554
Kenny Root49468902013-03-19 13:41:33 -07001555 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001556 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001557 pid_t spid = IPCThreadState::self()->getCallingPid();
1558 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001559 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001560 return ::PERMISSION_DENIED;
1561 }
Kenny Root70e3a862012-02-15 17:20:23 -08001562
Kenny Root49468902013-03-19 13:41:33 -07001563 if (targetUid == -1) {
1564 targetUid = callingUid;
1565 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001566 return ::PERMISSION_DENIED;
1567 }
1568
Kenny Root07438c82012-11-02 15:41:02 -07001569 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001570 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001571
1572 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001573 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001574 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07001575 if (responseCode != ::NO_ERROR) {
1576 return responseCode;
1577 }
1578 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001579 }
1580
Kenny Root49468902013-03-19 13:41:33 -07001581 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001582 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001583 pid_t spid = IPCThreadState::self()->getCallingPid();
1584 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001585 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001586 return ::PERMISSION_DENIED;
1587 }
Kenny Root70e3a862012-02-15 17:20:23 -08001588
Kenny Root49468902013-03-19 13:41:33 -07001589 if (targetUid == -1) {
1590 targetUid = callingUid;
1591 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001592 return ::PERMISSION_DENIED;
1593 }
1594
Kenny Root07438c82012-11-02 15:41:02 -07001595 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001596 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001597
Kenny Root655b9582013-04-04 08:37:42 -07001598 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001599 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1600 }
1601 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001602 }
1603
Kenny Root49468902013-03-19 13:41:33 -07001604 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001605 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001606 pid_t spid = IPCThreadState::self()->getCallingPid();
1607 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001608 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001609 return ::PERMISSION_DENIED;
1610 }
Kenny Root70e3a862012-02-15 17:20:23 -08001611
Kenny Root49468902013-03-19 13:41:33 -07001612 if (targetUid == -1) {
1613 targetUid = callingUid;
1614 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001615 return ::PERMISSION_DENIED;
1616 }
1617
Kenny Root655b9582013-04-04 08:37:42 -07001618 UserState* userState = mKeyStore->getUserState(targetUid);
1619 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001620 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07001621 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001622 return ::SYSTEM_ERROR;
1623 }
Kenny Root70e3a862012-02-15 17:20:23 -08001624
Kenny Root07438c82012-11-02 15:41:02 -07001625 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001626 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1627 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001628
Kenny Root07438c82012-11-02 15:41:02 -07001629 struct dirent* file;
1630 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001631 // We only care about files.
1632 if (file->d_type != DT_REG) {
1633 continue;
1634 }
1635
1636 // Skip anything that starts with a "."
1637 if (file->d_name[0] == '.') {
1638 continue;
1639 }
1640
1641 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001642 const char* p = &file->d_name[n];
1643 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001644
Kenny Root07438c82012-11-02 15:41:02 -07001645 size_t extra = decode_key_length(p, plen);
1646 char *match = (char*) malloc(extra + 1);
1647 if (match != NULL) {
1648 decode_key(match, p, plen);
1649 matches->push(String16(match, extra));
1650 free(match);
1651 } else {
1652 ALOGW("could not allocate match of size %zd", extra);
1653 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001654 }
1655 }
Kenny Root07438c82012-11-02 15:41:02 -07001656 closedir(dir);
1657
1658 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001659 }
1660
Kenny Root07438c82012-11-02 15:41:02 -07001661 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001662 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001663 pid_t spid = IPCThreadState::self()->getCallingPid();
1664 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001665 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001666 return ::PERMISSION_DENIED;
1667 }
1668
Kenny Root655b9582013-04-04 08:37:42 -07001669 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001670
1671 const keymaster_device_t* device = mKeyStore->getDevice();
1672 if (device == NULL) {
1673 ALOGE("No keymaster device!");
1674 return ::SYSTEM_ERROR;
1675 }
1676
1677 if (device->delete_all == NULL) {
1678 ALOGV("keymaster device doesn't implement delete_all");
1679 return rc;
1680 }
1681
1682 if (device->delete_all(device)) {
1683 ALOGE("Problem calling keymaster's delete_all");
1684 return ::SYSTEM_ERROR;
1685 }
1686
Kenny Root9a53d3e2012-08-14 10:47:54 -07001687 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001688 }
1689
Kenny Root07438c82012-11-02 15:41:02 -07001690 /*
1691 * Here is the history. To improve the security, the parameters to generate the
1692 * master key has been changed. To make a seamless transition, we update the
1693 * file using the same password when the user unlock it for the first time. If
1694 * any thing goes wrong during the transition, the new file will not overwrite
1695 * the old one. This avoids permanent damages of the existing data.
1696 */
1697 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001698 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001699 pid_t spid = IPCThreadState::self()->getCallingPid();
1700 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001701 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001702 return ::PERMISSION_DENIED;
1703 }
Kenny Root70e3a862012-02-15 17:20:23 -08001704
Kenny Root07438c82012-11-02 15:41:02 -07001705 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001706
Kenny Root655b9582013-04-04 08:37:42 -07001707 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001708 case ::STATE_UNINITIALIZED: {
1709 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001710 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001711 }
1712 case ::STATE_NO_ERROR: {
1713 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001714 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001715 }
1716 case ::STATE_LOCKED: {
1717 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001718 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001719 }
1720 }
1721 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001722 }
1723
Kenny Root07438c82012-11-02 15:41:02 -07001724 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001725 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001726 pid_t spid = IPCThreadState::self()->getCallingPid();
1727 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001728 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001729 return ::PERMISSION_DENIED;
1730 }
Kenny Root70e3a862012-02-15 17:20:23 -08001731
Kenny Root655b9582013-04-04 08:37:42 -07001732 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001733 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001734 ALOGD("calling lock in state: %d", state);
1735 return state;
1736 }
1737
Kenny Root655b9582013-04-04 08:37:42 -07001738 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001739 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001740 }
1741
Kenny Root07438c82012-11-02 15:41:02 -07001742 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001743 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001744 pid_t spid = IPCThreadState::self()->getCallingPid();
1745 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001746 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001747 return ::PERMISSION_DENIED;
1748 }
1749
Kenny Root655b9582013-04-04 08:37:42 -07001750 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001751 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001752 ALOGD("calling unlock when not locked");
1753 return state;
1754 }
1755
1756 const String8 password8(pw);
1757 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001758 }
1759
Kenny Root07438c82012-11-02 15:41:02 -07001760 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001761 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001762 pid_t spid = IPCThreadState::self()->getCallingPid();
1763 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001764 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001765 return -1;
1766 }
Kenny Root70e3a862012-02-15 17:20:23 -08001767
Kenny Root655b9582013-04-04 08:37:42 -07001768 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001769 }
1770
Kenny Root96427ba2013-08-16 14:02:41 -07001771 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1772 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001773 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001774 pid_t spid = IPCThreadState::self()->getCallingPid();
1775 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001776 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001777 return ::PERMISSION_DENIED;
1778 }
Kenny Root70e3a862012-02-15 17:20:23 -08001779
Kenny Root49468902013-03-19 13:41:33 -07001780 if (targetUid == -1) {
1781 targetUid = callingUid;
1782 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001783 return ::PERMISSION_DENIED;
1784 }
1785
Kenny Root655b9582013-04-04 08:37:42 -07001786 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001787 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1788 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001789 return state;
1790 }
Kenny Root70e3a862012-02-15 17:20:23 -08001791
Kenny Root07438c82012-11-02 15:41:02 -07001792 uint8_t* data;
1793 size_t dataLength;
1794 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001795 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001796
1797 const keymaster_device_t* device = mKeyStore->getDevice();
1798 if (device == NULL) {
1799 return ::SYSTEM_ERROR;
1800 }
1801
1802 if (device->generate_keypair == NULL) {
1803 return ::SYSTEM_ERROR;
1804 }
1805
Kenny Root17208e02013-09-04 13:56:03 -07001806 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001807 keymaster_dsa_keygen_params_t dsa_params;
1808 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001809
Kenny Root96427ba2013-08-16 14:02:41 -07001810 if (keySize == -1) {
1811 keySize = DSA_DEFAULT_KEY_SIZE;
1812 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1813 || keySize > DSA_MAX_KEY_SIZE) {
1814 ALOGI("invalid key size %d", keySize);
1815 return ::SYSTEM_ERROR;
1816 }
1817 dsa_params.key_size = keySize;
1818
1819 if (args->size() == 3) {
1820 sp<KeystoreArg> gArg = args->itemAt(0);
1821 sp<KeystoreArg> pArg = args->itemAt(1);
1822 sp<KeystoreArg> qArg = args->itemAt(2);
1823
1824 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1825 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1826 dsa_params.generator_len = gArg->size();
1827
1828 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1829 dsa_params.prime_p_len = pArg->size();
1830
1831 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1832 dsa_params.prime_q_len = qArg->size();
1833 } else {
1834 ALOGI("not all DSA parameters were read");
1835 return ::SYSTEM_ERROR;
1836 }
1837 } else if (args->size() != 0) {
1838 ALOGI("DSA args must be 3");
1839 return ::SYSTEM_ERROR;
1840 }
1841
Kenny Root1d448c02013-11-21 10:36:53 -08001842 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001843 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1844 } else {
1845 isFallback = true;
1846 rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1847 }
1848 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001849 keymaster_ec_keygen_params_t ec_params;
1850 memset(&ec_params, '\0', sizeof(ec_params));
1851
1852 if (keySize == -1) {
1853 keySize = EC_DEFAULT_KEY_SIZE;
1854 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1855 ALOGI("invalid key size %d", keySize);
1856 return ::SYSTEM_ERROR;
1857 }
1858 ec_params.field_size = keySize;
1859
Kenny Root1d448c02013-11-21 10:36:53 -08001860 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001861 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1862 } else {
1863 isFallback = true;
1864 rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1865 }
Kenny Root96427ba2013-08-16 14:02:41 -07001866 } else if (keyType == EVP_PKEY_RSA) {
1867 keymaster_rsa_keygen_params_t rsa_params;
1868 memset(&rsa_params, '\0', sizeof(rsa_params));
1869 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1870
1871 if (keySize == -1) {
1872 keySize = RSA_DEFAULT_KEY_SIZE;
1873 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1874 ALOGI("invalid key size %d", keySize);
1875 return ::SYSTEM_ERROR;
1876 }
1877 rsa_params.modulus_size = keySize;
1878
1879 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001880 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001881 return ::SYSTEM_ERROR;
1882 } else if (args->size() == 1) {
1883 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1884 if (pubExpBlob != NULL) {
1885 Unique_BIGNUM pubExpBn(
1886 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1887 pubExpBlob->size(), NULL));
1888 if (pubExpBn.get() == NULL) {
1889 ALOGI("Could not convert public exponent to BN");
1890 return ::SYSTEM_ERROR;
1891 }
1892 unsigned long pubExp = BN_get_word(pubExpBn.get());
1893 if (pubExp == 0xFFFFFFFFL) {
1894 ALOGI("cannot represent public exponent as a long value");
1895 return ::SYSTEM_ERROR;
1896 }
1897 rsa_params.public_exponent = pubExp;
1898 }
1899 }
1900
1901 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1902 } else {
1903 ALOGW("Unsupported key type %d", keyType);
1904 rc = -1;
1905 }
1906
Kenny Root07438c82012-11-02 15:41:02 -07001907 if (rc) {
1908 return ::SYSTEM_ERROR;
1909 }
1910
Kenny Root655b9582013-04-04 08:37:42 -07001911 String8 name8(name);
1912 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001913
1914 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1915 free(data);
1916
Kenny Rootee8068b2013-10-07 09:49:15 -07001917 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001918 keyBlob.setFallback(isFallback);
1919
Kenny Root655b9582013-04-04 08:37:42 -07001920 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001921 }
1922
Kenny Rootf9119d62013-04-03 09:22:15 -07001923 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1924 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001925 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001926 pid_t spid = IPCThreadState::self()->getCallingPid();
1927 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001928 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001929 return ::PERMISSION_DENIED;
1930 }
Kenny Root07438c82012-11-02 15:41:02 -07001931
Kenny Root49468902013-03-19 13:41:33 -07001932 if (targetUid == -1) {
1933 targetUid = callingUid;
1934 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001935 return ::PERMISSION_DENIED;
1936 }
1937
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001938 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001939 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001940 ALOGD("calling import in state: %d", state);
1941 return state;
1942 }
1943
1944 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001945 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001946
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001947 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001948 }
1949
Kenny Root07438c82012-11-02 15:41:02 -07001950 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1951 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001952 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001953 pid_t spid = IPCThreadState::self()->getCallingPid();
1954 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001955 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001956 return ::PERMISSION_DENIED;
1957 }
Kenny Root07438c82012-11-02 15:41:02 -07001958
Kenny Root07438c82012-11-02 15:41:02 -07001959 Blob keyBlob;
1960 String8 name8(name);
1961
Kenny Rootd38a0b02013-02-13 12:59:14 -08001962 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001963 int rc;
1964
Kenny Root655b9582013-04-04 08:37:42 -07001965 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001966 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001967 if (responseCode != ::NO_ERROR) {
1968 return responseCode;
1969 }
1970
1971 const keymaster_device_t* device = mKeyStore->getDevice();
1972 if (device == NULL) {
1973 ALOGE("no keymaster device; cannot sign");
1974 return ::SYSTEM_ERROR;
1975 }
1976
1977 if (device->sign_data == NULL) {
1978 ALOGE("device doesn't implement signing");
1979 return ::SYSTEM_ERROR;
1980 }
1981
1982 keymaster_rsa_sign_params_t params;
1983 params.digest_type = DIGEST_NONE;
1984 params.padding_type = PADDING_NONE;
1985
Kenny Root17208e02013-09-04 13:56:03 -07001986 if (keyBlob.isFallback()) {
1987 rc = openssl_sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1988 length, out, outLength);
1989 } else {
1990 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1991 length, out, outLength);
1992 }
Kenny Root07438c82012-11-02 15:41:02 -07001993 if (rc) {
1994 ALOGW("device couldn't sign data");
1995 return ::SYSTEM_ERROR;
1996 }
1997
1998 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001999 }
2000
Kenny Root07438c82012-11-02 15:41:02 -07002001 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2002 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002003 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002004 pid_t spid = IPCThreadState::self()->getCallingPid();
2005 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002006 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002007 return ::PERMISSION_DENIED;
2008 }
Kenny Root70e3a862012-02-15 17:20:23 -08002009
Kenny Root655b9582013-04-04 08:37:42 -07002010 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002011 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002012 ALOGD("calling verify in state: %d", state);
2013 return state;
2014 }
Kenny Root70e3a862012-02-15 17:20:23 -08002015
Kenny Root07438c82012-11-02 15:41:02 -07002016 Blob keyBlob;
2017 String8 name8(name);
2018 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002019
Kenny Root655b9582013-04-04 08:37:42 -07002020 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002021 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002022 if (responseCode != ::NO_ERROR) {
2023 return responseCode;
2024 }
Kenny Root70e3a862012-02-15 17:20:23 -08002025
Kenny Root07438c82012-11-02 15:41:02 -07002026 const keymaster_device_t* device = mKeyStore->getDevice();
2027 if (device == NULL) {
2028 return ::SYSTEM_ERROR;
2029 }
Kenny Root70e3a862012-02-15 17:20:23 -08002030
Kenny Root07438c82012-11-02 15:41:02 -07002031 if (device->verify_data == NULL) {
2032 return ::SYSTEM_ERROR;
2033 }
Kenny Root70e3a862012-02-15 17:20:23 -08002034
Kenny Root07438c82012-11-02 15:41:02 -07002035 keymaster_rsa_sign_params_t params;
2036 params.digest_type = DIGEST_NONE;
2037 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002038
Kenny Root17208e02013-09-04 13:56:03 -07002039 if (keyBlob.isFallback()) {
2040 rc = openssl_verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2041 dataLength, signature, signatureLength);
2042 } else {
2043 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2044 dataLength, signature, signatureLength);
2045 }
Kenny Root07438c82012-11-02 15:41:02 -07002046 if (rc) {
2047 return ::SYSTEM_ERROR;
2048 } else {
2049 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002050 }
2051 }
Kenny Root07438c82012-11-02 15:41:02 -07002052
2053 /*
2054 * TODO: The abstraction between things stored in hardware and regular blobs
2055 * of data stored on the filesystem should be moved down to keystore itself.
2056 * Unfortunately the Java code that calls this has naming conventions that it
2057 * knows about. Ideally keystore shouldn't be used to store random blobs of
2058 * data.
2059 *
2060 * Until that happens, it's necessary to have a separate "get_pubkey" and
2061 * "del_key" since the Java code doesn't really communicate what it's
2062 * intentions are.
2063 */
2064 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002065 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002066 pid_t spid = IPCThreadState::self()->getCallingPid();
2067 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002068 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002069 return ::PERMISSION_DENIED;
2070 }
Kenny Root07438c82012-11-02 15:41:02 -07002071
Kenny Root07438c82012-11-02 15:41:02 -07002072 Blob keyBlob;
2073 String8 name8(name);
2074
Kenny Rootd38a0b02013-02-13 12:59:14 -08002075 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002076
Kenny Root655b9582013-04-04 08:37:42 -07002077 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002078 TYPE_KEY_PAIR);
2079 if (responseCode != ::NO_ERROR) {
2080 return responseCode;
2081 }
2082
2083 const keymaster_device_t* device = mKeyStore->getDevice();
2084 if (device == NULL) {
2085 return ::SYSTEM_ERROR;
2086 }
2087
2088 if (device->get_keypair_public == NULL) {
2089 ALOGE("device has no get_keypair_public implementation!");
2090 return ::SYSTEM_ERROR;
2091 }
2092
Kenny Root17208e02013-09-04 13:56:03 -07002093 int rc;
2094 if (keyBlob.isFallback()) {
2095 rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2096 pubkeyLength);
2097 } else {
2098 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2099 pubkeyLength);
2100 }
Kenny Root07438c82012-11-02 15:41:02 -07002101 if (rc) {
2102 return ::SYSTEM_ERROR;
2103 }
2104
2105 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002106 }
Kenny Root07438c82012-11-02 15:41:02 -07002107
Kenny Root49468902013-03-19 13:41:33 -07002108 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002109 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002110 pid_t spid = IPCThreadState::self()->getCallingPid();
2111 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002112 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002113 return ::PERMISSION_DENIED;
2114 }
Kenny Root07438c82012-11-02 15:41:02 -07002115
Kenny Root49468902013-03-19 13:41:33 -07002116 if (targetUid == -1) {
2117 targetUid = callingUid;
2118 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002119 return ::PERMISSION_DENIED;
2120 }
2121
Kenny Root07438c82012-11-02 15:41:02 -07002122 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002123 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002124
2125 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002126 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002127 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002128 if (responseCode != ::NO_ERROR) {
2129 return responseCode;
2130 }
2131
2132 ResponseCode rc = ::NO_ERROR;
2133
2134 const keymaster_device_t* device = mKeyStore->getDevice();
2135 if (device == NULL) {
2136 rc = ::SYSTEM_ERROR;
2137 } else {
2138 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002139 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Root07438c82012-11-02 15:41:02 -07002140 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2141 rc = ::SYSTEM_ERROR;
2142 }
2143 }
2144 }
2145
2146 if (rc != ::NO_ERROR) {
2147 return rc;
2148 }
2149
2150 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
2151 }
2152
2153 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002154 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002155 pid_t spid = IPCThreadState::self()->getCallingPid();
2156 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002157 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002158 return ::PERMISSION_DENIED;
2159 }
Kenny Root07438c82012-11-02 15:41:02 -07002160
Kenny Root655b9582013-04-04 08:37:42 -07002161 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002162 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002163 ALOGD("calling grant in state: %d", state);
2164 return state;
2165 }
2166
2167 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002168 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002169
Kenny Root655b9582013-04-04 08:37:42 -07002170 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002171 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2172 }
2173
Kenny Root655b9582013-04-04 08:37:42 -07002174 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002175 return ::NO_ERROR;
2176 }
2177
2178 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002179 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002180 pid_t spid = IPCThreadState::self()->getCallingPid();
2181 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002182 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002183 return ::PERMISSION_DENIED;
2184 }
Kenny Root07438c82012-11-02 15:41:02 -07002185
Kenny Root655b9582013-04-04 08:37:42 -07002186 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002187 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002188 ALOGD("calling ungrant in state: %d", state);
2189 return state;
2190 }
2191
2192 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002193 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002194
Kenny Root655b9582013-04-04 08:37:42 -07002195 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002196 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2197 }
2198
Kenny Root655b9582013-04-04 08:37:42 -07002199 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002200 }
2201
2202 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002203 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002204 pid_t spid = IPCThreadState::self()->getCallingPid();
2205 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002206 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002207 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002208 }
Kenny Root07438c82012-11-02 15:41:02 -07002209
2210 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002211 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002212
Kenny Root655b9582013-04-04 08:37:42 -07002213 if (access(filename.string(), R_OK) == -1) {
2214 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002215 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002216 }
2217
Kenny Root655b9582013-04-04 08:37:42 -07002218 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002219 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002220 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002221 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002222 }
2223
2224 struct stat s;
2225 int ret = fstat(fd, &s);
2226 close(fd);
2227 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002228 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002229 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002230 }
2231
Kenny Root36a9e232013-02-04 14:24:15 -08002232 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002233 }
2234
Kenny Rootd53bc922013-03-21 14:10:15 -07002235 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2236 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002237 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002238 pid_t spid = IPCThreadState::self()->getCallingPid();
2239 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002240 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002241 return -1L;
2242 }
2243
Kenny Root655b9582013-04-04 08:37:42 -07002244 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002245 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002246 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002247 return state;
2248 }
2249
Kenny Rootd53bc922013-03-21 14:10:15 -07002250 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2251 srcUid = callingUid;
2252 } else if (!is_granted_to(callingUid, srcUid)) {
2253 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002254 return ::PERMISSION_DENIED;
2255 }
2256
Kenny Rootd53bc922013-03-21 14:10:15 -07002257 if (destUid == -1) {
2258 destUid = callingUid;
2259 }
2260
2261 if (srcUid != destUid) {
2262 if (static_cast<uid_t>(srcUid) != callingUid) {
2263 ALOGD("can only duplicate from caller to other or to same uid: "
2264 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2265 return ::PERMISSION_DENIED;
2266 }
2267
2268 if (!is_granted_to(callingUid, destUid)) {
2269 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2270 return ::PERMISSION_DENIED;
2271 }
2272 }
2273
2274 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002275 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002276
Kenny Rootd53bc922013-03-21 14:10:15 -07002277 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002278 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002279
Kenny Root655b9582013-04-04 08:37:42 -07002280 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2281 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002282 return ::SYSTEM_ERROR;
2283 }
2284
Kenny Rootd53bc922013-03-21 14:10:15 -07002285 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002286 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002287 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002288 if (responseCode != ::NO_ERROR) {
2289 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002290 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002291
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002292 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002293 }
2294
Kenny Root1b0e3932013-09-05 13:06:32 -07002295 int32_t is_hardware_backed(const String16& keyType) {
2296 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002297 }
2298
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002299 int32_t clear_uid(int64_t targetUid64) {
2300 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002301 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002302 pid_t spid = IPCThreadState::self()->getCallingPid();
2303 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002304 ALOGW("permission denied for %d: clear_uid", callingUid);
2305 return ::PERMISSION_DENIED;
2306 }
2307
Kenny Root655b9582013-04-04 08:37:42 -07002308 State state = mKeyStore->getState(callingUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002309 if (!isKeystoreUnlocked(state)) {
2310 ALOGD("calling clear_uid in state: %d", state);
2311 return state;
2312 }
2313
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002314 if (targetUid64 == -1) {
2315 targetUid = callingUid;
2316 } else if (!is_granted_to(callingUid, targetUid)) {
2317 return ::PERMISSION_DENIED;
2318 }
2319
Kenny Roota9bb5492013-04-01 16:29:11 -07002320 const keymaster_device_t* device = mKeyStore->getDevice();
2321 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002322 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002323 return ::SYSTEM_ERROR;
2324 }
2325
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002326 UserState* userState = mKeyStore->getUserState(targetUid);
Kenny Root655b9582013-04-04 08:37:42 -07002327 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota9bb5492013-04-01 16:29:11 -07002328 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07002329 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Roota9bb5492013-04-01 16:29:11 -07002330 return ::SYSTEM_ERROR;
2331 }
2332
Kenny Root655b9582013-04-04 08:37:42 -07002333 char prefix[NAME_MAX];
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002334 int n = snprintf(prefix, NAME_MAX, "%u_", targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002335
2336 ResponseCode rc = ::NO_ERROR;
2337
2338 struct dirent* file;
2339 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002340 // We only care about files.
2341 if (file->d_type != DT_REG) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002342 continue;
2343 }
2344
Kenny Root655b9582013-04-04 08:37:42 -07002345 // Skip anything that starts with a "."
2346 if (file->d_name[0] == '.') {
2347 continue;
2348 }
Kenny Roota9bb5492013-04-01 16:29:11 -07002349
Kenny Root655b9582013-04-04 08:37:42 -07002350 if (strncmp(prefix, file->d_name, n)) {
2351 continue;
2352 }
2353
2354 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Roota9bb5492013-04-01 16:29:11 -07002355 Blob keyBlob;
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002356 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, targetUid)
Kenny Root655b9582013-04-04 08:37:42 -07002357 != ::NO_ERROR) {
2358 ALOGW("couldn't open %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002359 continue;
2360 }
2361
2362 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2363 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002364 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002365 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2366 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002367 ALOGW("device couldn't remove %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002368 }
2369 }
2370 }
2371
Kenny Root5f531242013-04-12 11:31:50 -07002372 if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002373 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002374 ALOGW("couldn't unlink %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002375 }
2376 }
2377 closedir(dir);
2378
2379 return rc;
2380 }
2381
Kenny Root07438c82012-11-02 15:41:02 -07002382private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002383 inline bool isKeystoreUnlocked(State state) {
2384 switch (state) {
2385 case ::STATE_NO_ERROR:
2386 return true;
2387 case ::STATE_UNINITIALIZED:
2388 case ::STATE_LOCKED:
2389 return false;
2390 }
2391 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002392 }
2393
Kenny Root1d448c02013-11-21 10:36:53 -08002394 bool isKeyTypeSupported(const keymaster_device_t* device, keymaster_keypair_t keyType) {
2395 const int32_t device_api = device->common.module->module_api_version;
2396 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2397 switch (keyType) {
2398 case TYPE_RSA:
2399 case TYPE_DSA:
2400 case TYPE_EC:
2401 return true;
2402 default:
2403 return false;
2404 }
2405 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2406 switch (keyType) {
2407 case TYPE_RSA:
2408 return true;
2409 case TYPE_DSA:
2410 return device->flags & KEYMASTER_SUPPORTS_DSA;
2411 case TYPE_EC:
2412 return device->flags & KEYMASTER_SUPPORTS_EC;
2413 default:
2414 return false;
2415 }
2416 } else {
2417 return keyType == TYPE_RSA;
2418 }
2419 }
2420
Kenny Root07438c82012-11-02 15:41:02 -07002421 ::KeyStore* mKeyStore;
2422};
2423
2424}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002425
2426int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002427 if (argc < 2) {
2428 ALOGE("A directory must be specified!");
2429 return 1;
2430 }
2431 if (chdir(argv[1]) == -1) {
2432 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2433 return 1;
2434 }
2435
2436 Entropy entropy;
2437 if (!entropy.open()) {
2438 return 1;
2439 }
Kenny Root70e3a862012-02-15 17:20:23 -08002440
2441 keymaster_device_t* dev;
2442 if (keymaster_device_initialize(&dev)) {
2443 ALOGE("keystore keymaster could not be initialized; exiting");
2444 return 1;
2445 }
2446
Riley Spahneaabae92014-06-30 12:39:52 -07002447 ks_is_selinux_enabled = is_selinux_enabled();
2448 if (ks_is_selinux_enabled) {
2449 union selinux_callback cb;
2450 cb.func_log = selinux_log_callback;
2451 selinux_set_callback(SELINUX_CB_LOG, cb);
2452 if (getcon(&tctx) != 0) {
2453 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2454 return -1;
2455 }
2456 } else {
2457 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2458 }
2459
Kenny Root70e3a862012-02-15 17:20:23 -08002460 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002461 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002462 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2463 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2464 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2465 if (ret != android::OK) {
2466 ALOGE("Couldn't register binder service!");
2467 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002468 }
Kenny Root07438c82012-11-02 15:41:02 -07002469
2470 /*
2471 * We're the only thread in existence, so we're just going to process
2472 * Binder transaction as a single-threaded program.
2473 */
2474 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002475
2476 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002477 return 1;
2478}