blob: 4335f8a0aa31fe2f507ccdf01fd6249ece3a3e61 [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
23#include <unistd.h>
24#include <signal.h>
25#include <errno.h>
26#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070027#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080028#include <fcntl.h>
29#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070030#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080031#include <sys/types.h>
32#include <sys/socket.h>
33#include <sys/stat.h>
34#include <sys/time.h>
35#include <arpa/inet.h>
36
37#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070038#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080039#include <openssl/evp.h>
40#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070041#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080042
Kenny Root70e3a862012-02-15 17:20:23 -080043#include <hardware/keymaster.h>
44
Kenny Root17208e02013-09-04 13:56:03 -070045#include <keymaster/softkeymaster.h>
46
Kenny Root26cfc082013-09-11 14:38:56 -070047#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070048#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070049#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080050
Kenny Root07438c82012-11-02 15:41:02 -070051#include <keystore/IKeystoreService.h>
52#include <binder/IPCThreadState.h>
53#include <binder/IServiceManager.h>
54
Kenny Roota91203b2012-02-15 15:00:46 -080055#include <cutils/log.h>
56#include <cutils/sockets.h>
57#include <private/android_filesystem_config.h>
58
Kenny Root07438c82012-11-02 15:41:02 -070059#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080060
Riley Spahneaabae92014-06-30 12:39:52 -070061#include <selinux/android.h>
62
Kenny Root96427ba2013-08-16 14:02:41 -070063#include "defaults.h"
64
Kenny Roota91203b2012-02-15 15:00:46 -080065/* KeyStore is a secured storage for key-value pairs. In this implementation,
66 * each file stores one key-value pair. Keys are encoded in file names, and
67 * values are encrypted with checksums. The encryption key is protected by a
68 * user-defined password. To keep things simple, buffers are always larger than
69 * the maximum space we needed, so boundary checks on buffers are omitted. */
70
71#define KEY_SIZE ((NAME_MAX - 15) / 2)
72#define VALUE_SIZE 32768
73#define PASSWORD_SIZE VALUE_SIZE
74
Kenny Root822c3a92012-03-23 16:34:39 -070075
Kenny Root96427ba2013-08-16 14:02:41 -070076struct BIGNUM_Delete {
77 void operator()(BIGNUM* p) const {
78 BN_free(p);
79 }
80};
81typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
82
Kenny Root822c3a92012-03-23 16:34:39 -070083struct BIO_Delete {
84 void operator()(BIO* p) const {
85 BIO_free(p);
86 }
87};
88typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
89
90struct EVP_PKEY_Delete {
91 void operator()(EVP_PKEY* p) const {
92 EVP_PKEY_free(p);
93 }
94};
95typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
96
97struct PKCS8_PRIV_KEY_INFO_Delete {
98 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
99 PKCS8_PRIV_KEY_INFO_free(p);
100 }
101};
102typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
103
104
Kenny Root70e3a862012-02-15 17:20:23 -0800105static int keymaster_device_initialize(keymaster_device_t** dev) {
106 int rc;
107
108 const hw_module_t* mod;
109 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
110 if (rc) {
111 ALOGE("could not find any keystore module");
112 goto out;
113 }
114
115 rc = keymaster_open(mod, dev);
116 if (rc) {
117 ALOGE("could not open keymaster device in %s (%s)",
118 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
119 goto out;
120 }
121
122 return 0;
123
124out:
125 *dev = NULL;
126 return rc;
127}
128
129static void keymaster_device_release(keymaster_device_t* dev) {
130 keymaster_close(dev);
131}
132
Kenny Root07438c82012-11-02 15:41:02 -0700133/***************
134 * PERMISSIONS *
135 ***************/
136
137/* Here are the permissions, actions, users, and the main function. */
138typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700139 P_TEST = 1 << 0,
140 P_GET = 1 << 1,
141 P_INSERT = 1 << 2,
142 P_DELETE = 1 << 3,
143 P_EXIST = 1 << 4,
144 P_SAW = 1 << 5,
145 P_RESET = 1 << 6,
146 P_PASSWORD = 1 << 7,
147 P_LOCK = 1 << 8,
148 P_UNLOCK = 1 << 9,
149 P_ZERO = 1 << 10,
150 P_SIGN = 1 << 11,
151 P_VERIFY = 1 << 12,
152 P_GRANT = 1 << 13,
153 P_DUPLICATE = 1 << 14,
Kenny Roota9bb5492013-04-01 16:29:11 -0700154 P_CLEAR_UID = 1 << 15,
Kenny Root07438c82012-11-02 15:41:02 -0700155} perm_t;
156
157static struct user_euid {
158 uid_t uid;
159 uid_t euid;
160} user_euids[] = {
161 {AID_VPN, AID_SYSTEM},
162 {AID_WIFI, AID_SYSTEM},
163 {AID_ROOT, AID_SYSTEM},
164};
165
Riley Spahneaabae92014-06-30 12:39:52 -0700166/* perm_labels associcated with keystore_key SELinux class verbs. */
167const char *perm_labels[] = {
168 "test",
169 "get",
170 "insert",
171 "delete",
172 "exist",
173 "saw",
174 "reset",
175 "password",
176 "lock",
177 "unlock",
178 "zero",
179 "sign",
180 "verify",
181 "grant",
182 "duplicate",
183 "clear_uid"
184};
185
Kenny Root07438c82012-11-02 15:41:02 -0700186static struct user_perm {
187 uid_t uid;
188 perm_t perms;
189} user_perms[] = {
190 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
191 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
192 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
193 {AID_ROOT, static_cast<perm_t>(P_GET) },
194};
195
196static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
197 | P_VERIFY);
198
Riley Spahneaabae92014-06-30 12:39:52 -0700199static char *tctx;
200static int ks_is_selinux_enabled;
201
202static const char *get_perm_label(perm_t perm) {
203 unsigned int index = ffs(perm);
204 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
205 return perm_labels[index - 1];
206 } else {
207 ALOGE("Keystore: Failed to retrieve permission label.\n");
208 abort();
209 }
210}
211
Kenny Root655b9582013-04-04 08:37:42 -0700212/**
213 * Returns the app ID (in the Android multi-user sense) for the current
214 * UNIX UID.
215 */
216static uid_t get_app_id(uid_t uid) {
217 return uid % AID_USER;
218}
219
220/**
221 * Returns the user ID (in the Android multi-user sense) for the current
222 * UNIX UID.
223 */
224static uid_t get_user_id(uid_t uid) {
225 return uid / AID_USER;
226}
227
Riley Spahneaabae92014-06-30 12:39:52 -0700228static bool keystore_selinux_check_access(uid_t uid, perm_t perm, pid_t spid) {
229 if (!ks_is_selinux_enabled) {
230 return true;
231 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000232
Riley Spahneaabae92014-06-30 12:39:52 -0700233 char *sctx = NULL;
234 const char *selinux_class = "keystore_key";
235 const char *str_perm = get_perm_label(perm);
236
237 if (!str_perm) {
238 return false;
239 }
240
241 if (getpidcon(spid, &sctx) != 0) {
242 ALOGE("SELinux: Failed to get source pid context.\n");
243 return false;
244 }
245
246 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
247 NULL) == 0;
248 freecon(sctx);
249 return allowed;
250}
251
252static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700253 // All system users are equivalent for multi-user support.
254 if (get_app_id(uid) == AID_SYSTEM) {
255 uid = AID_SYSTEM;
256 }
257
Kenny Root07438c82012-11-02 15:41:02 -0700258 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
259 struct user_perm user = user_perms[i];
260 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700261 return (user.perms & perm) &&
262 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700263 }
264 }
265
Riley Spahneaabae92014-06-30 12:39:52 -0700266 return (DEFAULT_PERMS & perm) &&
267 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700268}
269
Kenny Root49468902013-03-19 13:41:33 -0700270/**
271 * Returns the UID that the callingUid should act as. This is here for
272 * legacy support of the WiFi and VPN systems and should be removed
273 * when WiFi can operate in its own namespace.
274 */
Kenny Root07438c82012-11-02 15:41:02 -0700275static uid_t get_keystore_euid(uid_t uid) {
276 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
277 struct user_euid user = user_euids[i];
278 if (user.uid == uid) {
279 return user.euid;
280 }
281 }
282
283 return uid;
284}
285
Kenny Root49468902013-03-19 13:41:33 -0700286/**
287 * Returns true if the callingUid is allowed to interact in the targetUid's
288 * namespace.
289 */
290static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
291 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
292 struct user_euid user = user_euids[i];
293 if (user.euid == callingUid && user.uid == targetUid) {
294 return true;
295 }
296 }
297
298 return false;
299}
300
Kenny Root007cb232014-07-30 16:59:42 -0700301/**
302 * Allow the system to perform some privileged tasks that have to do with
303 * system maintenance. This should not be used for any function that uses
304 * the keys in any way (e.g., signing).
305 */
306static bool is_self_or_system(uid_t callingUid, uid_t targetUid) {
307 return callingUid == targetUid || callingUid == AID_SYSTEM;
308}
309
Kenny Roota91203b2012-02-15 15:00:46 -0800310/* Here is the encoding of keys. This is necessary in order to allow arbitrary
311 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
312 * into two bytes. The first byte is one of [+-.] which represents the first
313 * two bits of the character. The second byte encodes the rest of the bits into
314 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
315 * that Base64 cannot be used here due to the need of prefix match on keys. */
316
Kenny Root655b9582013-04-04 08:37:42 -0700317static size_t encode_key_length(const android::String8& keyName) {
318 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
319 size_t length = keyName.length();
320 for (int i = length; i > 0; --i, ++in) {
321 if (*in < '0' || *in > '~') {
322 ++length;
323 }
324 }
325 return length;
326}
327
Kenny Root07438c82012-11-02 15:41:02 -0700328static int encode_key(char* out, const android::String8& keyName) {
329 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
330 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800331 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700332 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800333 *out = '+' + (*in >> 6);
334 *++out = '0' + (*in & 0x3F);
335 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700336 } else {
337 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800338 }
339 }
340 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800341 return length;
342}
343
Kenny Root07438c82012-11-02 15:41:02 -0700344/*
345 * Converts from the "escaped" format on disk to actual name.
346 * This will be smaller than the input string.
347 *
348 * Characters that should combine with the next at the end will be truncated.
349 */
350static size_t decode_key_length(const char* in, size_t length) {
351 size_t outLength = 0;
352
353 for (const char* end = in + length; in < end; in++) {
354 /* This combines with the next character. */
355 if (*in < '0' || *in > '~') {
356 continue;
357 }
358
359 outLength++;
360 }
361 return outLength;
362}
363
364static void decode_key(char* out, const char* in, size_t length) {
365 for (const char* end = in + length; in < end; in++) {
366 if (*in < '0' || *in > '~') {
367 /* Truncate combining characters at the end. */
368 if (in + 1 >= end) {
369 break;
370 }
371
372 *out = (*in++ - '+') << 6;
373 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800374 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700375 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800376 }
377 }
378 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800379}
380
381static size_t readFully(int fd, uint8_t* data, size_t size) {
382 size_t remaining = size;
383 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800384 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800385 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800386 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800387 }
388 data += n;
389 remaining -= n;
390 }
391 return size;
392}
393
394static size_t writeFully(int fd, uint8_t* data, size_t size) {
395 size_t remaining = size;
396 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800397 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
398 if (n < 0) {
399 ALOGW("write failed: %s", strerror(errno));
400 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800401 }
402 data += n;
403 remaining -= n;
404 }
405 return size;
406}
407
408class Entropy {
409public:
410 Entropy() : mRandom(-1) {}
411 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800412 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800413 close(mRandom);
414 }
415 }
416
417 bool open() {
418 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800419 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
420 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800421 ALOGE("open: %s: %s", randomDevice, strerror(errno));
422 return false;
423 }
424 return true;
425 }
426
Kenny Root51878182012-03-13 12:53:19 -0700427 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800428 return (readFully(mRandom, data, size) == size);
429 }
430
431private:
432 int mRandom;
433};
434
435/* Here is the file format. There are two parts in blob.value, the secret and
436 * the description. The secret is stored in ciphertext, and its original size
437 * can be found in blob.length. The description is stored after the secret in
438 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700439 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700440 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800441 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
442 * and decryptBlob(). Thus they should not be accessed from outside. */
443
Kenny Root822c3a92012-03-23 16:34:39 -0700444/* ** Note to future implementors of encryption: **
445 * Currently this is the construction:
446 * metadata || Enc(MD5(data) || data)
447 *
448 * This should be the construction used for encrypting if re-implementing:
449 *
450 * Derive independent keys for encryption and MAC:
451 * Kenc = AES_encrypt(masterKey, "Encrypt")
452 * Kmac = AES_encrypt(masterKey, "MAC")
453 *
454 * Store this:
455 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
456 * HMAC(Kmac, metadata || Enc(data))
457 */
Kenny Roota91203b2012-02-15 15:00:46 -0800458struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700459 uint8_t version;
460 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700461 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800462 uint8_t info;
463 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700464 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800465 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700466 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800467 int32_t length; // in network byte order when encrypted
468 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
469};
470
Kenny Root822c3a92012-03-23 16:34:39 -0700471typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700472 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700473 TYPE_GENERIC = 1,
474 TYPE_MASTER_KEY = 2,
475 TYPE_KEY_PAIR = 3,
476} BlobType;
477
Kenny Rootf9119d62013-04-03 09:22:15 -0700478static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700479
Kenny Roota91203b2012-02-15 15:00:46 -0800480class Blob {
481public:
Kenny Root07438c82012-11-02 15:41:02 -0700482 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
483 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800484 mBlob.length = valueLength;
485 memcpy(mBlob.value, value, valueLength);
486
487 mBlob.info = infoLength;
488 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700489
Kenny Root07438c82012-11-02 15:41:02 -0700490 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700491 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700492
Kenny Rootee8068b2013-10-07 09:49:15 -0700493 if (type == TYPE_MASTER_KEY) {
494 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
495 } else {
496 mBlob.flags = KEYSTORE_FLAG_NONE;
497 }
Kenny Roota91203b2012-02-15 15:00:46 -0800498 }
499
500 Blob(blob b) {
501 mBlob = b;
502 }
503
504 Blob() {}
505
Kenny Root51878182012-03-13 12:53:19 -0700506 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800507 return mBlob.value;
508 }
509
Kenny Root51878182012-03-13 12:53:19 -0700510 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800511 return mBlob.length;
512 }
513
Kenny Root51878182012-03-13 12:53:19 -0700514 const uint8_t* getInfo() const {
515 return mBlob.value + mBlob.length;
516 }
517
518 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800519 return mBlob.info;
520 }
521
Kenny Root822c3a92012-03-23 16:34:39 -0700522 uint8_t getVersion() const {
523 return mBlob.version;
524 }
525
Kenny Rootf9119d62013-04-03 09:22:15 -0700526 bool isEncrypted() const {
527 if (mBlob.version < 2) {
528 return true;
529 }
530
531 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
532 }
533
534 void setEncrypted(bool encrypted) {
535 if (encrypted) {
536 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
537 } else {
538 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
539 }
540 }
541
Kenny Root17208e02013-09-04 13:56:03 -0700542 bool isFallback() const {
543 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
544 }
545
546 void setFallback(bool fallback) {
547 if (fallback) {
548 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
549 } else {
550 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
551 }
552 }
553
Kenny Root822c3a92012-03-23 16:34:39 -0700554 void setVersion(uint8_t version) {
555 mBlob.version = version;
556 }
557
558 BlobType getType() const {
559 return BlobType(mBlob.type);
560 }
561
562 void setType(BlobType type) {
563 mBlob.type = uint8_t(type);
564 }
565
Kenny Rootf9119d62013-04-03 09:22:15 -0700566 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
567 ALOGV("writing blob %s", filename);
568 if (isEncrypted()) {
569 if (state != STATE_NO_ERROR) {
570 ALOGD("couldn't insert encrypted blob while not unlocked");
571 return LOCKED;
572 }
573
574 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
575 ALOGW("Could not read random data for: %s", filename);
576 return SYSTEM_ERROR;
577 }
Kenny Roota91203b2012-02-15 15:00:46 -0800578 }
579
580 // data includes the value and the value's length
581 size_t dataLength = mBlob.length + sizeof(mBlob.length);
582 // pad data to the AES_BLOCK_SIZE
583 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
584 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
585 // encrypted data includes the digest value
586 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
587 // move info after space for padding
588 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
589 // zero padding area
590 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
591
592 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800593
Kenny Rootf9119d62013-04-03 09:22:15 -0700594 if (isEncrypted()) {
595 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800596
Kenny Rootf9119d62013-04-03 09:22:15 -0700597 uint8_t vector[AES_BLOCK_SIZE];
598 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
599 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
600 aes_key, vector, AES_ENCRYPT);
601 }
602
Kenny Roota91203b2012-02-15 15:00:46 -0800603 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
604 size_t fileLength = encryptedLength + headerLength + mBlob.info;
605
606 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800607 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
608 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
609 if (out < 0) {
610 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800611 return SYSTEM_ERROR;
612 }
613 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
614 if (close(out) != 0) {
615 return SYSTEM_ERROR;
616 }
617 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800618 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800619 unlink(tmpFileName);
620 return SYSTEM_ERROR;
621 }
Kenny Root150ca932012-11-14 14:29:02 -0800622 if (rename(tmpFileName, filename) == -1) {
623 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
624 return SYSTEM_ERROR;
625 }
626 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800627 }
628
Kenny Rootf9119d62013-04-03 09:22:15 -0700629 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
630 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800631 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
632 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800633 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
634 }
635 // fileLength may be less than sizeof(mBlob) since the in
636 // memory version has extra padding to tolerate rounding up to
637 // the AES_BLOCK_SIZE
638 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
639 if (close(in) != 0) {
640 return SYSTEM_ERROR;
641 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700642
643 if (isEncrypted() && (state != STATE_NO_ERROR)) {
644 return LOCKED;
645 }
646
Kenny Roota91203b2012-02-15 15:00:46 -0800647 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
648 if (fileLength < headerLength) {
649 return VALUE_CORRUPTED;
650 }
651
652 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700653 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800654 return VALUE_CORRUPTED;
655 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700656
657 ssize_t digestedLength;
658 if (isEncrypted()) {
659 if (encryptedLength % AES_BLOCK_SIZE != 0) {
660 return VALUE_CORRUPTED;
661 }
662
663 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
664 mBlob.vector, AES_DECRYPT);
665 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
666 uint8_t computedDigest[MD5_DIGEST_LENGTH];
667 MD5(mBlob.digested, digestedLength, computedDigest);
668 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
669 return VALUE_CORRUPTED;
670 }
671 } else {
672 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800673 }
674
675 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
676 mBlob.length = ntohl(mBlob.length);
677 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
678 return VALUE_CORRUPTED;
679 }
680 if (mBlob.info != 0) {
681 // move info from after padding to after data
682 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
683 }
Kenny Root07438c82012-11-02 15:41:02 -0700684 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800685 }
686
687private:
688 struct blob mBlob;
689};
690
Kenny Root655b9582013-04-04 08:37:42 -0700691class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800692public:
Kenny Root655b9582013-04-04 08:37:42 -0700693 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
694 asprintf(&mUserDir, "user_%u", mUserId);
695 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
696 }
697
698 ~UserState() {
699 free(mUserDir);
700 free(mMasterKeyFile);
701 }
702
703 bool initialize() {
704 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
705 ALOGE("Could not create directory '%s'", mUserDir);
706 return false;
707 }
708
709 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800710 setState(STATE_LOCKED);
711 } else {
712 setState(STATE_UNINITIALIZED);
713 }
Kenny Root70e3a862012-02-15 17:20:23 -0800714
Kenny Root655b9582013-04-04 08:37:42 -0700715 return true;
716 }
717
718 uid_t getUserId() const {
719 return mUserId;
720 }
721
722 const char* getUserDirName() const {
723 return mUserDir;
724 }
725
726 const char* getMasterKeyFileName() const {
727 return mMasterKeyFile;
728 }
729
730 void setState(State state) {
731 mState = state;
732 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
733 mRetry = MAX_RETRY;
734 }
Kenny Roota91203b2012-02-15 15:00:46 -0800735 }
736
Kenny Root51878182012-03-13 12:53:19 -0700737 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800738 return mState;
739 }
740
Kenny Root51878182012-03-13 12:53:19 -0700741 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800742 return mRetry;
743 }
744
Kenny Root655b9582013-04-04 08:37:42 -0700745 void zeroizeMasterKeysInMemory() {
746 memset(mMasterKey, 0, sizeof(mMasterKey));
747 memset(mSalt, 0, sizeof(mSalt));
748 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
749 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800750 }
751
Kenny Root655b9582013-04-04 08:37:42 -0700752 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
753 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800754 return SYSTEM_ERROR;
755 }
Kenny Root655b9582013-04-04 08:37:42 -0700756 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800757 if (response != NO_ERROR) {
758 return response;
759 }
760 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700761 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800762 }
763
Kenny Root655b9582013-04-04 08:37:42 -0700764 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800765 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
766 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
767 AES_KEY passwordAesKey;
768 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700769 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700770 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800771 }
772
Kenny Root655b9582013-04-04 08:37:42 -0700773 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
774 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800775 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800776 return SYSTEM_ERROR;
777 }
778
779 // we read the raw blob to just to get the salt to generate
780 // the AES key, then we create the Blob to use with decryptBlob
781 blob rawBlob;
782 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
783 if (close(in) != 0) {
784 return SYSTEM_ERROR;
785 }
786 // find salt at EOF if present, otherwise we have an old file
787 uint8_t* salt;
788 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
789 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
790 } else {
791 salt = NULL;
792 }
793 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
794 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
795 AES_KEY passwordAesKey;
796 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
797 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700798 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
799 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800800 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700801 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800802 }
803 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
804 // if salt was missing, generate one and write a new master key file with the salt.
805 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700806 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800807 return SYSTEM_ERROR;
808 }
Kenny Root655b9582013-04-04 08:37:42 -0700809 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800810 }
811 if (response == NO_ERROR) {
812 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
813 setupMasterKeys();
814 }
815 return response;
816 }
817 if (mRetry <= 0) {
818 reset();
819 return UNINITIALIZED;
820 }
821 --mRetry;
822 switch (mRetry) {
823 case 0: return WRONG_PASSWORD_0;
824 case 1: return WRONG_PASSWORD_1;
825 case 2: return WRONG_PASSWORD_2;
826 case 3: return WRONG_PASSWORD_3;
827 default: return WRONG_PASSWORD_3;
828 }
829 }
830
Kenny Root655b9582013-04-04 08:37:42 -0700831 AES_KEY* getEncryptionKey() {
832 return &mMasterKeyEncryption;
833 }
834
835 AES_KEY* getDecryptionKey() {
836 return &mMasterKeyDecryption;
837 }
838
Kenny Roota91203b2012-02-15 15:00:46 -0800839 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700840 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800841 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700842 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800843 return false;
844 }
Kenny Root655b9582013-04-04 08:37:42 -0700845
846 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800847 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700848 // We only care about files.
849 if (file->d_type != DT_REG) {
850 continue;
851 }
852
853 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700854 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700855 continue;
856 }
857
858 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800859 }
860 closedir(dir);
861 return true;
862 }
863
Kenny Root655b9582013-04-04 08:37:42 -0700864private:
865 static const int MASTER_KEY_SIZE_BYTES = 16;
866 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
867
868 static const int MAX_RETRY = 4;
869 static const size_t SALT_SIZE = 16;
870
871 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
872 uint8_t* salt) {
873 size_t saltSize;
874 if (salt != NULL) {
875 saltSize = SALT_SIZE;
876 } else {
877 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
878 salt = (uint8_t*) "keystore";
879 // sizeof = 9, not strlen = 8
880 saltSize = sizeof("keystore");
881 }
882
883 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
884 saltSize, 8192, keySize, key);
885 }
886
887 bool generateSalt(Entropy* entropy) {
888 return entropy->generate_random_data(mSalt, sizeof(mSalt));
889 }
890
891 bool generateMasterKey(Entropy* entropy) {
892 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
893 return false;
894 }
895 if (!generateSalt(entropy)) {
896 return false;
897 }
898 return true;
899 }
900
901 void setupMasterKeys() {
902 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
903 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
904 setState(STATE_NO_ERROR);
905 }
906
907 uid_t mUserId;
908
909 char* mUserDir;
910 char* mMasterKeyFile;
911
912 State mState;
913 int8_t mRetry;
914
915 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
916 uint8_t mSalt[SALT_SIZE];
917
918 AES_KEY mMasterKeyEncryption;
919 AES_KEY mMasterKeyDecryption;
920};
921
922typedef struct {
923 uint32_t uid;
924 const uint8_t* filename;
925} grant_t;
926
927class KeyStore {
928public:
929 KeyStore(Entropy* entropy, keymaster_device_t* device)
930 : mEntropy(entropy)
931 , mDevice(device)
932 {
933 memset(&mMetaData, '\0', sizeof(mMetaData));
934 }
935
936 ~KeyStore() {
937 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
938 it != mGrants.end(); it++) {
939 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700940 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800941 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700942
943 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
944 it != mMasterKeys.end(); it++) {
945 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700946 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800947 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700948 }
949
950 keymaster_device_t* getDevice() const {
951 return mDevice;
952 }
953
954 ResponseCode initialize() {
955 readMetaData();
956 if (upgradeKeystore()) {
957 writeMetaData();
958 }
959
960 return ::NO_ERROR;
961 }
962
963 State getState(uid_t uid) {
964 return getUserState(uid)->getState();
965 }
966
967 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
968 UserState* userState = getUserState(uid);
969 return userState->initialize(pw, mEntropy);
970 }
971
972 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
973 uid_t user_id = get_user_id(uid);
974 UserState* userState = getUserState(user_id);
975 return userState->writeMasterKey(pw, mEntropy);
976 }
977
978 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
979 uid_t user_id = get_user_id(uid);
980 UserState* userState = getUserState(user_id);
981 return userState->readMasterKey(pw, mEntropy);
982 }
983
984 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700985 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700986 encode_key(encoded, keyName);
987 return android::String8(encoded);
988 }
989
990 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700991 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700992 encode_key(encoded, keyName);
993 return android::String8::format("%u_%s", uid, encoded);
994 }
995
996 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -0700997 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -0700998 encode_key(encoded, keyName);
999 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1000 encoded);
1001 }
1002
1003 bool reset(uid_t uid) {
1004 UserState* userState = getUserState(uid);
1005 userState->zeroizeMasterKeysInMemory();
1006 userState->setState(STATE_UNINITIALIZED);
1007 return userState->reset();
1008 }
1009
1010 bool isEmpty(uid_t uid) const {
1011 const UserState* userState = getUserState(uid);
1012 if (userState == NULL) {
1013 return true;
1014 }
1015
1016 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001017 struct dirent* file;
1018 if (!dir) {
1019 return true;
1020 }
1021 bool result = true;
Kenny Root655b9582013-04-04 08:37:42 -07001022
1023 char filename[NAME_MAX];
1024 int n = snprintf(filename, sizeof(filename), "%u_", uid);
1025
Kenny Roota91203b2012-02-15 15:00:46 -08001026 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001027 // We only care about files.
1028 if (file->d_type != DT_REG) {
1029 continue;
1030 }
1031
1032 // Skip anything that starts with a "."
1033 if (file->d_name[0] == '.') {
1034 continue;
1035 }
1036
1037 if (!strncmp(file->d_name, filename, n)) {
Kenny Roota91203b2012-02-15 15:00:46 -08001038 result = false;
1039 break;
1040 }
1041 }
1042 closedir(dir);
1043 return result;
1044 }
1045
Kenny Root655b9582013-04-04 08:37:42 -07001046 void lock(uid_t uid) {
1047 UserState* userState = getUserState(uid);
1048 userState->zeroizeMasterKeysInMemory();
1049 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001050 }
1051
Kenny Root655b9582013-04-04 08:37:42 -07001052 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1053 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001054 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1055 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001056 if (rc != NO_ERROR) {
1057 return rc;
1058 }
1059
1060 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001061 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001062 /* If we upgrade the key, we need to write it to disk again. Then
1063 * it must be read it again since the blob is encrypted each time
1064 * it's written.
1065 */
Kenny Root655b9582013-04-04 08:37:42 -07001066 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1067 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001068 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1069 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001070 return rc;
1071 }
1072 }
Kenny Root822c3a92012-03-23 16:34:39 -07001073 }
1074
Kenny Root17208e02013-09-04 13:56:03 -07001075 /*
1076 * This will upgrade software-backed keys to hardware-backed keys when
1077 * the HAL for the device supports the newer key types.
1078 */
1079 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1080 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1081 && keyBlob->isFallback()) {
1082 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1083 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1084
1085 // The HAL allowed the import, reget the key to have the "fresh"
1086 // version.
1087 if (imported == NO_ERROR) {
1088 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1089 }
1090 }
1091
Kenny Rootd53bc922013-03-21 14:10:15 -07001092 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001093 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1094 return KEY_NOT_FOUND;
1095 }
1096
1097 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001098 }
1099
Kenny Root655b9582013-04-04 08:37:42 -07001100 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1101 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001102 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1103 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001104 }
1105
Kenny Root07438c82012-11-02 15:41:02 -07001106 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001107 const grant_t* existing = getGrant(filename, granteeUid);
1108 if (existing == NULL) {
1109 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001110 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001111 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001112 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001113 }
1114 }
1115
Kenny Root07438c82012-11-02 15:41:02 -07001116 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001117 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1118 it != mGrants.end(); it++) {
1119 grant_t* grant = *it;
1120 if (grant->uid == granteeUid
1121 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1122 mGrants.erase(it);
1123 return true;
1124 }
Kenny Root70e3a862012-02-15 17:20:23 -08001125 }
Kenny Root70e3a862012-02-15 17:20:23 -08001126 return false;
1127 }
1128
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001129 bool hasGrant(const char* filename, const uid_t uid) const {
1130 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001131 }
1132
Kenny Rootf9119d62013-04-03 09:22:15 -07001133 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1134 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001135 uint8_t* data;
1136 size_t dataLength;
1137 int rc;
1138
1139 if (mDevice->import_keypair == NULL) {
1140 ALOGE("Keymaster doesn't support import!");
1141 return SYSTEM_ERROR;
1142 }
1143
Kenny Root17208e02013-09-04 13:56:03 -07001144 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001145 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001146 if (rc) {
Kenny Root17208e02013-09-04 13:56:03 -07001147 // If this is an old device HAL, try to fall back to an old version
1148 if (mDevice->common.module->module_api_version < KEYMASTER_MODULE_API_VERSION_0_2) {
1149 rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength);
1150 isFallback = true;
1151 }
1152
1153 if (rc) {
1154 ALOGE("Error while importing keypair: %d", rc);
1155 return SYSTEM_ERROR;
1156 }
Kenny Root822c3a92012-03-23 16:34:39 -07001157 }
1158
1159 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1160 free(data);
1161
Kenny Rootf9119d62013-04-03 09:22:15 -07001162 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001163 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001164
Kenny Root655b9582013-04-04 08:37:42 -07001165 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001166 }
1167
Kenny Root1b0e3932013-09-05 13:06:32 -07001168 bool isHardwareBacked(const android::String16& keyType) const {
1169 if (mDevice == NULL) {
1170 ALOGW("can't get keymaster device");
1171 return false;
1172 }
1173
1174 if (sRSAKeyType == keyType) {
1175 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1176 } else {
1177 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1178 && (mDevice->common.module->module_api_version
1179 >= KEYMASTER_MODULE_API_VERSION_0_2);
1180 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001181 }
1182
Kenny Root655b9582013-04-04 08:37:42 -07001183 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1184 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001185 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001186
1187 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1188 if (responseCode == NO_ERROR) {
1189 return responseCode;
1190 }
1191
1192 // If this is one of the legacy UID->UID mappings, use it.
1193 uid_t euid = get_keystore_euid(uid);
1194 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001195 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001196 responseCode = get(filepath8.string(), keyBlob, type, uid);
1197 if (responseCode == NO_ERROR) {
1198 return responseCode;
1199 }
1200 }
1201
1202 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001203 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001204 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001205 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001206 if (end[0] != '_' || end[1] == 0) {
1207 return KEY_NOT_FOUND;
1208 }
Kenny Root86b16e82013-09-09 11:15:54 -07001209 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1210 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001211 if (!hasGrant(filepath8.string(), uid)) {
1212 return responseCode;
1213 }
1214
1215 // It is a granted key. Try to load it.
1216 return get(filepath8.string(), keyBlob, type, uid);
1217 }
1218
1219 /**
1220 * Returns any existing UserState or creates it if it doesn't exist.
1221 */
1222 UserState* getUserState(uid_t uid) {
1223 uid_t userId = get_user_id(uid);
1224
1225 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1226 it != mMasterKeys.end(); it++) {
1227 UserState* state = *it;
1228 if (state->getUserId() == userId) {
1229 return state;
1230 }
1231 }
1232
1233 UserState* userState = new UserState(userId);
1234 if (!userState->initialize()) {
1235 /* There's not much we can do if initialization fails. Trying to
1236 * unlock the keystore for that user will fail as well, so any
1237 * subsequent request for this user will just return SYSTEM_ERROR.
1238 */
1239 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1240 }
1241 mMasterKeys.add(userState);
1242 return userState;
1243 }
1244
1245 /**
1246 * Returns NULL if the UserState doesn't already exist.
1247 */
1248 const UserState* getUserState(uid_t uid) const {
1249 uid_t userId = get_user_id(uid);
1250
1251 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1252 it != mMasterKeys.end(); it++) {
1253 UserState* state = *it;
1254 if (state->getUserId() == userId) {
1255 return state;
1256 }
1257 }
1258
1259 return NULL;
1260 }
1261
Kenny Roota91203b2012-02-15 15:00:46 -08001262private:
Kenny Root655b9582013-04-04 08:37:42 -07001263 static const char* sOldMasterKey;
1264 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001265 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001266 Entropy* mEntropy;
1267
Kenny Root70e3a862012-02-15 17:20:23 -08001268 keymaster_device_t* mDevice;
1269
Kenny Root655b9582013-04-04 08:37:42 -07001270 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001271
Kenny Root655b9582013-04-04 08:37:42 -07001272 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001273
Kenny Root655b9582013-04-04 08:37:42 -07001274 typedef struct {
1275 uint32_t version;
1276 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001277
Kenny Root655b9582013-04-04 08:37:42 -07001278 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001279
Kenny Root655b9582013-04-04 08:37:42 -07001280 const grant_t* getGrant(const char* filename, uid_t uid) const {
1281 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1282 it != mGrants.end(); it++) {
1283 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001284 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001285 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001286 return grant;
1287 }
1288 }
Kenny Root70e3a862012-02-15 17:20:23 -08001289 return NULL;
1290 }
1291
Kenny Root822c3a92012-03-23 16:34:39 -07001292 /**
1293 * Upgrade code. This will upgrade the key from the current version
1294 * to whatever is newest.
1295 */
Kenny Root655b9582013-04-04 08:37:42 -07001296 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1297 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001298 bool updated = false;
1299 uint8_t version = oldVersion;
1300
1301 /* From V0 -> V1: All old types were unknown */
1302 if (version == 0) {
1303 ALOGV("upgrading to version 1 and setting type %d", type);
1304
1305 blob->setType(type);
1306 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001307 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001308 }
1309 version = 1;
1310 updated = true;
1311 }
1312
Kenny Rootf9119d62013-04-03 09:22:15 -07001313 /* From V1 -> V2: All old keys were encrypted */
1314 if (version == 1) {
1315 ALOGV("upgrading to version 2");
1316
1317 blob->setEncrypted(true);
1318 version = 2;
1319 updated = true;
1320 }
1321
Kenny Root822c3a92012-03-23 16:34:39 -07001322 /*
1323 * If we've updated, set the key blob to the right version
1324 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001325 */
Kenny Root822c3a92012-03-23 16:34:39 -07001326 if (updated) {
1327 ALOGV("updated and writing file %s", filename);
1328 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001329 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001330
1331 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001332 }
1333
1334 /**
1335 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1336 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1337 * Then it overwrites the original blob with the new blob
1338 * format that is returned from the keymaster.
1339 */
Kenny Root655b9582013-04-04 08:37:42 -07001340 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001341 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1342 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1343 if (b.get() == NULL) {
1344 ALOGE("Problem instantiating BIO");
1345 return SYSTEM_ERROR;
1346 }
1347
1348 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1349 if (pkey.get() == NULL) {
1350 ALOGE("Couldn't read old PEM file");
1351 return SYSTEM_ERROR;
1352 }
1353
1354 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1355 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1356 if (len < 0) {
1357 ALOGE("Couldn't measure PKCS#8 length");
1358 return SYSTEM_ERROR;
1359 }
1360
Kenny Root70c98892013-02-07 09:10:36 -08001361 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1362 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001363 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1364 ALOGE("Couldn't convert to PKCS#8");
1365 return SYSTEM_ERROR;
1366 }
1367
Kenny Rootf9119d62013-04-03 09:22:15 -07001368 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1369 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001370 if (rc != NO_ERROR) {
1371 return rc;
1372 }
1373
Kenny Root655b9582013-04-04 08:37:42 -07001374 return get(filename, blob, TYPE_KEY_PAIR, uid);
1375 }
1376
1377 void readMetaData() {
1378 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1379 if (in < 0) {
1380 return;
1381 }
1382 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1383 if (fileLength != sizeof(mMetaData)) {
1384 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1385 sizeof(mMetaData));
1386 }
1387 close(in);
1388 }
1389
1390 void writeMetaData() {
1391 const char* tmpFileName = ".metadata.tmp";
1392 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1393 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1394 if (out < 0) {
1395 ALOGE("couldn't write metadata file: %s", strerror(errno));
1396 return;
1397 }
1398 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1399 if (fileLength != sizeof(mMetaData)) {
1400 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1401 sizeof(mMetaData));
1402 }
1403 close(out);
1404 rename(tmpFileName, sMetaDataFile);
1405 }
1406
1407 bool upgradeKeystore() {
1408 bool upgraded = false;
1409
1410 if (mMetaData.version == 0) {
1411 UserState* userState = getUserState(0);
1412
1413 // Initialize first so the directory is made.
1414 userState->initialize();
1415
1416 // Migrate the old .masterkey file to user 0.
1417 if (access(sOldMasterKey, R_OK) == 0) {
1418 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1419 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1420 return false;
1421 }
1422 }
1423
1424 // Initialize again in case we had a key.
1425 userState->initialize();
1426
1427 // Try to migrate existing keys.
1428 DIR* dir = opendir(".");
1429 if (!dir) {
1430 // Give up now; maybe we can upgrade later.
1431 ALOGE("couldn't open keystore's directory; something is wrong");
1432 return false;
1433 }
1434
1435 struct dirent* file;
1436 while ((file = readdir(dir)) != NULL) {
1437 // We only care about files.
1438 if (file->d_type != DT_REG) {
1439 continue;
1440 }
1441
1442 // Skip anything that starts with a "."
1443 if (file->d_name[0] == '.') {
1444 continue;
1445 }
1446
1447 // Find the current file's user.
1448 char* end;
1449 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1450 if (end[0] != '_' || end[1] == 0) {
1451 continue;
1452 }
1453 UserState* otherUser = getUserState(thisUid);
1454 if (otherUser->getUserId() != 0) {
1455 unlinkat(dirfd(dir), file->d_name, 0);
1456 }
1457
1458 // Rename the file into user directory.
1459 DIR* otherdir = opendir(otherUser->getUserDirName());
1460 if (otherdir == NULL) {
1461 ALOGW("couldn't open user directory for rename");
1462 continue;
1463 }
1464 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1465 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1466 }
1467 closedir(otherdir);
1468 }
1469 closedir(dir);
1470
1471 mMetaData.version = 1;
1472 upgraded = true;
1473 }
1474
1475 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001476 }
Kenny Roota91203b2012-02-15 15:00:46 -08001477};
1478
Kenny Root655b9582013-04-04 08:37:42 -07001479const char* KeyStore::sOldMasterKey = ".masterkey";
1480const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001481
Kenny Root1b0e3932013-09-05 13:06:32 -07001482const android::String16 KeyStore::sRSAKeyType("RSA");
1483
Kenny Root07438c82012-11-02 15:41:02 -07001484namespace android {
1485class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1486public:
1487 KeyStoreProxy(KeyStore* keyStore)
1488 : mKeyStore(keyStore)
1489 {
Kenny Roota91203b2012-02-15 15:00:46 -08001490 }
Kenny Roota91203b2012-02-15 15:00:46 -08001491
Kenny Root07438c82012-11-02 15:41:02 -07001492 void binderDied(const wp<IBinder>&) {
1493 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001494 }
Kenny Roota91203b2012-02-15 15:00:46 -08001495
Kenny Root07438c82012-11-02 15:41:02 -07001496 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001497 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001498 pid_t spid = IPCThreadState::self()->getCallingPid();
1499 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001500 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001501 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001502 }
Kenny Roota91203b2012-02-15 15:00:46 -08001503
Kenny Root655b9582013-04-04 08:37:42 -07001504 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001505 }
1506
Kenny Root07438c82012-11-02 15:41:02 -07001507 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001508 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001509 pid_t spid = IPCThreadState::self()->getCallingPid();
1510 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001511 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001512 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001513 }
Kenny Root07438c82012-11-02 15:41:02 -07001514
Kenny Root07438c82012-11-02 15:41:02 -07001515 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001516 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001517
Kenny Root655b9582013-04-04 08:37:42 -07001518 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001519 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001520 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001521 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001522 *item = NULL;
1523 *itemLength = 0;
1524 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001525 }
Kenny Roota91203b2012-02-15 15:00:46 -08001526
Kenny Root07438c82012-11-02 15:41:02 -07001527 *item = (uint8_t*) malloc(keyBlob.getLength());
1528 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1529 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001530
Kenny Root07438c82012-11-02 15:41:02 -07001531 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001532 }
1533
Kenny Rootf9119d62013-04-03 09:22:15 -07001534 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1535 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001536 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001537 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001538 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001539 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001540 return ::PERMISSION_DENIED;
1541 }
Kenny Root07438c82012-11-02 15:41:02 -07001542
Kenny Rootf9119d62013-04-03 09:22:15 -07001543 State state = mKeyStore->getState(callingUid);
1544 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1545 ALOGD("calling get in state: %d", state);
1546 return state;
1547 }
1548
Kenny Root49468902013-03-19 13:41:33 -07001549 if (targetUid == -1) {
1550 targetUid = callingUid;
1551 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001552 return ::PERMISSION_DENIED;
1553 }
1554
Kenny Root07438c82012-11-02 15:41:02 -07001555 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001556 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001557
1558 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001559 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1560
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001561 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001562 }
1563
Kenny Root49468902013-03-19 13:41:33 -07001564 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001565 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001566 pid_t spid = IPCThreadState::self()->getCallingPid();
1567 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001568 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001569 return ::PERMISSION_DENIED;
1570 }
Kenny Root70e3a862012-02-15 17:20:23 -08001571
Kenny Root49468902013-03-19 13:41:33 -07001572 if (targetUid == -1) {
1573 targetUid = callingUid;
1574 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001575 return ::PERMISSION_DENIED;
1576 }
1577
Kenny Root07438c82012-11-02 15:41:02 -07001578 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001579 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001580
1581 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001582 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001583 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07001584 if (responseCode != ::NO_ERROR) {
1585 return responseCode;
1586 }
1587 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001588 }
1589
Kenny Root49468902013-03-19 13:41:33 -07001590 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001591 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001592 pid_t spid = IPCThreadState::self()->getCallingPid();
1593 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001594 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001595 return ::PERMISSION_DENIED;
1596 }
Kenny Root70e3a862012-02-15 17:20:23 -08001597
Kenny Root49468902013-03-19 13:41:33 -07001598 if (targetUid == -1) {
1599 targetUid = callingUid;
1600 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001601 return ::PERMISSION_DENIED;
1602 }
1603
Kenny Root07438c82012-11-02 15:41:02 -07001604 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001605 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001606
Kenny Root655b9582013-04-04 08:37:42 -07001607 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001608 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1609 }
1610 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001611 }
1612
Kenny Root49468902013-03-19 13:41:33 -07001613 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001614 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001615 pid_t spid = IPCThreadState::self()->getCallingPid();
1616 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001617 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001618 return ::PERMISSION_DENIED;
1619 }
Kenny Root70e3a862012-02-15 17:20:23 -08001620
Kenny Root49468902013-03-19 13:41:33 -07001621 if (targetUid == -1) {
1622 targetUid = callingUid;
1623 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001624 return ::PERMISSION_DENIED;
1625 }
1626
Kenny Root655b9582013-04-04 08:37:42 -07001627 UserState* userState = mKeyStore->getUserState(targetUid);
1628 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001629 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07001630 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001631 return ::SYSTEM_ERROR;
1632 }
Kenny Root70e3a862012-02-15 17:20:23 -08001633
Kenny Root07438c82012-11-02 15:41:02 -07001634 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001635 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1636 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001637
Kenny Root07438c82012-11-02 15:41:02 -07001638 struct dirent* file;
1639 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001640 // We only care about files.
1641 if (file->d_type != DT_REG) {
1642 continue;
1643 }
1644
1645 // Skip anything that starts with a "."
1646 if (file->d_name[0] == '.') {
1647 continue;
1648 }
1649
1650 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001651 const char* p = &file->d_name[n];
1652 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001653
Kenny Root07438c82012-11-02 15:41:02 -07001654 size_t extra = decode_key_length(p, plen);
1655 char *match = (char*) malloc(extra + 1);
1656 if (match != NULL) {
1657 decode_key(match, p, plen);
1658 matches->push(String16(match, extra));
1659 free(match);
1660 } else {
1661 ALOGW("could not allocate match of size %zd", extra);
1662 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001663 }
1664 }
Kenny Root07438c82012-11-02 15:41:02 -07001665 closedir(dir);
1666
1667 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001668 }
1669
Kenny Root07438c82012-11-02 15:41:02 -07001670 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001671 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001672 pid_t spid = IPCThreadState::self()->getCallingPid();
1673 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001674 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001675 return ::PERMISSION_DENIED;
1676 }
1677
Kenny Root655b9582013-04-04 08:37:42 -07001678 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001679
1680 const keymaster_device_t* device = mKeyStore->getDevice();
1681 if (device == NULL) {
1682 ALOGE("No keymaster device!");
1683 return ::SYSTEM_ERROR;
1684 }
1685
1686 if (device->delete_all == NULL) {
1687 ALOGV("keymaster device doesn't implement delete_all");
1688 return rc;
1689 }
1690
1691 if (device->delete_all(device)) {
1692 ALOGE("Problem calling keymaster's delete_all");
1693 return ::SYSTEM_ERROR;
1694 }
1695
Kenny Root9a53d3e2012-08-14 10:47:54 -07001696 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001697 }
1698
Kenny Root07438c82012-11-02 15:41:02 -07001699 /*
1700 * Here is the history. To improve the security, the parameters to generate the
1701 * master key has been changed. To make a seamless transition, we update the
1702 * file using the same password when the user unlock it for the first time. If
1703 * any thing goes wrong during the transition, the new file will not overwrite
1704 * the old one. This avoids permanent damages of the existing data.
1705 */
1706 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001707 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001708 pid_t spid = IPCThreadState::self()->getCallingPid();
1709 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001710 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001711 return ::PERMISSION_DENIED;
1712 }
Kenny Root70e3a862012-02-15 17:20:23 -08001713
Kenny Root07438c82012-11-02 15:41:02 -07001714 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001715
Kenny Root655b9582013-04-04 08:37:42 -07001716 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001717 case ::STATE_UNINITIALIZED: {
1718 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001719 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001720 }
1721 case ::STATE_NO_ERROR: {
1722 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001723 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001724 }
1725 case ::STATE_LOCKED: {
1726 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001727 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001728 }
1729 }
1730 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001731 }
1732
Kenny Root07438c82012-11-02 15:41:02 -07001733 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001734 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001735 pid_t spid = IPCThreadState::self()->getCallingPid();
1736 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001737 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001738 return ::PERMISSION_DENIED;
1739 }
Kenny Root70e3a862012-02-15 17:20:23 -08001740
Kenny Root655b9582013-04-04 08:37:42 -07001741 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001742 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001743 ALOGD("calling lock in state: %d", state);
1744 return state;
1745 }
1746
Kenny Root655b9582013-04-04 08:37:42 -07001747 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001748 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001749 }
1750
Kenny Root07438c82012-11-02 15:41:02 -07001751 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001752 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001753 pid_t spid = IPCThreadState::self()->getCallingPid();
1754 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001755 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001756 return ::PERMISSION_DENIED;
1757 }
1758
Kenny Root655b9582013-04-04 08:37:42 -07001759 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001760 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001761 ALOGD("calling unlock when not locked");
1762 return state;
1763 }
1764
1765 const String8 password8(pw);
1766 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001767 }
1768
Kenny Root07438c82012-11-02 15:41:02 -07001769 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001770 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001771 pid_t spid = IPCThreadState::self()->getCallingPid();
1772 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001773 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001774 return -1;
1775 }
Kenny Root70e3a862012-02-15 17:20:23 -08001776
Kenny Root655b9582013-04-04 08:37:42 -07001777 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001778 }
1779
Kenny Root96427ba2013-08-16 14:02:41 -07001780 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1781 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001782 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001783 pid_t spid = IPCThreadState::self()->getCallingPid();
1784 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001785 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001786 return ::PERMISSION_DENIED;
1787 }
Kenny Root70e3a862012-02-15 17:20:23 -08001788
Kenny Root49468902013-03-19 13:41:33 -07001789 if (targetUid == -1) {
1790 targetUid = callingUid;
1791 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001792 return ::PERMISSION_DENIED;
1793 }
1794
Kenny Root655b9582013-04-04 08:37:42 -07001795 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001796 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1797 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001798 return state;
1799 }
Kenny Root70e3a862012-02-15 17:20:23 -08001800
Kenny Root07438c82012-11-02 15:41:02 -07001801 uint8_t* data;
1802 size_t dataLength;
1803 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001804 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001805
1806 const keymaster_device_t* device = mKeyStore->getDevice();
1807 if (device == NULL) {
1808 return ::SYSTEM_ERROR;
1809 }
1810
1811 if (device->generate_keypair == NULL) {
1812 return ::SYSTEM_ERROR;
1813 }
1814
Kenny Root17208e02013-09-04 13:56:03 -07001815 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001816 keymaster_dsa_keygen_params_t dsa_params;
1817 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001818
Kenny Root96427ba2013-08-16 14:02:41 -07001819 if (keySize == -1) {
1820 keySize = DSA_DEFAULT_KEY_SIZE;
1821 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1822 || keySize > DSA_MAX_KEY_SIZE) {
1823 ALOGI("invalid key size %d", keySize);
1824 return ::SYSTEM_ERROR;
1825 }
1826 dsa_params.key_size = keySize;
1827
1828 if (args->size() == 3) {
1829 sp<KeystoreArg> gArg = args->itemAt(0);
1830 sp<KeystoreArg> pArg = args->itemAt(1);
1831 sp<KeystoreArg> qArg = args->itemAt(2);
1832
1833 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1834 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1835 dsa_params.generator_len = gArg->size();
1836
1837 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1838 dsa_params.prime_p_len = pArg->size();
1839
1840 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1841 dsa_params.prime_q_len = qArg->size();
1842 } else {
1843 ALOGI("not all DSA parameters were read");
1844 return ::SYSTEM_ERROR;
1845 }
1846 } else if (args->size() != 0) {
1847 ALOGI("DSA args must be 3");
1848 return ::SYSTEM_ERROR;
1849 }
1850
Kenny Root1d448c02013-11-21 10:36:53 -08001851 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001852 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1853 } else {
1854 isFallback = true;
1855 rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1856 }
1857 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001858 keymaster_ec_keygen_params_t ec_params;
1859 memset(&ec_params, '\0', sizeof(ec_params));
1860
1861 if (keySize == -1) {
1862 keySize = EC_DEFAULT_KEY_SIZE;
1863 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1864 ALOGI("invalid key size %d", keySize);
1865 return ::SYSTEM_ERROR;
1866 }
1867 ec_params.field_size = keySize;
1868
Kenny Root1d448c02013-11-21 10:36:53 -08001869 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001870 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1871 } else {
1872 isFallback = true;
1873 rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1874 }
Kenny Root96427ba2013-08-16 14:02:41 -07001875 } else if (keyType == EVP_PKEY_RSA) {
1876 keymaster_rsa_keygen_params_t rsa_params;
1877 memset(&rsa_params, '\0', sizeof(rsa_params));
1878 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1879
1880 if (keySize == -1) {
1881 keySize = RSA_DEFAULT_KEY_SIZE;
1882 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1883 ALOGI("invalid key size %d", keySize);
1884 return ::SYSTEM_ERROR;
1885 }
1886 rsa_params.modulus_size = keySize;
1887
1888 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001889 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001890 return ::SYSTEM_ERROR;
1891 } else if (args->size() == 1) {
1892 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1893 if (pubExpBlob != NULL) {
1894 Unique_BIGNUM pubExpBn(
1895 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1896 pubExpBlob->size(), NULL));
1897 if (pubExpBn.get() == NULL) {
1898 ALOGI("Could not convert public exponent to BN");
1899 return ::SYSTEM_ERROR;
1900 }
1901 unsigned long pubExp = BN_get_word(pubExpBn.get());
1902 if (pubExp == 0xFFFFFFFFL) {
1903 ALOGI("cannot represent public exponent as a long value");
1904 return ::SYSTEM_ERROR;
1905 }
1906 rsa_params.public_exponent = pubExp;
1907 }
1908 }
1909
1910 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1911 } else {
1912 ALOGW("Unsupported key type %d", keyType);
1913 rc = -1;
1914 }
1915
Kenny Root07438c82012-11-02 15:41:02 -07001916 if (rc) {
1917 return ::SYSTEM_ERROR;
1918 }
1919
Kenny Root655b9582013-04-04 08:37:42 -07001920 String8 name8(name);
1921 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001922
1923 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1924 free(data);
1925
Kenny Rootee8068b2013-10-07 09:49:15 -07001926 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001927 keyBlob.setFallback(isFallback);
1928
Kenny Root655b9582013-04-04 08:37:42 -07001929 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001930 }
1931
Kenny Rootf9119d62013-04-03 09:22:15 -07001932 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1933 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001934 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001935 pid_t spid = IPCThreadState::self()->getCallingPid();
1936 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001937 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001938 return ::PERMISSION_DENIED;
1939 }
Kenny Root07438c82012-11-02 15:41:02 -07001940
Kenny Root49468902013-03-19 13:41:33 -07001941 if (targetUid == -1) {
1942 targetUid = callingUid;
1943 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001944 return ::PERMISSION_DENIED;
1945 }
1946
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001947 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001948 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001949 ALOGD("calling import in state: %d", state);
1950 return state;
1951 }
1952
1953 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001954 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001955
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001956 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001957 }
1958
Kenny Root07438c82012-11-02 15:41:02 -07001959 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1960 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001961 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001962 pid_t spid = IPCThreadState::self()->getCallingPid();
1963 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001964 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001965 return ::PERMISSION_DENIED;
1966 }
Kenny Root07438c82012-11-02 15:41:02 -07001967
Kenny Root07438c82012-11-02 15:41:02 -07001968 Blob keyBlob;
1969 String8 name8(name);
1970
Kenny Rootd38a0b02013-02-13 12:59:14 -08001971 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001972 int rc;
1973
Kenny Root655b9582013-04-04 08:37:42 -07001974 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001975 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001976 if (responseCode != ::NO_ERROR) {
1977 return responseCode;
1978 }
1979
1980 const keymaster_device_t* device = mKeyStore->getDevice();
1981 if (device == NULL) {
1982 ALOGE("no keymaster device; cannot sign");
1983 return ::SYSTEM_ERROR;
1984 }
1985
1986 if (device->sign_data == NULL) {
1987 ALOGE("device doesn't implement signing");
1988 return ::SYSTEM_ERROR;
1989 }
1990
1991 keymaster_rsa_sign_params_t params;
1992 params.digest_type = DIGEST_NONE;
1993 params.padding_type = PADDING_NONE;
1994
Kenny Root17208e02013-09-04 13:56:03 -07001995 if (keyBlob.isFallback()) {
1996 rc = openssl_sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
1997 length, out, outLength);
1998 } else {
1999 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2000 length, out, outLength);
2001 }
Kenny Root07438c82012-11-02 15:41:02 -07002002 if (rc) {
2003 ALOGW("device couldn't sign data");
2004 return ::SYSTEM_ERROR;
2005 }
2006
2007 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002008 }
2009
Kenny Root07438c82012-11-02 15:41:02 -07002010 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2011 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002012 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002013 pid_t spid = IPCThreadState::self()->getCallingPid();
2014 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002015 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002016 return ::PERMISSION_DENIED;
2017 }
Kenny Root70e3a862012-02-15 17:20:23 -08002018
Kenny Root655b9582013-04-04 08:37:42 -07002019 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002020 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002021 ALOGD("calling verify in state: %d", state);
2022 return state;
2023 }
Kenny Root70e3a862012-02-15 17:20:23 -08002024
Kenny Root07438c82012-11-02 15:41:02 -07002025 Blob keyBlob;
2026 String8 name8(name);
2027 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002028
Kenny Root655b9582013-04-04 08:37:42 -07002029 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002030 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002031 if (responseCode != ::NO_ERROR) {
2032 return responseCode;
2033 }
Kenny Root70e3a862012-02-15 17:20:23 -08002034
Kenny Root07438c82012-11-02 15:41:02 -07002035 const keymaster_device_t* device = mKeyStore->getDevice();
2036 if (device == NULL) {
2037 return ::SYSTEM_ERROR;
2038 }
Kenny Root70e3a862012-02-15 17:20:23 -08002039
Kenny Root07438c82012-11-02 15:41:02 -07002040 if (device->verify_data == NULL) {
2041 return ::SYSTEM_ERROR;
2042 }
Kenny Root70e3a862012-02-15 17:20:23 -08002043
Kenny Root07438c82012-11-02 15:41:02 -07002044 keymaster_rsa_sign_params_t params;
2045 params.digest_type = DIGEST_NONE;
2046 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002047
Kenny Root17208e02013-09-04 13:56:03 -07002048 if (keyBlob.isFallback()) {
2049 rc = openssl_verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2050 dataLength, signature, signatureLength);
2051 } else {
2052 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2053 dataLength, signature, signatureLength);
2054 }
Kenny Root07438c82012-11-02 15:41:02 -07002055 if (rc) {
2056 return ::SYSTEM_ERROR;
2057 } else {
2058 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002059 }
2060 }
Kenny Root07438c82012-11-02 15:41:02 -07002061
2062 /*
2063 * TODO: The abstraction between things stored in hardware and regular blobs
2064 * of data stored on the filesystem should be moved down to keystore itself.
2065 * Unfortunately the Java code that calls this has naming conventions that it
2066 * knows about. Ideally keystore shouldn't be used to store random blobs of
2067 * data.
2068 *
2069 * Until that happens, it's necessary to have a separate "get_pubkey" and
2070 * "del_key" since the Java code doesn't really communicate what it's
2071 * intentions are.
2072 */
2073 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002074 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002075 pid_t spid = IPCThreadState::self()->getCallingPid();
2076 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002077 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002078 return ::PERMISSION_DENIED;
2079 }
Kenny Root07438c82012-11-02 15:41:02 -07002080
Kenny Root07438c82012-11-02 15:41:02 -07002081 Blob keyBlob;
2082 String8 name8(name);
2083
Kenny Rootd38a0b02013-02-13 12:59:14 -08002084 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002085
Kenny Root655b9582013-04-04 08:37:42 -07002086 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002087 TYPE_KEY_PAIR);
2088 if (responseCode != ::NO_ERROR) {
2089 return responseCode;
2090 }
2091
2092 const keymaster_device_t* device = mKeyStore->getDevice();
2093 if (device == NULL) {
2094 return ::SYSTEM_ERROR;
2095 }
2096
2097 if (device->get_keypair_public == NULL) {
2098 ALOGE("device has no get_keypair_public implementation!");
2099 return ::SYSTEM_ERROR;
2100 }
2101
Kenny Root17208e02013-09-04 13:56:03 -07002102 int rc;
2103 if (keyBlob.isFallback()) {
2104 rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2105 pubkeyLength);
2106 } else {
2107 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2108 pubkeyLength);
2109 }
Kenny Root07438c82012-11-02 15:41:02 -07002110 if (rc) {
2111 return ::SYSTEM_ERROR;
2112 }
2113
2114 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002115 }
Kenny Root07438c82012-11-02 15:41:02 -07002116
Kenny Root49468902013-03-19 13:41:33 -07002117 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002118 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002119 pid_t spid = IPCThreadState::self()->getCallingPid();
2120 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002121 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002122 return ::PERMISSION_DENIED;
2123 }
Kenny Root07438c82012-11-02 15:41:02 -07002124
Kenny Root49468902013-03-19 13:41:33 -07002125 if (targetUid == -1) {
2126 targetUid = callingUid;
2127 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002128 return ::PERMISSION_DENIED;
2129 }
2130
Kenny Root07438c82012-11-02 15:41:02 -07002131 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002132 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002133
2134 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002135 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002136 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002137 if (responseCode != ::NO_ERROR) {
2138 return responseCode;
2139 }
2140
2141 ResponseCode rc = ::NO_ERROR;
2142
2143 const keymaster_device_t* device = mKeyStore->getDevice();
2144 if (device == NULL) {
2145 rc = ::SYSTEM_ERROR;
2146 } else {
2147 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002148 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Root07438c82012-11-02 15:41:02 -07002149 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2150 rc = ::SYSTEM_ERROR;
2151 }
2152 }
2153 }
2154
2155 if (rc != ::NO_ERROR) {
2156 return rc;
2157 }
2158
2159 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
2160 }
2161
2162 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002163 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002164 pid_t spid = IPCThreadState::self()->getCallingPid();
2165 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002166 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002167 return ::PERMISSION_DENIED;
2168 }
Kenny Root07438c82012-11-02 15:41:02 -07002169
Kenny Root655b9582013-04-04 08:37:42 -07002170 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002171 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002172 ALOGD("calling grant in state: %d", state);
2173 return state;
2174 }
2175
2176 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002177 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002178
Kenny Root655b9582013-04-04 08:37:42 -07002179 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002180 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2181 }
2182
Kenny Root655b9582013-04-04 08:37:42 -07002183 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002184 return ::NO_ERROR;
2185 }
2186
2187 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002188 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002189 pid_t spid = IPCThreadState::self()->getCallingPid();
2190 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002191 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002192 return ::PERMISSION_DENIED;
2193 }
Kenny Root07438c82012-11-02 15:41:02 -07002194
Kenny Root655b9582013-04-04 08:37:42 -07002195 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002196 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002197 ALOGD("calling ungrant in state: %d", state);
2198 return state;
2199 }
2200
2201 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002202 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002203
Kenny Root655b9582013-04-04 08:37:42 -07002204 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002205 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2206 }
2207
Kenny Root655b9582013-04-04 08:37:42 -07002208 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002209 }
2210
2211 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002212 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002213 pid_t spid = IPCThreadState::self()->getCallingPid();
2214 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002215 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002216 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002217 }
Kenny Root07438c82012-11-02 15:41:02 -07002218
2219 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002220 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002221
Kenny Root655b9582013-04-04 08:37:42 -07002222 if (access(filename.string(), R_OK) == -1) {
2223 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002224 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002225 }
2226
Kenny Root655b9582013-04-04 08:37:42 -07002227 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002228 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002229 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002230 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002231 }
2232
2233 struct stat s;
2234 int ret = fstat(fd, &s);
2235 close(fd);
2236 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002237 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002238 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002239 }
2240
Kenny Root36a9e232013-02-04 14:24:15 -08002241 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002242 }
2243
Kenny Rootd53bc922013-03-21 14:10:15 -07002244 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2245 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002246 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002247 pid_t spid = IPCThreadState::self()->getCallingPid();
2248 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002249 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002250 return -1L;
2251 }
2252
Kenny Root655b9582013-04-04 08:37:42 -07002253 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002254 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002255 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002256 return state;
2257 }
2258
Kenny Rootd53bc922013-03-21 14:10:15 -07002259 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2260 srcUid = callingUid;
2261 } else if (!is_granted_to(callingUid, srcUid)) {
2262 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002263 return ::PERMISSION_DENIED;
2264 }
2265
Kenny Rootd53bc922013-03-21 14:10:15 -07002266 if (destUid == -1) {
2267 destUid = callingUid;
2268 }
2269
2270 if (srcUid != destUid) {
2271 if (static_cast<uid_t>(srcUid) != callingUid) {
2272 ALOGD("can only duplicate from caller to other or to same uid: "
2273 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2274 return ::PERMISSION_DENIED;
2275 }
2276
2277 if (!is_granted_to(callingUid, destUid)) {
2278 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2279 return ::PERMISSION_DENIED;
2280 }
2281 }
2282
2283 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002284 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002285
Kenny Rootd53bc922013-03-21 14:10:15 -07002286 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002287 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002288
Kenny Root655b9582013-04-04 08:37:42 -07002289 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2290 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002291 return ::SYSTEM_ERROR;
2292 }
2293
Kenny Rootd53bc922013-03-21 14:10:15 -07002294 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002295 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002296 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002297 if (responseCode != ::NO_ERROR) {
2298 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002299 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002300
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002301 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002302 }
2303
Kenny Root1b0e3932013-09-05 13:06:32 -07002304 int32_t is_hardware_backed(const String16& keyType) {
2305 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002306 }
2307
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002308 int32_t clear_uid(int64_t targetUid64) {
2309 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002310 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002311 pid_t spid = IPCThreadState::self()->getCallingPid();
2312 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002313 ALOGW("permission denied for %d: clear_uid", callingUid);
2314 return ::PERMISSION_DENIED;
2315 }
2316
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002317 if (targetUid64 == -1) {
2318 targetUid = callingUid;
Kenny Root007cb232014-07-30 16:59:42 -07002319 } else if (!is_self_or_system(callingUid, targetUid)) {
2320 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002321 return ::PERMISSION_DENIED;
2322 }
2323
Kenny Roota9bb5492013-04-01 16:29:11 -07002324 const keymaster_device_t* device = mKeyStore->getDevice();
2325 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002326 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002327 return ::SYSTEM_ERROR;
2328 }
2329
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002330 UserState* userState = mKeyStore->getUserState(targetUid);
Kenny Root655b9582013-04-04 08:37:42 -07002331 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota9bb5492013-04-01 16:29:11 -07002332 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07002333 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Roota9bb5492013-04-01 16:29:11 -07002334 return ::SYSTEM_ERROR;
2335 }
2336
Kenny Root655b9582013-04-04 08:37:42 -07002337 char prefix[NAME_MAX];
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002338 int n = snprintf(prefix, NAME_MAX, "%u_", targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002339
2340 ResponseCode rc = ::NO_ERROR;
2341
2342 struct dirent* file;
2343 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002344 // We only care about files.
2345 if (file->d_type != DT_REG) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002346 continue;
2347 }
2348
Kenny Root655b9582013-04-04 08:37:42 -07002349 // Skip anything that starts with a "."
2350 if (file->d_name[0] == '.') {
2351 continue;
2352 }
Kenny Roota9bb5492013-04-01 16:29:11 -07002353
Kenny Root655b9582013-04-04 08:37:42 -07002354 if (strncmp(prefix, file->d_name, n)) {
2355 continue;
2356 }
2357
2358 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Roota9bb5492013-04-01 16:29:11 -07002359 Blob keyBlob;
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002360 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, targetUid)
Kenny Root655b9582013-04-04 08:37:42 -07002361 != ::NO_ERROR) {
2362 ALOGW("couldn't open %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002363 continue;
2364 }
2365
2366 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2367 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002368 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002369 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2370 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002371 ALOGW("device couldn't remove %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002372 }
2373 }
2374 }
2375
Kenny Root5f531242013-04-12 11:31:50 -07002376 if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002377 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002378 ALOGW("couldn't unlink %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002379 }
2380 }
2381 closedir(dir);
2382
2383 return rc;
2384 }
2385
Kenny Root07438c82012-11-02 15:41:02 -07002386private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002387 inline bool isKeystoreUnlocked(State state) {
2388 switch (state) {
2389 case ::STATE_NO_ERROR:
2390 return true;
2391 case ::STATE_UNINITIALIZED:
2392 case ::STATE_LOCKED:
2393 return false;
2394 }
2395 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002396 }
2397
Kenny Root1d448c02013-11-21 10:36:53 -08002398 bool isKeyTypeSupported(const keymaster_device_t* device, keymaster_keypair_t keyType) {
2399 const int32_t device_api = device->common.module->module_api_version;
2400 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2401 switch (keyType) {
2402 case TYPE_RSA:
2403 case TYPE_DSA:
2404 case TYPE_EC:
2405 return true;
2406 default:
2407 return false;
2408 }
2409 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2410 switch (keyType) {
2411 case TYPE_RSA:
2412 return true;
2413 case TYPE_DSA:
2414 return device->flags & KEYMASTER_SUPPORTS_DSA;
2415 case TYPE_EC:
2416 return device->flags & KEYMASTER_SUPPORTS_EC;
2417 default:
2418 return false;
2419 }
2420 } else {
2421 return keyType == TYPE_RSA;
2422 }
2423 }
2424
Kenny Root07438c82012-11-02 15:41:02 -07002425 ::KeyStore* mKeyStore;
2426};
2427
2428}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002429
2430int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002431 if (argc < 2) {
2432 ALOGE("A directory must be specified!");
2433 return 1;
2434 }
2435 if (chdir(argv[1]) == -1) {
2436 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2437 return 1;
2438 }
2439
2440 Entropy entropy;
2441 if (!entropy.open()) {
2442 return 1;
2443 }
Kenny Root70e3a862012-02-15 17:20:23 -08002444
2445 keymaster_device_t* dev;
2446 if (keymaster_device_initialize(&dev)) {
2447 ALOGE("keystore keymaster could not be initialized; exiting");
2448 return 1;
2449 }
2450
Riley Spahneaabae92014-06-30 12:39:52 -07002451 ks_is_selinux_enabled = is_selinux_enabled();
2452 if (ks_is_selinux_enabled) {
2453 union selinux_callback cb;
2454 cb.func_log = selinux_log_callback;
2455 selinux_set_callback(SELINUX_CB_LOG, cb);
2456 if (getcon(&tctx) != 0) {
2457 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2458 return -1;
2459 }
2460 } else {
2461 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2462 }
2463
Kenny Root70e3a862012-02-15 17:20:23 -08002464 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002465 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002466 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2467 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2468 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2469 if (ret != android::OK) {
2470 ALOGE("Couldn't register binder service!");
2471 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002472 }
Kenny Root07438c82012-11-02 15:41:02 -07002473
2474 /*
2475 * We're the only thread in existence, so we're just going to process
2476 * Binder transaction as a single-threaded program.
2477 */
2478 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002479
2480 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002481 return 1;
2482}