blob: d8e468649758198755f5698d61943504eca5f22d [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 "."
845 if (file->d_name[0] == '.') {
846 continue;
847 }
848
849 // Find the current file's UID.
850 char* end;
851 unsigned long thisUid = strtoul(file->d_name, &end, 10);
852 if (end[0] != '_' || end[1] == 0) {
853 continue;
854 }
855
856 // Skip if this is not our user.
857 if (get_user_id(thisUid) != mUserId) {
858 continue;
859 }
860
861 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800862 }
863 closedir(dir);
864 return true;
865 }
866
Kenny Root655b9582013-04-04 08:37:42 -0700867private:
868 static const int MASTER_KEY_SIZE_BYTES = 16;
869 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
870
871 static const int MAX_RETRY = 4;
872 static const size_t SALT_SIZE = 16;
873
874 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
875 uint8_t* salt) {
876 size_t saltSize;
877 if (salt != NULL) {
878 saltSize = SALT_SIZE;
879 } else {
880 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
881 salt = (uint8_t*) "keystore";
882 // sizeof = 9, not strlen = 8
883 saltSize = sizeof("keystore");
884 }
885
886 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
887 saltSize, 8192, keySize, key);
888 }
889
890 bool generateSalt(Entropy* entropy) {
891 return entropy->generate_random_data(mSalt, sizeof(mSalt));
892 }
893
894 bool generateMasterKey(Entropy* entropy) {
895 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
896 return false;
897 }
898 if (!generateSalt(entropy)) {
899 return false;
900 }
901 return true;
902 }
903
904 void setupMasterKeys() {
905 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
906 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
907 setState(STATE_NO_ERROR);
908 }
909
910 uid_t mUserId;
911
912 char* mUserDir;
913 char* mMasterKeyFile;
914
915 State mState;
916 int8_t mRetry;
917
918 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
919 uint8_t mSalt[SALT_SIZE];
920
921 AES_KEY mMasterKeyEncryption;
922 AES_KEY mMasterKeyDecryption;
923};
924
925typedef struct {
926 uint32_t uid;
927 const uint8_t* filename;
928} grant_t;
929
930class KeyStore {
931public:
932 KeyStore(Entropy* entropy, keymaster_device_t* device)
933 : mEntropy(entropy)
934 , mDevice(device)
935 {
936 memset(&mMetaData, '\0', sizeof(mMetaData));
937 }
938
939 ~KeyStore() {
940 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
941 it != mGrants.end(); it++) {
942 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700943 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800944 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700945
946 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
947 it != mMasterKeys.end(); it++) {
948 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700949 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800950 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700951 }
952
953 keymaster_device_t* getDevice() const {
954 return mDevice;
955 }
956
957 ResponseCode initialize() {
958 readMetaData();
959 if (upgradeKeystore()) {
960 writeMetaData();
961 }
962
963 return ::NO_ERROR;
964 }
965
966 State getState(uid_t uid) {
967 return getUserState(uid)->getState();
968 }
969
970 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
971 UserState* userState = getUserState(uid);
972 return userState->initialize(pw, mEntropy);
973 }
974
975 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
976 uid_t user_id = get_user_id(uid);
977 UserState* userState = getUserState(user_id);
978 return userState->writeMasterKey(pw, mEntropy);
979 }
980
981 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
982 uid_t user_id = get_user_id(uid);
983 UserState* userState = getUserState(user_id);
984 return userState->readMasterKey(pw, mEntropy);
985 }
986
987 android::String8 getKeyName(const android::String8& keyName) {
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(encoded);
991 }
992
993 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700994 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700995 encode_key(encoded, keyName);
996 return android::String8::format("%u_%s", uid, encoded);
997 }
998
999 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001000 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001001 encode_key(encoded, keyName);
1002 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1003 encoded);
1004 }
1005
1006 bool reset(uid_t uid) {
1007 UserState* userState = getUserState(uid);
1008 userState->zeroizeMasterKeysInMemory();
1009 userState->setState(STATE_UNINITIALIZED);
1010 return userState->reset();
1011 }
1012
1013 bool isEmpty(uid_t uid) const {
1014 const UserState* userState = getUserState(uid);
1015 if (userState == NULL) {
1016 return true;
1017 }
1018
1019 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001020 struct dirent* file;
1021 if (!dir) {
1022 return true;
1023 }
1024 bool result = true;
Kenny Root655b9582013-04-04 08:37:42 -07001025
1026 char filename[NAME_MAX];
1027 int n = snprintf(filename, sizeof(filename), "%u_", uid);
1028
Kenny Roota91203b2012-02-15 15:00:46 -08001029 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001030 // We only care about files.
1031 if (file->d_type != DT_REG) {
1032 continue;
1033 }
1034
1035 // Skip anything that starts with a "."
1036 if (file->d_name[0] == '.') {
1037 continue;
1038 }
1039
1040 if (!strncmp(file->d_name, filename, n)) {
Kenny Roota91203b2012-02-15 15:00:46 -08001041 result = false;
1042 break;
1043 }
1044 }
1045 closedir(dir);
1046 return result;
1047 }
1048
Kenny Root655b9582013-04-04 08:37:42 -07001049 void lock(uid_t uid) {
1050 UserState* userState = getUserState(uid);
1051 userState->zeroizeMasterKeysInMemory();
1052 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001053 }
1054
Kenny Root655b9582013-04-04 08:37:42 -07001055 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1056 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001057 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1058 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001059 if (rc != NO_ERROR) {
1060 return rc;
1061 }
1062
1063 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001064 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001065 /* If we upgrade the key, we need to write it to disk again. Then
1066 * it must be read it again since the blob is encrypted each time
1067 * it's written.
1068 */
Kenny Root655b9582013-04-04 08:37:42 -07001069 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1070 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001071 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1072 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001073 return rc;
1074 }
1075 }
Kenny Root822c3a92012-03-23 16:34:39 -07001076 }
1077
Kenny Root17208e02013-09-04 13:56:03 -07001078 /*
1079 * This will upgrade software-backed keys to hardware-backed keys when
1080 * the HAL for the device supports the newer key types.
1081 */
1082 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1083 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1084 && keyBlob->isFallback()) {
1085 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1086 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1087
1088 // The HAL allowed the import, reget the key to have the "fresh"
1089 // version.
1090 if (imported == NO_ERROR) {
1091 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1092 }
1093 }
1094
Kenny Rootd53bc922013-03-21 14:10:15 -07001095 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001096 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1097 return KEY_NOT_FOUND;
1098 }
1099
1100 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001101 }
1102
Kenny Root655b9582013-04-04 08:37:42 -07001103 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1104 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001105 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1106 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001107 }
1108
Kenny Root07438c82012-11-02 15:41:02 -07001109 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001110 const grant_t* existing = getGrant(filename, granteeUid);
1111 if (existing == NULL) {
1112 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001113 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001114 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001115 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001116 }
1117 }
1118
Kenny Root07438c82012-11-02 15:41:02 -07001119 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001120 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1121 it != mGrants.end(); it++) {
1122 grant_t* grant = *it;
1123 if (grant->uid == granteeUid
1124 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1125 mGrants.erase(it);
1126 return true;
1127 }
Kenny Root70e3a862012-02-15 17:20:23 -08001128 }
Kenny Root70e3a862012-02-15 17:20:23 -08001129 return false;
1130 }
1131
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001132 bool hasGrant(const char* filename, const uid_t uid) const {
1133 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001134 }
1135
Kenny Rootf9119d62013-04-03 09:22:15 -07001136 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1137 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001138 uint8_t* data;
1139 size_t dataLength;
1140 int rc;
1141
1142 if (mDevice->import_keypair == NULL) {
1143 ALOGE("Keymaster doesn't support import!");
1144 return SYSTEM_ERROR;
1145 }
1146
Kenny Root17208e02013-09-04 13:56:03 -07001147 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001148 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001149 if (rc) {
Kenny Root17208e02013-09-04 13:56:03 -07001150 // If this is an old device HAL, try to fall back to an old version
1151 if (mDevice->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_2) {
1152 rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength);
1153 isFallback = true;
1154 }
1155
1156 if (rc) {
1157 ALOGE("Error while importing keypair: %d", rc);
1158 return SYSTEM_ERROR;
1159 }
Kenny Root822c3a92012-03-23 16:34:39 -07001160 }
1161
1162 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1163 free(data);
1164
Kenny Rootf9119d62013-04-03 09:22:15 -07001165 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001166 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001167
Kenny Root655b9582013-04-04 08:37:42 -07001168 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001169 }
1170
Kenny Root1b0e3932013-09-05 13:06:32 -07001171 bool isHardwareBacked(const android::String16& keyType) const {
1172 if (mDevice == NULL) {
1173 ALOGW("can't get keymaster device");
1174 return false;
1175 }
1176
1177 if (sRSAKeyType == keyType) {
1178 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1179 } else {
1180 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1181 && (mDevice->common.module->module_api_version
1182 >= KEYMASTER_MODULE_API_VERSION_0_2);
1183 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001184 }
1185
Kenny Root655b9582013-04-04 08:37:42 -07001186 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1187 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001188 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001189
1190 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1191 if (responseCode == NO_ERROR) {
1192 return responseCode;
1193 }
1194
1195 // If this is one of the legacy UID->UID mappings, use it.
1196 uid_t euid = get_keystore_euid(uid);
1197 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001198 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001199 responseCode = get(filepath8.string(), keyBlob, type, uid);
1200 if (responseCode == NO_ERROR) {
1201 return responseCode;
1202 }
1203 }
1204
1205 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001206 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001207 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001208 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001209 if (end[0] != '_' || end[1] == 0) {
1210 return KEY_NOT_FOUND;
1211 }
Kenny Root86b16e82013-09-09 11:15:54 -07001212 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1213 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001214 if (!hasGrant(filepath8.string(), uid)) {
1215 return responseCode;
1216 }
1217
1218 // It is a granted key. Try to load it.
1219 return get(filepath8.string(), keyBlob, type, uid);
1220 }
1221
1222 /**
1223 * Returns any existing UserState or creates it if it doesn't exist.
1224 */
1225 UserState* getUserState(uid_t uid) {
1226 uid_t userId = get_user_id(uid);
1227
1228 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1229 it != mMasterKeys.end(); it++) {
1230 UserState* state = *it;
1231 if (state->getUserId() == userId) {
1232 return state;
1233 }
1234 }
1235
1236 UserState* userState = new UserState(userId);
1237 if (!userState->initialize()) {
1238 /* There's not much we can do if initialization fails. Trying to
1239 * unlock the keystore for that user will fail as well, so any
1240 * subsequent request for this user will just return SYSTEM_ERROR.
1241 */
1242 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1243 }
1244 mMasterKeys.add(userState);
1245 return userState;
1246 }
1247
1248 /**
1249 * Returns NULL if the UserState doesn't already exist.
1250 */
1251 const UserState* getUserState(uid_t uid) const {
1252 uid_t userId = get_user_id(uid);
1253
1254 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1255 it != mMasterKeys.end(); it++) {
1256 UserState* state = *it;
1257 if (state->getUserId() == userId) {
1258 return state;
1259 }
1260 }
1261
1262 return NULL;
1263 }
1264
Kenny Roota91203b2012-02-15 15:00:46 -08001265private:
Kenny Root655b9582013-04-04 08:37:42 -07001266 static const char* sOldMasterKey;
1267 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001268 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001269 Entropy* mEntropy;
1270
Kenny Root70e3a862012-02-15 17:20:23 -08001271 keymaster_device_t* mDevice;
1272
Kenny Root655b9582013-04-04 08:37:42 -07001273 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001274
Kenny Root655b9582013-04-04 08:37:42 -07001275 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001276
Kenny Root655b9582013-04-04 08:37:42 -07001277 typedef struct {
1278 uint32_t version;
1279 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001280
Kenny Root655b9582013-04-04 08:37:42 -07001281 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001282
Kenny Root655b9582013-04-04 08:37:42 -07001283 const grant_t* getGrant(const char* filename, uid_t uid) const {
1284 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1285 it != mGrants.end(); it++) {
1286 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001287 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001288 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001289 return grant;
1290 }
1291 }
Kenny Root70e3a862012-02-15 17:20:23 -08001292 return NULL;
1293 }
1294
Kenny Root822c3a92012-03-23 16:34:39 -07001295 /**
1296 * Upgrade code. This will upgrade the key from the current version
1297 * to whatever is newest.
1298 */
Kenny Root655b9582013-04-04 08:37:42 -07001299 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1300 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001301 bool updated = false;
1302 uint8_t version = oldVersion;
1303
1304 /* From V0 -> V1: All old types were unknown */
1305 if (version == 0) {
1306 ALOGV("upgrading to version 1 and setting type %d", type);
1307
1308 blob->setType(type);
1309 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001310 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001311 }
1312 version = 1;
1313 updated = true;
1314 }
1315
Kenny Rootf9119d62013-04-03 09:22:15 -07001316 /* From V1 -> V2: All old keys were encrypted */
1317 if (version == 1) {
1318 ALOGV("upgrading to version 2");
1319
1320 blob->setEncrypted(true);
1321 version = 2;
1322 updated = true;
1323 }
1324
Kenny Root822c3a92012-03-23 16:34:39 -07001325 /*
1326 * If we've updated, set the key blob to the right version
1327 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001328 */
Kenny Root822c3a92012-03-23 16:34:39 -07001329 if (updated) {
1330 ALOGV("updated and writing file %s", filename);
1331 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001332 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001333
1334 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001335 }
1336
1337 /**
1338 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1339 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1340 * Then it overwrites the original blob with the new blob
1341 * format that is returned from the keymaster.
1342 */
Kenny Root655b9582013-04-04 08:37:42 -07001343 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001344 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1345 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1346 if (b.get() == NULL) {
1347 ALOGE("Problem instantiating BIO");
1348 return SYSTEM_ERROR;
1349 }
1350
1351 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1352 if (pkey.get() == NULL) {
1353 ALOGE("Couldn't read old PEM file");
1354 return SYSTEM_ERROR;
1355 }
1356
1357 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1358 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1359 if (len < 0) {
1360 ALOGE("Couldn't measure PKCS#8 length");
1361 return SYSTEM_ERROR;
1362 }
1363
Kenny Root70c98892013-02-07 09:10:36 -08001364 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1365 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001366 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1367 ALOGE("Couldn't convert to PKCS#8");
1368 return SYSTEM_ERROR;
1369 }
1370
Kenny Rootf9119d62013-04-03 09:22:15 -07001371 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1372 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001373 if (rc != NO_ERROR) {
1374 return rc;
1375 }
1376
Kenny Root655b9582013-04-04 08:37:42 -07001377 return get(filename, blob, TYPE_KEY_PAIR, uid);
1378 }
1379
1380 void readMetaData() {
1381 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1382 if (in < 0) {
1383 return;
1384 }
1385 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1386 if (fileLength != sizeof(mMetaData)) {
1387 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1388 sizeof(mMetaData));
1389 }
1390 close(in);
1391 }
1392
1393 void writeMetaData() {
1394 const char* tmpFileName = ".metadata.tmp";
1395 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1396 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1397 if (out < 0) {
1398 ALOGE("couldn't write metadata file: %s", strerror(errno));
1399 return;
1400 }
1401 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1402 if (fileLength != sizeof(mMetaData)) {
1403 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1404 sizeof(mMetaData));
1405 }
1406 close(out);
1407 rename(tmpFileName, sMetaDataFile);
1408 }
1409
1410 bool upgradeKeystore() {
1411 bool upgraded = false;
1412
1413 if (mMetaData.version == 0) {
1414 UserState* userState = getUserState(0);
1415
1416 // Initialize first so the directory is made.
1417 userState->initialize();
1418
1419 // Migrate the old .masterkey file to user 0.
1420 if (access(sOldMasterKey, R_OK) == 0) {
1421 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1422 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1423 return false;
1424 }
1425 }
1426
1427 // Initialize again in case we had a key.
1428 userState->initialize();
1429
1430 // Try to migrate existing keys.
1431 DIR* dir = opendir(".");
1432 if (!dir) {
1433 // Give up now; maybe we can upgrade later.
1434 ALOGE("couldn't open keystore's directory; something is wrong");
1435 return false;
1436 }
1437
1438 struct dirent* file;
1439 while ((file = readdir(dir)) != NULL) {
1440 // We only care about files.
1441 if (file->d_type != DT_REG) {
1442 continue;
1443 }
1444
1445 // Skip anything that starts with a "."
1446 if (file->d_name[0] == '.') {
1447 continue;
1448 }
1449
1450 // Find the current file's user.
1451 char* end;
1452 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1453 if (end[0] != '_' || end[1] == 0) {
1454 continue;
1455 }
1456 UserState* otherUser = getUserState(thisUid);
1457 if (otherUser->getUserId() != 0) {
1458 unlinkat(dirfd(dir), file->d_name, 0);
1459 }
1460
1461 // Rename the file into user directory.
1462 DIR* otherdir = opendir(otherUser->getUserDirName());
1463 if (otherdir == NULL) {
1464 ALOGW("couldn't open user directory for rename");
1465 continue;
1466 }
1467 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1468 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1469 }
1470 closedir(otherdir);
1471 }
1472 closedir(dir);
1473
1474 mMetaData.version = 1;
1475 upgraded = true;
1476 }
1477
1478 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001479 }
Kenny Roota91203b2012-02-15 15:00:46 -08001480};
1481
Kenny Root655b9582013-04-04 08:37:42 -07001482const char* KeyStore::sOldMasterKey = ".masterkey";
1483const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001484
Kenny Root1b0e3932013-09-05 13:06:32 -07001485const android::String16 KeyStore::sRSAKeyType("RSA");
1486
Kenny Root07438c82012-11-02 15:41:02 -07001487namespace android {
1488class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1489public:
1490 KeyStoreProxy(KeyStore* keyStore)
1491 : mKeyStore(keyStore)
1492 {
Kenny Roota91203b2012-02-15 15:00:46 -08001493 }
Kenny Roota91203b2012-02-15 15:00:46 -08001494
Kenny Root07438c82012-11-02 15:41:02 -07001495 void binderDied(const wp<IBinder>&) {
1496 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001497 }
Kenny Roota91203b2012-02-15 15:00:46 -08001498
Kenny Root07438c82012-11-02 15:41:02 -07001499 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001500 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001501 pid_t spid = IPCThreadState::self()->getCallingPid();
1502 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001503 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001504 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001505 }
Kenny Roota91203b2012-02-15 15:00:46 -08001506
Kenny Root655b9582013-04-04 08:37:42 -07001507 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001508 }
1509
Kenny Root07438c82012-11-02 15:41:02 -07001510 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001511 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001512 pid_t spid = IPCThreadState::self()->getCallingPid();
1513 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001514 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001515 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001516 }
Kenny Root07438c82012-11-02 15:41:02 -07001517
Kenny Root07438c82012-11-02 15:41:02 -07001518 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001519 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001520
Kenny Root655b9582013-04-04 08:37:42 -07001521 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001522 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001523 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001524 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001525 *item = NULL;
1526 *itemLength = 0;
1527 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001528 }
Kenny Roota91203b2012-02-15 15:00:46 -08001529
Kenny Root07438c82012-11-02 15:41:02 -07001530 *item = (uint8_t*) malloc(keyBlob.getLength());
1531 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1532 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001533
Kenny Root07438c82012-11-02 15:41:02 -07001534 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001535 }
1536
Kenny Rootf9119d62013-04-03 09:22:15 -07001537 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1538 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001539 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001540 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001541 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001542 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001543 return ::PERMISSION_DENIED;
1544 }
Kenny Root07438c82012-11-02 15:41:02 -07001545
Kenny Rootf9119d62013-04-03 09:22:15 -07001546 State state = mKeyStore->getState(callingUid);
1547 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1548 ALOGD("calling get in state: %d", state);
1549 return state;
1550 }
1551
Kenny Root49468902013-03-19 13:41:33 -07001552 if (targetUid == -1) {
1553 targetUid = callingUid;
1554 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001555 return ::PERMISSION_DENIED;
1556 }
1557
Kenny Root07438c82012-11-02 15:41:02 -07001558 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001559 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001560
1561 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001562 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1563
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001564 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001565 }
1566
Kenny Root49468902013-03-19 13:41:33 -07001567 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001568 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001569 pid_t spid = IPCThreadState::self()->getCallingPid();
1570 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001571 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001572 return ::PERMISSION_DENIED;
1573 }
Kenny Root70e3a862012-02-15 17:20:23 -08001574
Kenny Root49468902013-03-19 13:41:33 -07001575 if (targetUid == -1) {
1576 targetUid = callingUid;
1577 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001578 return ::PERMISSION_DENIED;
1579 }
1580
Kenny Root07438c82012-11-02 15:41:02 -07001581 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001582 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001583
1584 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001585 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001586 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07001587 if (responseCode != ::NO_ERROR) {
1588 return responseCode;
1589 }
1590 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001591 }
1592
Kenny Root49468902013-03-19 13:41:33 -07001593 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001594 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001595 pid_t spid = IPCThreadState::self()->getCallingPid();
1596 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001597 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001598 return ::PERMISSION_DENIED;
1599 }
Kenny Root70e3a862012-02-15 17:20:23 -08001600
Kenny Root49468902013-03-19 13:41:33 -07001601 if (targetUid == -1) {
1602 targetUid = callingUid;
1603 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001604 return ::PERMISSION_DENIED;
1605 }
1606
Kenny Root07438c82012-11-02 15:41:02 -07001607 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001608 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001609
Kenny Root655b9582013-04-04 08:37:42 -07001610 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001611 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1612 }
1613 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001614 }
1615
Kenny Root49468902013-03-19 13:41:33 -07001616 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001617 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001618 pid_t spid = IPCThreadState::self()->getCallingPid();
1619 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001620 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001621 return ::PERMISSION_DENIED;
1622 }
Kenny Root70e3a862012-02-15 17:20:23 -08001623
Kenny Root49468902013-03-19 13:41:33 -07001624 if (targetUid == -1) {
1625 targetUid = callingUid;
1626 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001627 return ::PERMISSION_DENIED;
1628 }
1629
Kenny Root655b9582013-04-04 08:37:42 -07001630 UserState* userState = mKeyStore->getUserState(targetUid);
1631 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001632 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07001633 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001634 return ::SYSTEM_ERROR;
1635 }
Kenny Root70e3a862012-02-15 17:20:23 -08001636
Kenny Root07438c82012-11-02 15:41:02 -07001637 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001638 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1639 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001640
Kenny Root07438c82012-11-02 15:41:02 -07001641 struct dirent* file;
1642 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001643 // We only care about files.
1644 if (file->d_type != DT_REG) {
1645 continue;
1646 }
1647
1648 // Skip anything that starts with a "."
1649 if (file->d_name[0] == '.') {
1650 continue;
1651 }
1652
1653 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001654 const char* p = &file->d_name[n];
1655 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001656
Kenny Root07438c82012-11-02 15:41:02 -07001657 size_t extra = decode_key_length(p, plen);
1658 char *match = (char*) malloc(extra + 1);
1659 if (match != NULL) {
1660 decode_key(match, p, plen);
1661 matches->push(String16(match, extra));
1662 free(match);
1663 } else {
1664 ALOGW("could not allocate match of size %zd", extra);
1665 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001666 }
1667 }
Kenny Root07438c82012-11-02 15:41:02 -07001668 closedir(dir);
1669
1670 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001671 }
1672
Kenny Root07438c82012-11-02 15:41:02 -07001673 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001674 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001675 pid_t spid = IPCThreadState::self()->getCallingPid();
1676 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001677 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001678 return ::PERMISSION_DENIED;
1679 }
1680
Kenny Root655b9582013-04-04 08:37:42 -07001681 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001682
1683 const keymaster_device_t* device = mKeyStore->getDevice();
1684 if (device == NULL) {
1685 ALOGE("No keymaster device!");
1686 return ::SYSTEM_ERROR;
1687 }
1688
1689 if (device->delete_all == NULL) {
1690 ALOGV("keymaster device doesn't implement delete_all");
1691 return rc;
1692 }
1693
1694 if (device->delete_all(device)) {
1695 ALOGE("Problem calling keymaster's delete_all");
1696 return ::SYSTEM_ERROR;
1697 }
1698
Kenny Root9a53d3e2012-08-14 10:47:54 -07001699 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001700 }
1701
Kenny Root07438c82012-11-02 15:41:02 -07001702 /*
1703 * Here is the history. To improve the security, the parameters to generate the
1704 * master key has been changed. To make a seamless transition, we update the
1705 * file using the same password when the user unlock it for the first time. If
1706 * any thing goes wrong during the transition, the new file will not overwrite
1707 * the old one. This avoids permanent damages of the existing data.
1708 */
1709 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001710 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001711 pid_t spid = IPCThreadState::self()->getCallingPid();
1712 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001713 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001714 return ::PERMISSION_DENIED;
1715 }
Kenny Root70e3a862012-02-15 17:20:23 -08001716
Kenny Root07438c82012-11-02 15:41:02 -07001717 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001718
Kenny Root655b9582013-04-04 08:37:42 -07001719 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001720 case ::STATE_UNINITIALIZED: {
1721 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001722 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001723 }
1724 case ::STATE_NO_ERROR: {
1725 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001726 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001727 }
1728 case ::STATE_LOCKED: {
1729 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001730 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001731 }
1732 }
1733 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001734 }
1735
Kenny Root07438c82012-11-02 15:41:02 -07001736 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001737 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001738 pid_t spid = IPCThreadState::self()->getCallingPid();
1739 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001740 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001741 return ::PERMISSION_DENIED;
1742 }
Kenny Root70e3a862012-02-15 17:20:23 -08001743
Kenny Root655b9582013-04-04 08:37:42 -07001744 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001745 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001746 ALOGD("calling lock in state: %d", state);
1747 return state;
1748 }
1749
Kenny Root655b9582013-04-04 08:37:42 -07001750 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001751 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001752 }
1753
Kenny Root07438c82012-11-02 15:41:02 -07001754 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001755 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001756 pid_t spid = IPCThreadState::self()->getCallingPid();
1757 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001758 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001759 return ::PERMISSION_DENIED;
1760 }
1761
Kenny Root655b9582013-04-04 08:37:42 -07001762 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001763 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001764 ALOGD("calling unlock when not locked");
1765 return state;
1766 }
1767
1768 const String8 password8(pw);
1769 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001770 }
1771
Kenny Root07438c82012-11-02 15:41:02 -07001772 int32_t zero() {
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_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001776 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001777 return -1;
1778 }
Kenny Root70e3a862012-02-15 17:20:23 -08001779
Kenny Root655b9582013-04-04 08:37:42 -07001780 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001781 }
1782
Kenny Root96427ba2013-08-16 14:02:41 -07001783 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1784 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001785 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001786 pid_t spid = IPCThreadState::self()->getCallingPid();
1787 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001788 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001789 return ::PERMISSION_DENIED;
1790 }
Kenny Root70e3a862012-02-15 17:20:23 -08001791
Kenny Root49468902013-03-19 13:41:33 -07001792 if (targetUid == -1) {
1793 targetUid = callingUid;
1794 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001795 return ::PERMISSION_DENIED;
1796 }
1797
Kenny Root655b9582013-04-04 08:37:42 -07001798 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001799 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1800 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001801 return state;
1802 }
Kenny Root70e3a862012-02-15 17:20:23 -08001803
Kenny Root07438c82012-11-02 15:41:02 -07001804 uint8_t* data;
1805 size_t dataLength;
1806 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001807 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001808
1809 const keymaster_device_t* device = mKeyStore->getDevice();
1810 if (device == NULL) {
1811 return ::SYSTEM_ERROR;
1812 }
1813
1814 if (device->generate_keypair == NULL) {
1815 return ::SYSTEM_ERROR;
1816 }
1817
Kenny Root17208e02013-09-04 13:56:03 -07001818 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001819 keymaster_dsa_keygen_params_t dsa_params;
1820 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001821
Kenny Root96427ba2013-08-16 14:02:41 -07001822 if (keySize == -1) {
1823 keySize = DSA_DEFAULT_KEY_SIZE;
1824 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1825 || keySize > DSA_MAX_KEY_SIZE) {
1826 ALOGI("invalid key size %d", keySize);
1827 return ::SYSTEM_ERROR;
1828 }
1829 dsa_params.key_size = keySize;
1830
1831 if (args->size() == 3) {
1832 sp<KeystoreArg> gArg = args->itemAt(0);
1833 sp<KeystoreArg> pArg = args->itemAt(1);
1834 sp<KeystoreArg> qArg = args->itemAt(2);
1835
1836 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1837 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1838 dsa_params.generator_len = gArg->size();
1839
1840 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1841 dsa_params.prime_p_len = pArg->size();
1842
1843 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1844 dsa_params.prime_q_len = qArg->size();
1845 } else {
1846 ALOGI("not all DSA parameters were read");
1847 return ::SYSTEM_ERROR;
1848 }
1849 } else if (args->size() != 0) {
1850 ALOGI("DSA args must be 3");
1851 return ::SYSTEM_ERROR;
1852 }
1853
Kenny Root1d448c02013-11-21 10:36:53 -08001854 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001855 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1856 } else {
1857 isFallback = true;
1858 rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1859 }
1860 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001861 keymaster_ec_keygen_params_t ec_params;
1862 memset(&ec_params, '\0', sizeof(ec_params));
1863
1864 if (keySize == -1) {
1865 keySize = EC_DEFAULT_KEY_SIZE;
1866 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1867 ALOGI("invalid key size %d", keySize);
1868 return ::SYSTEM_ERROR;
1869 }
1870 ec_params.field_size = keySize;
1871
Kenny Root1d448c02013-11-21 10:36:53 -08001872 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001873 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1874 } else {
1875 isFallback = true;
1876 rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1877 }
Kenny Root96427ba2013-08-16 14:02:41 -07001878 } else if (keyType == EVP_PKEY_RSA) {
1879 keymaster_rsa_keygen_params_t rsa_params;
1880 memset(&rsa_params, '\0', sizeof(rsa_params));
1881 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1882
1883 if (keySize == -1) {
1884 keySize = RSA_DEFAULT_KEY_SIZE;
1885 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1886 ALOGI("invalid key size %d", keySize);
1887 return ::SYSTEM_ERROR;
1888 }
1889 rsa_params.modulus_size = keySize;
1890
1891 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001892 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001893 return ::SYSTEM_ERROR;
1894 } else if (args->size() == 1) {
1895 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1896 if (pubExpBlob != NULL) {
1897 Unique_BIGNUM pubExpBn(
1898 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1899 pubExpBlob->size(), NULL));
1900 if (pubExpBn.get() == NULL) {
1901 ALOGI("Could not convert public exponent to BN");
1902 return ::SYSTEM_ERROR;
1903 }
1904 unsigned long pubExp = BN_get_word(pubExpBn.get());
1905 if (pubExp == 0xFFFFFFFFL) {
1906 ALOGI("cannot represent public exponent as a long value");
1907 return ::SYSTEM_ERROR;
1908 }
1909 rsa_params.public_exponent = pubExp;
1910 }
1911 }
1912
1913 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1914 } else {
1915 ALOGW("Unsupported key type %d", keyType);
1916 rc = -1;
1917 }
1918
Kenny Root07438c82012-11-02 15:41:02 -07001919 if (rc) {
1920 return ::SYSTEM_ERROR;
1921 }
1922
Kenny Root655b9582013-04-04 08:37:42 -07001923 String8 name8(name);
1924 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001925
1926 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1927 free(data);
1928
Kenny Rootee8068b2013-10-07 09:49:15 -07001929 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001930 keyBlob.setFallback(isFallback);
1931
Kenny Root655b9582013-04-04 08:37:42 -07001932 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001933 }
1934
Kenny Rootf9119d62013-04-03 09:22:15 -07001935 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1936 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001937 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001938 pid_t spid = IPCThreadState::self()->getCallingPid();
1939 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001940 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001941 return ::PERMISSION_DENIED;
1942 }
Kenny Root07438c82012-11-02 15:41:02 -07001943
Kenny Root49468902013-03-19 13:41:33 -07001944 if (targetUid == -1) {
1945 targetUid = callingUid;
1946 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001947 return ::PERMISSION_DENIED;
1948 }
1949
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001950 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001951 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001952 ALOGD("calling import in state: %d", state);
1953 return state;
1954 }
1955
1956 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001957 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001958
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001959 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001960 }
1961
Kenny Root07438c82012-11-02 15:41:02 -07001962 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1963 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001964 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001965 pid_t spid = IPCThreadState::self()->getCallingPid();
1966 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001967 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001968 return ::PERMISSION_DENIED;
1969 }
Kenny Root07438c82012-11-02 15:41:02 -07001970
Kenny Root07438c82012-11-02 15:41:02 -07001971 Blob keyBlob;
1972 String8 name8(name);
1973
Kenny Rootd38a0b02013-02-13 12:59:14 -08001974 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001975 int rc;
1976
Kenny Root655b9582013-04-04 08:37:42 -07001977 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001978 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001979 if (responseCode != ::NO_ERROR) {
1980 return responseCode;
1981 }
1982
1983 const keymaster_device_t* device = mKeyStore->getDevice();
1984 if (device == NULL) {
1985 ALOGE("no keymaster device; cannot sign");
1986 return ::SYSTEM_ERROR;
1987 }
1988
1989 if (device->sign_data == NULL) {
1990 ALOGE("device doesn't implement signing");
1991 return ::SYSTEM_ERROR;
1992 }
1993
1994 keymaster_rsa_sign_params_t params;
1995 params.digest_type = DIGEST_NONE;
1996 params.padding_type = PADDING_NONE;
1997
Kenny Root17208e02013-09-04 13:56:03 -07001998 if (keyBlob.isFallback()) {
1999 rc = openssl_sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2000 length, out, outLength);
2001 } else {
2002 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2003 length, out, outLength);
2004 }
Kenny Root07438c82012-11-02 15:41:02 -07002005 if (rc) {
2006 ALOGW("device couldn't sign data");
2007 return ::SYSTEM_ERROR;
2008 }
2009
2010 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002011 }
2012
Kenny Root07438c82012-11-02 15:41:02 -07002013 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2014 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002015 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002016 pid_t spid = IPCThreadState::self()->getCallingPid();
2017 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002018 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002019 return ::PERMISSION_DENIED;
2020 }
Kenny Root70e3a862012-02-15 17:20:23 -08002021
Kenny Root655b9582013-04-04 08:37:42 -07002022 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002023 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002024 ALOGD("calling verify in state: %d", state);
2025 return state;
2026 }
Kenny Root70e3a862012-02-15 17:20:23 -08002027
Kenny Root07438c82012-11-02 15:41:02 -07002028 Blob keyBlob;
2029 String8 name8(name);
2030 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002031
Kenny Root655b9582013-04-04 08:37:42 -07002032 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002033 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002034 if (responseCode != ::NO_ERROR) {
2035 return responseCode;
2036 }
Kenny Root70e3a862012-02-15 17:20:23 -08002037
Kenny Root07438c82012-11-02 15:41:02 -07002038 const keymaster_device_t* device = mKeyStore->getDevice();
2039 if (device == NULL) {
2040 return ::SYSTEM_ERROR;
2041 }
Kenny Root70e3a862012-02-15 17:20:23 -08002042
Kenny Root07438c82012-11-02 15:41:02 -07002043 if (device->verify_data == NULL) {
2044 return ::SYSTEM_ERROR;
2045 }
Kenny Root70e3a862012-02-15 17:20:23 -08002046
Kenny Root07438c82012-11-02 15:41:02 -07002047 keymaster_rsa_sign_params_t params;
2048 params.digest_type = DIGEST_NONE;
2049 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002050
Kenny Root17208e02013-09-04 13:56:03 -07002051 if (keyBlob.isFallback()) {
2052 rc = openssl_verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2053 dataLength, signature, signatureLength);
2054 } else {
2055 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2056 dataLength, signature, signatureLength);
2057 }
Kenny Root07438c82012-11-02 15:41:02 -07002058 if (rc) {
2059 return ::SYSTEM_ERROR;
2060 } else {
2061 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002062 }
2063 }
Kenny Root07438c82012-11-02 15:41:02 -07002064
2065 /*
2066 * TODO: The abstraction between things stored in hardware and regular blobs
2067 * of data stored on the filesystem should be moved down to keystore itself.
2068 * Unfortunately the Java code that calls this has naming conventions that it
2069 * knows about. Ideally keystore shouldn't be used to store random blobs of
2070 * data.
2071 *
2072 * Until that happens, it's necessary to have a separate "get_pubkey" and
2073 * "del_key" since the Java code doesn't really communicate what it's
2074 * intentions are.
2075 */
2076 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002077 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002078 pid_t spid = IPCThreadState::self()->getCallingPid();
2079 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002080 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002081 return ::PERMISSION_DENIED;
2082 }
Kenny Root07438c82012-11-02 15:41:02 -07002083
Kenny Root07438c82012-11-02 15:41:02 -07002084 Blob keyBlob;
2085 String8 name8(name);
2086
Kenny Rootd38a0b02013-02-13 12:59:14 -08002087 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002088
Kenny Root655b9582013-04-04 08:37:42 -07002089 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002090 TYPE_KEY_PAIR);
2091 if (responseCode != ::NO_ERROR) {
2092 return responseCode;
2093 }
2094
2095 const keymaster_device_t* device = mKeyStore->getDevice();
2096 if (device == NULL) {
2097 return ::SYSTEM_ERROR;
2098 }
2099
2100 if (device->get_keypair_public == NULL) {
2101 ALOGE("device has no get_keypair_public implementation!");
2102 return ::SYSTEM_ERROR;
2103 }
2104
Kenny Root17208e02013-09-04 13:56:03 -07002105 int rc;
2106 if (keyBlob.isFallback()) {
2107 rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2108 pubkeyLength);
2109 } else {
2110 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2111 pubkeyLength);
2112 }
Kenny Root07438c82012-11-02 15:41:02 -07002113 if (rc) {
2114 return ::SYSTEM_ERROR;
2115 }
2116
2117 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002118 }
Kenny Root07438c82012-11-02 15:41:02 -07002119
Kenny Root49468902013-03-19 13:41:33 -07002120 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002121 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002122 pid_t spid = IPCThreadState::self()->getCallingPid();
2123 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002124 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002125 return ::PERMISSION_DENIED;
2126 }
Kenny Root07438c82012-11-02 15:41:02 -07002127
Kenny Root49468902013-03-19 13:41:33 -07002128 if (targetUid == -1) {
2129 targetUid = callingUid;
2130 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002131 return ::PERMISSION_DENIED;
2132 }
2133
Kenny Root07438c82012-11-02 15:41:02 -07002134 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002135 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002136
2137 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002138 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002139 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002140 if (responseCode != ::NO_ERROR) {
2141 return responseCode;
2142 }
2143
2144 ResponseCode rc = ::NO_ERROR;
2145
2146 const keymaster_device_t* device = mKeyStore->getDevice();
2147 if (device == NULL) {
2148 rc = ::SYSTEM_ERROR;
2149 } else {
2150 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002151 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Root07438c82012-11-02 15:41:02 -07002152 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2153 rc = ::SYSTEM_ERROR;
2154 }
2155 }
2156 }
2157
2158 if (rc != ::NO_ERROR) {
2159 return rc;
2160 }
2161
2162 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
2163 }
2164
2165 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002166 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002167 pid_t spid = IPCThreadState::self()->getCallingPid();
2168 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002169 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002170 return ::PERMISSION_DENIED;
2171 }
Kenny Root07438c82012-11-02 15:41:02 -07002172
Kenny Root655b9582013-04-04 08:37:42 -07002173 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002174 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002175 ALOGD("calling grant in state: %d", state);
2176 return state;
2177 }
2178
2179 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002180 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002181
Kenny Root655b9582013-04-04 08:37:42 -07002182 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002183 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2184 }
2185
Kenny Root655b9582013-04-04 08:37:42 -07002186 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002187 return ::NO_ERROR;
2188 }
2189
2190 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002191 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002192 pid_t spid = IPCThreadState::self()->getCallingPid();
2193 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002194 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002195 return ::PERMISSION_DENIED;
2196 }
Kenny Root07438c82012-11-02 15:41:02 -07002197
Kenny Root655b9582013-04-04 08:37:42 -07002198 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002199 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002200 ALOGD("calling ungrant in state: %d", state);
2201 return state;
2202 }
2203
2204 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002205 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002206
Kenny Root655b9582013-04-04 08:37:42 -07002207 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002208 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2209 }
2210
Kenny Root655b9582013-04-04 08:37:42 -07002211 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002212 }
2213
2214 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002215 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002216 pid_t spid = IPCThreadState::self()->getCallingPid();
2217 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002218 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002219 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002220 }
Kenny Root07438c82012-11-02 15:41:02 -07002221
2222 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002223 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002224
Kenny Root655b9582013-04-04 08:37:42 -07002225 if (access(filename.string(), R_OK) == -1) {
2226 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002227 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002228 }
2229
Kenny Root655b9582013-04-04 08:37:42 -07002230 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002231 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002232 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002233 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002234 }
2235
2236 struct stat s;
2237 int ret = fstat(fd, &s);
2238 close(fd);
2239 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002240 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002241 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002242 }
2243
Kenny Root36a9e232013-02-04 14:24:15 -08002244 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002245 }
2246
Kenny Rootd53bc922013-03-21 14:10:15 -07002247 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2248 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002249 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002250 pid_t spid = IPCThreadState::self()->getCallingPid();
2251 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002252 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002253 return -1L;
2254 }
2255
Kenny Root655b9582013-04-04 08:37:42 -07002256 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002257 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002258 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002259 return state;
2260 }
2261
Kenny Rootd53bc922013-03-21 14:10:15 -07002262 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2263 srcUid = callingUid;
2264 } else if (!is_granted_to(callingUid, srcUid)) {
2265 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002266 return ::PERMISSION_DENIED;
2267 }
2268
Kenny Rootd53bc922013-03-21 14:10:15 -07002269 if (destUid == -1) {
2270 destUid = callingUid;
2271 }
2272
2273 if (srcUid != destUid) {
2274 if (static_cast<uid_t>(srcUid) != callingUid) {
2275 ALOGD("can only duplicate from caller to other or to same uid: "
2276 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2277 return ::PERMISSION_DENIED;
2278 }
2279
2280 if (!is_granted_to(callingUid, destUid)) {
2281 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2282 return ::PERMISSION_DENIED;
2283 }
2284 }
2285
2286 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002287 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002288
Kenny Rootd53bc922013-03-21 14:10:15 -07002289 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002290 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002291
Kenny Root655b9582013-04-04 08:37:42 -07002292 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2293 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002294 return ::SYSTEM_ERROR;
2295 }
2296
Kenny Rootd53bc922013-03-21 14:10:15 -07002297 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002298 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002299 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002300 if (responseCode != ::NO_ERROR) {
2301 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002302 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002303
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002304 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002305 }
2306
Kenny Root1b0e3932013-09-05 13:06:32 -07002307 int32_t is_hardware_backed(const String16& keyType) {
2308 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002309 }
2310
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002311 int32_t clear_uid(int64_t targetUid64) {
2312 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002313 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002314 pid_t spid = IPCThreadState::self()->getCallingPid();
2315 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002316 ALOGW("permission denied for %d: clear_uid", callingUid);
2317 return ::PERMISSION_DENIED;
2318 }
2319
Kenny Root655b9582013-04-04 08:37:42 -07002320 State state = mKeyStore->getState(callingUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002321 if (!isKeystoreUnlocked(state)) {
2322 ALOGD("calling clear_uid in state: %d", state);
2323 return state;
2324 }
2325
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002326 if (targetUid64 == -1) {
2327 targetUid = callingUid;
2328 } else if (!is_granted_to(callingUid, targetUid)) {
2329 return ::PERMISSION_DENIED;
2330 }
2331
Kenny Roota9bb5492013-04-01 16:29:11 -07002332 const keymaster_device_t* device = mKeyStore->getDevice();
2333 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002334 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002335 return ::SYSTEM_ERROR;
2336 }
2337
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002338 UserState* userState = mKeyStore->getUserState(targetUid);
Kenny Root655b9582013-04-04 08:37:42 -07002339 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota9bb5492013-04-01 16:29:11 -07002340 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07002341 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Roota9bb5492013-04-01 16:29:11 -07002342 return ::SYSTEM_ERROR;
2343 }
2344
Kenny Root655b9582013-04-04 08:37:42 -07002345 char prefix[NAME_MAX];
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002346 int n = snprintf(prefix, NAME_MAX, "%u_", targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002347
2348 ResponseCode rc = ::NO_ERROR;
2349
2350 struct dirent* file;
2351 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002352 // We only care about files.
2353 if (file->d_type != DT_REG) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002354 continue;
2355 }
2356
Kenny Root655b9582013-04-04 08:37:42 -07002357 // Skip anything that starts with a "."
2358 if (file->d_name[0] == '.') {
2359 continue;
2360 }
Kenny Roota9bb5492013-04-01 16:29:11 -07002361
Kenny Root655b9582013-04-04 08:37:42 -07002362 if (strncmp(prefix, file->d_name, n)) {
2363 continue;
2364 }
2365
2366 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Roota9bb5492013-04-01 16:29:11 -07002367 Blob keyBlob;
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002368 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, targetUid)
Kenny Root655b9582013-04-04 08:37:42 -07002369 != ::NO_ERROR) {
2370 ALOGW("couldn't open %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002371 continue;
2372 }
2373
2374 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2375 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002376 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002377 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2378 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002379 ALOGW("device couldn't remove %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002380 }
2381 }
2382 }
2383
Kenny Root5f531242013-04-12 11:31:50 -07002384 if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002385 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002386 ALOGW("couldn't unlink %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002387 }
2388 }
2389 closedir(dir);
2390
2391 return rc;
2392 }
2393
Kenny Root07438c82012-11-02 15:41:02 -07002394private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002395 inline bool isKeystoreUnlocked(State state) {
2396 switch (state) {
2397 case ::STATE_NO_ERROR:
2398 return true;
2399 case ::STATE_UNINITIALIZED:
2400 case ::STATE_LOCKED:
2401 return false;
2402 }
2403 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002404 }
2405
Kenny Root1d448c02013-11-21 10:36:53 -08002406 bool isKeyTypeSupported(const keymaster_device_t* device, keymaster_keypair_t keyType) {
2407 const int32_t device_api = device->common.module->module_api_version;
2408 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2409 switch (keyType) {
2410 case TYPE_RSA:
2411 case TYPE_DSA:
2412 case TYPE_EC:
2413 return true;
2414 default:
2415 return false;
2416 }
2417 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2418 switch (keyType) {
2419 case TYPE_RSA:
2420 return true;
2421 case TYPE_DSA:
2422 return device->flags & KEYMASTER_SUPPORTS_DSA;
2423 case TYPE_EC:
2424 return device->flags & KEYMASTER_SUPPORTS_EC;
2425 default:
2426 return false;
2427 }
2428 } else {
2429 return keyType == TYPE_RSA;
2430 }
2431 }
2432
Kenny Root07438c82012-11-02 15:41:02 -07002433 ::KeyStore* mKeyStore;
2434};
2435
2436}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002437
2438int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002439 if (argc < 2) {
2440 ALOGE("A directory must be specified!");
2441 return 1;
2442 }
2443 if (chdir(argv[1]) == -1) {
2444 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2445 return 1;
2446 }
2447
2448 Entropy entropy;
2449 if (!entropy.open()) {
2450 return 1;
2451 }
Kenny Root70e3a862012-02-15 17:20:23 -08002452
2453 keymaster_device_t* dev;
2454 if (keymaster_device_initialize(&dev)) {
2455 ALOGE("keystore keymaster could not be initialized; exiting");
2456 return 1;
2457 }
2458
Riley Spahneaabae92014-06-30 12:39:52 -07002459 ks_is_selinux_enabled = is_selinux_enabled();
2460 if (ks_is_selinux_enabled) {
2461 union selinux_callback cb;
2462 cb.func_log = selinux_log_callback;
2463 selinux_set_callback(SELINUX_CB_LOG, cb);
2464 if (getcon(&tctx) != 0) {
2465 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2466 return -1;
2467 }
2468 } else {
2469 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2470 }
2471
Kenny Root70e3a862012-02-15 17:20:23 -08002472 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002473 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002474 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2475 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2476 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2477 if (ret != android::OK) {
2478 ALOGE("Couldn't register binder service!");
2479 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002480 }
Kenny Root07438c82012-11-02 15:41:02 -07002481
2482 /*
2483 * We're the only thread in existence, so we're just going to process
2484 * Binder transaction as a single-threaded program.
2485 */
2486 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002487
2488 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002489 return 1;
2490}