blob: b0a476e7da3a5fde5c7d65656e2768f1b123451b [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 {
Robin Lee4e865752014-08-19 17:37:55 +0100139 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,
154 P_CLEAR_UID = 1 << 15,
155 P_RESET_UID = 1 << 16,
156 P_SYNC_UID = 1 << 17,
157 P_PASSWORD_UID = 1 << 18,
Kenny Root07438c82012-11-02 15:41:02 -0700158} perm_t;
159
160static struct user_euid {
161 uid_t uid;
162 uid_t euid;
163} user_euids[] = {
164 {AID_VPN, AID_SYSTEM},
165 {AID_WIFI, AID_SYSTEM},
166 {AID_ROOT, AID_SYSTEM},
167};
168
Riley Spahneaabae92014-06-30 12:39:52 -0700169/* perm_labels associcated with keystore_key SELinux class verbs. */
170const char *perm_labels[] = {
171 "test",
172 "get",
173 "insert",
174 "delete",
175 "exist",
176 "saw",
177 "reset",
178 "password",
179 "lock",
180 "unlock",
181 "zero",
182 "sign",
183 "verify",
184 "grant",
185 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100186 "clear_uid",
187 "reset_uid",
188 "sync_uid",
189 "password_uid",
Riley Spahneaabae92014-06-30 12:39:52 -0700190};
191
Kenny Root07438c82012-11-02 15:41:02 -0700192static struct user_perm {
193 uid_t uid;
194 perm_t perms;
195} user_perms[] = {
196 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
197 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
198 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
199 {AID_ROOT, static_cast<perm_t>(P_GET) },
200};
201
202static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
203 | P_VERIFY);
204
Riley Spahneaabae92014-06-30 12:39:52 -0700205static char *tctx;
206static int ks_is_selinux_enabled;
207
208static const char *get_perm_label(perm_t perm) {
209 unsigned int index = ffs(perm);
210 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
211 return perm_labels[index - 1];
212 } else {
213 ALOGE("Keystore: Failed to retrieve permission label.\n");
214 abort();
215 }
216}
217
Kenny Root655b9582013-04-04 08:37:42 -0700218/**
219 * Returns the app ID (in the Android multi-user sense) for the current
220 * UNIX UID.
221 */
222static uid_t get_app_id(uid_t uid) {
223 return uid % AID_USER;
224}
225
226/**
227 * Returns the user ID (in the Android multi-user sense) for the current
228 * UNIX UID.
229 */
230static uid_t get_user_id(uid_t uid) {
231 return uid / AID_USER;
232}
233
Riley Spahneaabae92014-06-30 12:39:52 -0700234static bool keystore_selinux_check_access(uid_t uid, perm_t perm, pid_t spid) {
235 if (!ks_is_selinux_enabled) {
236 return true;
237 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000238
Riley Spahneaabae92014-06-30 12:39:52 -0700239 char *sctx = NULL;
240 const char *selinux_class = "keystore_key";
241 const char *str_perm = get_perm_label(perm);
242
243 if (!str_perm) {
244 return false;
245 }
246
247 if (getpidcon(spid, &sctx) != 0) {
248 ALOGE("SELinux: Failed to get source pid context.\n");
249 return false;
250 }
251
252 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
253 NULL) == 0;
254 freecon(sctx);
255 return allowed;
256}
257
258static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700259 // All system users are equivalent for multi-user support.
260 if (get_app_id(uid) == AID_SYSTEM) {
261 uid = AID_SYSTEM;
262 }
263
Kenny Root07438c82012-11-02 15:41:02 -0700264 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
265 struct user_perm user = user_perms[i];
266 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700267 return (user.perms & perm) &&
268 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700269 }
270 }
271
Riley Spahneaabae92014-06-30 12:39:52 -0700272 return (DEFAULT_PERMS & perm) &&
273 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700274}
275
Kenny Root49468902013-03-19 13:41:33 -0700276/**
277 * Returns the UID that the callingUid should act as. This is here for
278 * legacy support of the WiFi and VPN systems and should be removed
279 * when WiFi can operate in its own namespace.
280 */
Kenny Root07438c82012-11-02 15:41:02 -0700281static uid_t get_keystore_euid(uid_t uid) {
282 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
283 struct user_euid user = user_euids[i];
284 if (user.uid == uid) {
285 return user.euid;
286 }
287 }
288
289 return uid;
290}
291
Kenny Root49468902013-03-19 13:41:33 -0700292/**
293 * Returns true if the callingUid is allowed to interact in the targetUid's
294 * namespace.
295 */
296static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
297 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
298 struct user_euid user = user_euids[i];
299 if (user.euid == callingUid && user.uid == targetUid) {
300 return true;
301 }
302 }
303
304 return false;
305}
306
Kenny Root007cb232014-07-30 16:59:42 -0700307/**
308 * Allow the system to perform some privileged tasks that have to do with
309 * system maintenance. This should not be used for any function that uses
310 * the keys in any way (e.g., signing).
311 */
312static bool is_self_or_system(uid_t callingUid, uid_t targetUid) {
313 return callingUid == targetUid || callingUid == AID_SYSTEM;
314}
315
Kenny Roota91203b2012-02-15 15:00:46 -0800316/* Here is the encoding of keys. This is necessary in order to allow arbitrary
317 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
318 * into two bytes. The first byte is one of [+-.] which represents the first
319 * two bits of the character. The second byte encodes the rest of the bits into
320 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
321 * that Base64 cannot be used here due to the need of prefix match on keys. */
322
Kenny Root655b9582013-04-04 08:37:42 -0700323static size_t encode_key_length(const android::String8& keyName) {
324 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
325 size_t length = keyName.length();
326 for (int i = length; i > 0; --i, ++in) {
327 if (*in < '0' || *in > '~') {
328 ++length;
329 }
330 }
331 return length;
332}
333
Kenny Root07438c82012-11-02 15:41:02 -0700334static int encode_key(char* out, const android::String8& keyName) {
335 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
336 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800337 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700338 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800339 *out = '+' + (*in >> 6);
340 *++out = '0' + (*in & 0x3F);
341 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700342 } else {
343 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800344 }
345 }
346 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800347 return length;
348}
349
Kenny Root07438c82012-11-02 15:41:02 -0700350/*
351 * Converts from the "escaped" format on disk to actual name.
352 * This will be smaller than the input string.
353 *
354 * Characters that should combine with the next at the end will be truncated.
355 */
356static size_t decode_key_length(const char* in, size_t length) {
357 size_t outLength = 0;
358
359 for (const char* end = in + length; in < end; in++) {
360 /* This combines with the next character. */
361 if (*in < '0' || *in > '~') {
362 continue;
363 }
364
365 outLength++;
366 }
367 return outLength;
368}
369
370static void decode_key(char* out, const char* in, size_t length) {
371 for (const char* end = in + length; in < end; in++) {
372 if (*in < '0' || *in > '~') {
373 /* Truncate combining characters at the end. */
374 if (in + 1 >= end) {
375 break;
376 }
377
378 *out = (*in++ - '+') << 6;
379 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800380 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700381 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800382 }
383 }
384 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800385}
386
387static size_t readFully(int fd, uint8_t* data, size_t size) {
388 size_t remaining = size;
389 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800390 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800391 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800392 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800393 }
394 data += n;
395 remaining -= n;
396 }
397 return size;
398}
399
400static size_t writeFully(int fd, uint8_t* data, size_t size) {
401 size_t remaining = size;
402 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800403 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
404 if (n < 0) {
405 ALOGW("write failed: %s", strerror(errno));
406 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800407 }
408 data += n;
409 remaining -= n;
410 }
411 return size;
412}
413
414class Entropy {
415public:
416 Entropy() : mRandom(-1) {}
417 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800418 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800419 close(mRandom);
420 }
421 }
422
423 bool open() {
424 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800425 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
426 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800427 ALOGE("open: %s: %s", randomDevice, strerror(errno));
428 return false;
429 }
430 return true;
431 }
432
Kenny Root51878182012-03-13 12:53:19 -0700433 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800434 return (readFully(mRandom, data, size) == size);
435 }
436
437private:
438 int mRandom;
439};
440
441/* Here is the file format. There are two parts in blob.value, the secret and
442 * the description. The secret is stored in ciphertext, and its original size
443 * can be found in blob.length. The description is stored after the secret in
444 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700445 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700446 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800447 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
448 * and decryptBlob(). Thus they should not be accessed from outside. */
449
Kenny Root822c3a92012-03-23 16:34:39 -0700450/* ** Note to future implementors of encryption: **
451 * Currently this is the construction:
452 * metadata || Enc(MD5(data) || data)
453 *
454 * This should be the construction used for encrypting if re-implementing:
455 *
456 * Derive independent keys for encryption and MAC:
457 * Kenc = AES_encrypt(masterKey, "Encrypt")
458 * Kmac = AES_encrypt(masterKey, "MAC")
459 *
460 * Store this:
461 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
462 * HMAC(Kmac, metadata || Enc(data))
463 */
Kenny Roota91203b2012-02-15 15:00:46 -0800464struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700465 uint8_t version;
466 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700467 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800468 uint8_t info;
469 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700470 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800471 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700472 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800473 int32_t length; // in network byte order when encrypted
474 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
475};
476
Kenny Root822c3a92012-03-23 16:34:39 -0700477typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700478 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700479 TYPE_GENERIC = 1,
480 TYPE_MASTER_KEY = 2,
481 TYPE_KEY_PAIR = 3,
482} BlobType;
483
Kenny Rootf9119d62013-04-03 09:22:15 -0700484static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700485
Kenny Roota91203b2012-02-15 15:00:46 -0800486class Blob {
487public:
Kenny Root07438c82012-11-02 15:41:02 -0700488 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
489 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800490 mBlob.length = valueLength;
491 memcpy(mBlob.value, value, valueLength);
492
493 mBlob.info = infoLength;
494 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700495
Kenny Root07438c82012-11-02 15:41:02 -0700496 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700497 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700498
Kenny Rootee8068b2013-10-07 09:49:15 -0700499 if (type == TYPE_MASTER_KEY) {
500 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
501 } else {
502 mBlob.flags = KEYSTORE_FLAG_NONE;
503 }
Kenny Roota91203b2012-02-15 15:00:46 -0800504 }
505
506 Blob(blob b) {
507 mBlob = b;
508 }
509
510 Blob() {}
511
Kenny Root51878182012-03-13 12:53:19 -0700512 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800513 return mBlob.value;
514 }
515
Kenny Root51878182012-03-13 12:53:19 -0700516 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800517 return mBlob.length;
518 }
519
Kenny Root51878182012-03-13 12:53:19 -0700520 const uint8_t* getInfo() const {
521 return mBlob.value + mBlob.length;
522 }
523
524 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800525 return mBlob.info;
526 }
527
Kenny Root822c3a92012-03-23 16:34:39 -0700528 uint8_t getVersion() const {
529 return mBlob.version;
530 }
531
Kenny Rootf9119d62013-04-03 09:22:15 -0700532 bool isEncrypted() const {
533 if (mBlob.version < 2) {
534 return true;
535 }
536
537 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
538 }
539
540 void setEncrypted(bool encrypted) {
541 if (encrypted) {
542 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
543 } else {
544 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
545 }
546 }
547
Kenny Root17208e02013-09-04 13:56:03 -0700548 bool isFallback() const {
549 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
550 }
551
552 void setFallback(bool fallback) {
553 if (fallback) {
554 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
555 } else {
556 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
557 }
558 }
559
Kenny Root822c3a92012-03-23 16:34:39 -0700560 void setVersion(uint8_t version) {
561 mBlob.version = version;
562 }
563
564 BlobType getType() const {
565 return BlobType(mBlob.type);
566 }
567
568 void setType(BlobType type) {
569 mBlob.type = uint8_t(type);
570 }
571
Kenny Rootf9119d62013-04-03 09:22:15 -0700572 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
573 ALOGV("writing blob %s", filename);
574 if (isEncrypted()) {
575 if (state != STATE_NO_ERROR) {
576 ALOGD("couldn't insert encrypted blob while not unlocked");
577 return LOCKED;
578 }
579
580 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
581 ALOGW("Could not read random data for: %s", filename);
582 return SYSTEM_ERROR;
583 }
Kenny Roota91203b2012-02-15 15:00:46 -0800584 }
585
586 // data includes the value and the value's length
587 size_t dataLength = mBlob.length + sizeof(mBlob.length);
588 // pad data to the AES_BLOCK_SIZE
589 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
590 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
591 // encrypted data includes the digest value
592 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
593 // move info after space for padding
594 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
595 // zero padding area
596 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
597
598 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800599
Kenny Rootf9119d62013-04-03 09:22:15 -0700600 if (isEncrypted()) {
601 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800602
Kenny Rootf9119d62013-04-03 09:22:15 -0700603 uint8_t vector[AES_BLOCK_SIZE];
604 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
605 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
606 aes_key, vector, AES_ENCRYPT);
607 }
608
Kenny Roota91203b2012-02-15 15:00:46 -0800609 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
610 size_t fileLength = encryptedLength + headerLength + mBlob.info;
611
612 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800613 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
614 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
615 if (out < 0) {
616 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800617 return SYSTEM_ERROR;
618 }
619 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
620 if (close(out) != 0) {
621 return SYSTEM_ERROR;
622 }
623 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800624 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800625 unlink(tmpFileName);
626 return SYSTEM_ERROR;
627 }
Kenny Root150ca932012-11-14 14:29:02 -0800628 if (rename(tmpFileName, filename) == -1) {
629 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
630 return SYSTEM_ERROR;
631 }
632 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800633 }
634
Kenny Rootf9119d62013-04-03 09:22:15 -0700635 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
636 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800637 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
638 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800639 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
640 }
641 // fileLength may be less than sizeof(mBlob) since the in
642 // memory version has extra padding to tolerate rounding up to
643 // the AES_BLOCK_SIZE
644 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
645 if (close(in) != 0) {
646 return SYSTEM_ERROR;
647 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700648
649 if (isEncrypted() && (state != STATE_NO_ERROR)) {
650 return LOCKED;
651 }
652
Kenny Roota91203b2012-02-15 15:00:46 -0800653 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
654 if (fileLength < headerLength) {
655 return VALUE_CORRUPTED;
656 }
657
658 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700659 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800660 return VALUE_CORRUPTED;
661 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700662
663 ssize_t digestedLength;
664 if (isEncrypted()) {
665 if (encryptedLength % AES_BLOCK_SIZE != 0) {
666 return VALUE_CORRUPTED;
667 }
668
669 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
670 mBlob.vector, AES_DECRYPT);
671 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
672 uint8_t computedDigest[MD5_DIGEST_LENGTH];
673 MD5(mBlob.digested, digestedLength, computedDigest);
674 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
675 return VALUE_CORRUPTED;
676 }
677 } else {
678 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800679 }
680
681 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
682 mBlob.length = ntohl(mBlob.length);
683 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
684 return VALUE_CORRUPTED;
685 }
686 if (mBlob.info != 0) {
687 // move info from after padding to after data
688 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
689 }
Kenny Root07438c82012-11-02 15:41:02 -0700690 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800691 }
692
693private:
694 struct blob mBlob;
695};
696
Kenny Root655b9582013-04-04 08:37:42 -0700697class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800698public:
Kenny Root655b9582013-04-04 08:37:42 -0700699 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
700 asprintf(&mUserDir, "user_%u", mUserId);
701 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
702 }
703
704 ~UserState() {
705 free(mUserDir);
706 free(mMasterKeyFile);
707 }
708
709 bool initialize() {
710 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
711 ALOGE("Could not create directory '%s'", mUserDir);
712 return false;
713 }
714
715 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800716 setState(STATE_LOCKED);
717 } else {
718 setState(STATE_UNINITIALIZED);
719 }
Kenny Root70e3a862012-02-15 17:20:23 -0800720
Kenny Root655b9582013-04-04 08:37:42 -0700721 return true;
722 }
723
724 uid_t getUserId() const {
725 return mUserId;
726 }
727
728 const char* getUserDirName() const {
729 return mUserDir;
730 }
731
732 const char* getMasterKeyFileName() const {
733 return mMasterKeyFile;
734 }
735
736 void setState(State state) {
737 mState = state;
738 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
739 mRetry = MAX_RETRY;
740 }
Kenny Roota91203b2012-02-15 15:00:46 -0800741 }
742
Kenny Root51878182012-03-13 12:53:19 -0700743 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800744 return mState;
745 }
746
Kenny Root51878182012-03-13 12:53:19 -0700747 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800748 return mRetry;
749 }
750
Kenny Root655b9582013-04-04 08:37:42 -0700751 void zeroizeMasterKeysInMemory() {
752 memset(mMasterKey, 0, sizeof(mMasterKey));
753 memset(mSalt, 0, sizeof(mSalt));
754 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
755 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800756 }
757
Kenny Root655b9582013-04-04 08:37:42 -0700758 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
759 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800760 return SYSTEM_ERROR;
761 }
Kenny Root655b9582013-04-04 08:37:42 -0700762 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800763 if (response != NO_ERROR) {
764 return response;
765 }
766 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700767 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800768 }
769
Robin Lee4e865752014-08-19 17:37:55 +0100770 ResponseCode copyMasterKey(UserState* src) {
771 if (mState != STATE_UNINITIALIZED) {
772 return ::SYSTEM_ERROR;
773 }
774 if (src->getState() != STATE_NO_ERROR) {
775 return ::SYSTEM_ERROR;
776 }
777 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
778 setupMasterKeys();
779 return ::NO_ERROR;
780 }
781
Kenny Root655b9582013-04-04 08:37:42 -0700782 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800783 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
784 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
785 AES_KEY passwordAesKey;
786 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700787 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700788 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800789 }
790
Kenny Root655b9582013-04-04 08:37:42 -0700791 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
792 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800793 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800794 return SYSTEM_ERROR;
795 }
796
797 // we read the raw blob to just to get the salt to generate
798 // the AES key, then we create the Blob to use with decryptBlob
799 blob rawBlob;
800 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
801 if (close(in) != 0) {
802 return SYSTEM_ERROR;
803 }
804 // find salt at EOF if present, otherwise we have an old file
805 uint8_t* salt;
806 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
807 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
808 } else {
809 salt = NULL;
810 }
811 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
812 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
813 AES_KEY passwordAesKey;
814 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
815 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700816 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
817 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800818 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700819 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800820 }
821 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
822 // if salt was missing, generate one and write a new master key file with the salt.
823 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700824 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800825 return SYSTEM_ERROR;
826 }
Kenny Root655b9582013-04-04 08:37:42 -0700827 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800828 }
829 if (response == NO_ERROR) {
830 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
831 setupMasterKeys();
832 }
833 return response;
834 }
835 if (mRetry <= 0) {
836 reset();
837 return UNINITIALIZED;
838 }
839 --mRetry;
840 switch (mRetry) {
841 case 0: return WRONG_PASSWORD_0;
842 case 1: return WRONG_PASSWORD_1;
843 case 2: return WRONG_PASSWORD_2;
844 case 3: return WRONG_PASSWORD_3;
845 default: return WRONG_PASSWORD_3;
846 }
847 }
848
Kenny Root655b9582013-04-04 08:37:42 -0700849 AES_KEY* getEncryptionKey() {
850 return &mMasterKeyEncryption;
851 }
852
853 AES_KEY* getDecryptionKey() {
854 return &mMasterKeyDecryption;
855 }
856
Kenny Roota91203b2012-02-15 15:00:46 -0800857 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700858 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800859 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700860 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800861 return false;
862 }
Kenny Root655b9582013-04-04 08:37:42 -0700863
864 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800865 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700866 // We only care about files.
867 if (file->d_type != DT_REG) {
868 continue;
869 }
870
871 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700872 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700873 continue;
874 }
875
876 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800877 }
878 closedir(dir);
879 return true;
880 }
881
Kenny Root655b9582013-04-04 08:37:42 -0700882private:
883 static const int MASTER_KEY_SIZE_BYTES = 16;
884 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
885
886 static const int MAX_RETRY = 4;
887 static const size_t SALT_SIZE = 16;
888
889 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
890 uint8_t* salt) {
891 size_t saltSize;
892 if (salt != NULL) {
893 saltSize = SALT_SIZE;
894 } else {
895 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
896 salt = (uint8_t*) "keystore";
897 // sizeof = 9, not strlen = 8
898 saltSize = sizeof("keystore");
899 }
900
901 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
902 saltSize, 8192, keySize, key);
903 }
904
905 bool generateSalt(Entropy* entropy) {
906 return entropy->generate_random_data(mSalt, sizeof(mSalt));
907 }
908
909 bool generateMasterKey(Entropy* entropy) {
910 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
911 return false;
912 }
913 if (!generateSalt(entropy)) {
914 return false;
915 }
916 return true;
917 }
918
919 void setupMasterKeys() {
920 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
921 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
922 setState(STATE_NO_ERROR);
923 }
924
925 uid_t mUserId;
926
927 char* mUserDir;
928 char* mMasterKeyFile;
929
930 State mState;
931 int8_t mRetry;
932
933 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
934 uint8_t mSalt[SALT_SIZE];
935
936 AES_KEY mMasterKeyEncryption;
937 AES_KEY mMasterKeyDecryption;
938};
939
940typedef struct {
941 uint32_t uid;
942 const uint8_t* filename;
943} grant_t;
944
945class KeyStore {
946public:
947 KeyStore(Entropy* entropy, keymaster_device_t* device)
948 : mEntropy(entropy)
949 , mDevice(device)
950 {
951 memset(&mMetaData, '\0', sizeof(mMetaData));
952 }
953
954 ~KeyStore() {
955 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
956 it != mGrants.end(); it++) {
957 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700958 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800959 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700960
961 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
962 it != mMasterKeys.end(); it++) {
963 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700964 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800965 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700966 }
967
968 keymaster_device_t* getDevice() const {
969 return mDevice;
970 }
971
972 ResponseCode initialize() {
973 readMetaData();
974 if (upgradeKeystore()) {
975 writeMetaData();
976 }
977
978 return ::NO_ERROR;
979 }
980
981 State getState(uid_t uid) {
982 return getUserState(uid)->getState();
983 }
984
985 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
986 UserState* userState = getUserState(uid);
987 return userState->initialize(pw, mEntropy);
988 }
989
Robin Lee4e865752014-08-19 17:37:55 +0100990 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
991 UserState *userState = getUserState(uid);
992 UserState *initState = getUserState(src);
993 return userState->copyMasterKey(initState);
994 }
995
Kenny Root655b9582013-04-04 08:37:42 -0700996 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +0100997 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -0700998 return userState->writeMasterKey(pw, mEntropy);
999 }
1000
Robin Lee4e865752014-08-19 17:37:55 +01001001
Kenny Root655b9582013-04-04 08:37:42 -07001002 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001003 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001004 return userState->readMasterKey(pw, mEntropy);
1005 }
1006
1007 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001008 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001009 encode_key(encoded, keyName);
1010 return android::String8(encoded);
1011 }
1012
1013 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001014 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001015 encode_key(encoded, keyName);
1016 return android::String8::format("%u_%s", uid, encoded);
1017 }
1018
1019 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001020 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001021 encode_key(encoded, keyName);
1022 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1023 encoded);
1024 }
1025
1026 bool reset(uid_t uid) {
1027 UserState* userState = getUserState(uid);
1028 userState->zeroizeMasterKeysInMemory();
1029 userState->setState(STATE_UNINITIALIZED);
1030 return userState->reset();
1031 }
1032
1033 bool isEmpty(uid_t uid) const {
1034 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001035 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001036 return true;
1037 }
1038
1039 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001040 if (!dir) {
1041 return true;
1042 }
Kenny Root31e27462014-09-10 11:28:03 -07001043
Kenny Roota91203b2012-02-15 15:00:46 -08001044 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001045 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001046 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001047 // We only care about files.
1048 if (file->d_type != DT_REG) {
1049 continue;
1050 }
1051
1052 // Skip anything that starts with a "."
1053 if (file->d_name[0] == '.') {
1054 continue;
1055 }
1056
Kenny Root31e27462014-09-10 11:28:03 -07001057 result = false;
1058 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001059 }
1060 closedir(dir);
1061 return result;
1062 }
1063
Kenny Root655b9582013-04-04 08:37:42 -07001064 void lock(uid_t uid) {
1065 UserState* userState = getUserState(uid);
1066 userState->zeroizeMasterKeysInMemory();
1067 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001068 }
1069
Kenny Root655b9582013-04-04 08:37:42 -07001070 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1071 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001072 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1073 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001074 if (rc != NO_ERROR) {
1075 return rc;
1076 }
1077
1078 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001079 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001080 /* If we upgrade the key, we need to write it to disk again. Then
1081 * it must be read it again since the blob is encrypted each time
1082 * it's written.
1083 */
Kenny Root655b9582013-04-04 08:37:42 -07001084 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1085 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001086 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1087 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001088 return rc;
1089 }
1090 }
Kenny Root822c3a92012-03-23 16:34:39 -07001091 }
1092
Kenny Root17208e02013-09-04 13:56:03 -07001093 /*
1094 * This will upgrade software-backed keys to hardware-backed keys when
1095 * the HAL for the device supports the newer key types.
1096 */
1097 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1098 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1099 && keyBlob->isFallback()) {
1100 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1101 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1102
1103 // The HAL allowed the import, reget the key to have the "fresh"
1104 // version.
1105 if (imported == NO_ERROR) {
1106 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1107 }
1108 }
1109
Kenny Rootd53bc922013-03-21 14:10:15 -07001110 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001111 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1112 return KEY_NOT_FOUND;
1113 }
1114
1115 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001116 }
1117
Kenny Root655b9582013-04-04 08:37:42 -07001118 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1119 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001120 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1121 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001122 }
1123
Kenny Root07438c82012-11-02 15:41:02 -07001124 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001125 const grant_t* existing = getGrant(filename, granteeUid);
1126 if (existing == NULL) {
1127 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001128 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001129 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001130 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001131 }
1132 }
1133
Kenny Root07438c82012-11-02 15:41:02 -07001134 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001135 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1136 it != mGrants.end(); it++) {
1137 grant_t* grant = *it;
1138 if (grant->uid == granteeUid
1139 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1140 mGrants.erase(it);
1141 return true;
1142 }
Kenny Root70e3a862012-02-15 17:20:23 -08001143 }
Kenny Root70e3a862012-02-15 17:20:23 -08001144 return false;
1145 }
1146
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001147 bool hasGrant(const char* filename, const uid_t uid) const {
1148 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001149 }
1150
Kenny Rootf9119d62013-04-03 09:22:15 -07001151 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1152 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001153 uint8_t* data;
1154 size_t dataLength;
1155 int rc;
1156
1157 if (mDevice->import_keypair == NULL) {
1158 ALOGE("Keymaster doesn't support import!");
1159 return SYSTEM_ERROR;
1160 }
1161
Kenny Root17208e02013-09-04 13:56:03 -07001162 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001163 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001164 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001165 /*
1166 * Maybe the device doesn't support this type of key. Try to use the
1167 * software fallback keymaster implementation. This is a little bit
1168 * lazier than checking the PKCS#8 key type, but the software
1169 * implementation will do that anyway.
1170 */
1171 rc = openssl_import_keypair(mDevice, key, keyLen, &data, &dataLength);
1172 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001173
1174 if (rc) {
1175 ALOGE("Error while importing keypair: %d", rc);
1176 return SYSTEM_ERROR;
1177 }
Kenny Root822c3a92012-03-23 16:34:39 -07001178 }
1179
1180 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1181 free(data);
1182
Kenny Rootf9119d62013-04-03 09:22:15 -07001183 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001184 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001185
Kenny Root655b9582013-04-04 08:37:42 -07001186 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001187 }
1188
Kenny Root1b0e3932013-09-05 13:06:32 -07001189 bool isHardwareBacked(const android::String16& keyType) const {
1190 if (mDevice == NULL) {
1191 ALOGW("can't get keymaster device");
1192 return false;
1193 }
1194
1195 if (sRSAKeyType == keyType) {
1196 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1197 } else {
1198 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1199 && (mDevice->common.module->module_api_version
1200 >= KEYMASTER_MODULE_API_VERSION_0_2);
1201 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001202 }
1203
Kenny Root655b9582013-04-04 08:37:42 -07001204 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1205 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001206 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001207
1208 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1209 if (responseCode == NO_ERROR) {
1210 return responseCode;
1211 }
1212
1213 // If this is one of the legacy UID->UID mappings, use it.
1214 uid_t euid = get_keystore_euid(uid);
1215 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001216 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001217 responseCode = get(filepath8.string(), keyBlob, type, uid);
1218 if (responseCode == NO_ERROR) {
1219 return responseCode;
1220 }
1221 }
1222
1223 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001224 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001225 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001226 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001227 if (end[0] != '_' || end[1] == 0) {
1228 return KEY_NOT_FOUND;
1229 }
Kenny Root86b16e82013-09-09 11:15:54 -07001230 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1231 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001232 if (!hasGrant(filepath8.string(), uid)) {
1233 return responseCode;
1234 }
1235
1236 // It is a granted key. Try to load it.
1237 return get(filepath8.string(), keyBlob, type, uid);
1238 }
1239
1240 /**
1241 * Returns any existing UserState or creates it if it doesn't exist.
1242 */
1243 UserState* getUserState(uid_t uid) {
1244 uid_t userId = get_user_id(uid);
1245
1246 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1247 it != mMasterKeys.end(); it++) {
1248 UserState* state = *it;
1249 if (state->getUserId() == userId) {
1250 return state;
1251 }
1252 }
1253
1254 UserState* userState = new UserState(userId);
1255 if (!userState->initialize()) {
1256 /* There's not much we can do if initialization fails. Trying to
1257 * unlock the keystore for that user will fail as well, so any
1258 * subsequent request for this user will just return SYSTEM_ERROR.
1259 */
1260 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1261 }
1262 mMasterKeys.add(userState);
1263 return userState;
1264 }
1265
1266 /**
1267 * Returns NULL if the UserState doesn't already exist.
1268 */
1269 const UserState* getUserState(uid_t uid) const {
1270 uid_t userId = get_user_id(uid);
1271
1272 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1273 it != mMasterKeys.end(); it++) {
1274 UserState* state = *it;
1275 if (state->getUserId() == userId) {
1276 return state;
1277 }
1278 }
1279
1280 return NULL;
1281 }
1282
Kenny Roota91203b2012-02-15 15:00:46 -08001283private:
Kenny Root655b9582013-04-04 08:37:42 -07001284 static const char* sOldMasterKey;
1285 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001286 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001287 Entropy* mEntropy;
1288
Kenny Root70e3a862012-02-15 17:20:23 -08001289 keymaster_device_t* mDevice;
1290
Kenny Root655b9582013-04-04 08:37:42 -07001291 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001292
Kenny Root655b9582013-04-04 08:37:42 -07001293 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001294
Kenny Root655b9582013-04-04 08:37:42 -07001295 typedef struct {
1296 uint32_t version;
1297 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001298
Kenny Root655b9582013-04-04 08:37:42 -07001299 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001300
Kenny Root655b9582013-04-04 08:37:42 -07001301 const grant_t* getGrant(const char* filename, uid_t uid) const {
1302 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1303 it != mGrants.end(); it++) {
1304 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001305 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001306 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001307 return grant;
1308 }
1309 }
Kenny Root70e3a862012-02-15 17:20:23 -08001310 return NULL;
1311 }
1312
Kenny Root822c3a92012-03-23 16:34:39 -07001313 /**
1314 * Upgrade code. This will upgrade the key from the current version
1315 * to whatever is newest.
1316 */
Kenny Root655b9582013-04-04 08:37:42 -07001317 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1318 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001319 bool updated = false;
1320 uint8_t version = oldVersion;
1321
1322 /* From V0 -> V1: All old types were unknown */
1323 if (version == 0) {
1324 ALOGV("upgrading to version 1 and setting type %d", type);
1325
1326 blob->setType(type);
1327 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001328 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001329 }
1330 version = 1;
1331 updated = true;
1332 }
1333
Kenny Rootf9119d62013-04-03 09:22:15 -07001334 /* From V1 -> V2: All old keys were encrypted */
1335 if (version == 1) {
1336 ALOGV("upgrading to version 2");
1337
1338 blob->setEncrypted(true);
1339 version = 2;
1340 updated = true;
1341 }
1342
Kenny Root822c3a92012-03-23 16:34:39 -07001343 /*
1344 * If we've updated, set the key blob to the right version
1345 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001346 */
Kenny Root822c3a92012-03-23 16:34:39 -07001347 if (updated) {
1348 ALOGV("updated and writing file %s", filename);
1349 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001350 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001351
1352 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001353 }
1354
1355 /**
1356 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1357 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1358 * Then it overwrites the original blob with the new blob
1359 * format that is returned from the keymaster.
1360 */
Kenny Root655b9582013-04-04 08:37:42 -07001361 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001362 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1363 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1364 if (b.get() == NULL) {
1365 ALOGE("Problem instantiating BIO");
1366 return SYSTEM_ERROR;
1367 }
1368
1369 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1370 if (pkey.get() == NULL) {
1371 ALOGE("Couldn't read old PEM file");
1372 return SYSTEM_ERROR;
1373 }
1374
1375 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1376 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1377 if (len < 0) {
1378 ALOGE("Couldn't measure PKCS#8 length");
1379 return SYSTEM_ERROR;
1380 }
1381
Kenny Root70c98892013-02-07 09:10:36 -08001382 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1383 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001384 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1385 ALOGE("Couldn't convert to PKCS#8");
1386 return SYSTEM_ERROR;
1387 }
1388
Kenny Rootf9119d62013-04-03 09:22:15 -07001389 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1390 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001391 if (rc != NO_ERROR) {
1392 return rc;
1393 }
1394
Kenny Root655b9582013-04-04 08:37:42 -07001395 return get(filename, blob, TYPE_KEY_PAIR, uid);
1396 }
1397
1398 void readMetaData() {
1399 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1400 if (in < 0) {
1401 return;
1402 }
1403 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1404 if (fileLength != sizeof(mMetaData)) {
1405 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1406 sizeof(mMetaData));
1407 }
1408 close(in);
1409 }
1410
1411 void writeMetaData() {
1412 const char* tmpFileName = ".metadata.tmp";
1413 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1414 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1415 if (out < 0) {
1416 ALOGE("couldn't write metadata file: %s", strerror(errno));
1417 return;
1418 }
1419 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1420 if (fileLength != sizeof(mMetaData)) {
1421 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1422 sizeof(mMetaData));
1423 }
1424 close(out);
1425 rename(tmpFileName, sMetaDataFile);
1426 }
1427
1428 bool upgradeKeystore() {
1429 bool upgraded = false;
1430
1431 if (mMetaData.version == 0) {
1432 UserState* userState = getUserState(0);
1433
1434 // Initialize first so the directory is made.
1435 userState->initialize();
1436
1437 // Migrate the old .masterkey file to user 0.
1438 if (access(sOldMasterKey, R_OK) == 0) {
1439 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1440 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1441 return false;
1442 }
1443 }
1444
1445 // Initialize again in case we had a key.
1446 userState->initialize();
1447
1448 // Try to migrate existing keys.
1449 DIR* dir = opendir(".");
1450 if (!dir) {
1451 // Give up now; maybe we can upgrade later.
1452 ALOGE("couldn't open keystore's directory; something is wrong");
1453 return false;
1454 }
1455
1456 struct dirent* file;
1457 while ((file = readdir(dir)) != NULL) {
1458 // We only care about files.
1459 if (file->d_type != DT_REG) {
1460 continue;
1461 }
1462
1463 // Skip anything that starts with a "."
1464 if (file->d_name[0] == '.') {
1465 continue;
1466 }
1467
1468 // Find the current file's user.
1469 char* end;
1470 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1471 if (end[0] != '_' || end[1] == 0) {
1472 continue;
1473 }
1474 UserState* otherUser = getUserState(thisUid);
1475 if (otherUser->getUserId() != 0) {
1476 unlinkat(dirfd(dir), file->d_name, 0);
1477 }
1478
1479 // Rename the file into user directory.
1480 DIR* otherdir = opendir(otherUser->getUserDirName());
1481 if (otherdir == NULL) {
1482 ALOGW("couldn't open user directory for rename");
1483 continue;
1484 }
1485 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1486 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1487 }
1488 closedir(otherdir);
1489 }
1490 closedir(dir);
1491
1492 mMetaData.version = 1;
1493 upgraded = true;
1494 }
1495
1496 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001497 }
Kenny Roota91203b2012-02-15 15:00:46 -08001498};
1499
Kenny Root655b9582013-04-04 08:37:42 -07001500const char* KeyStore::sOldMasterKey = ".masterkey";
1501const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001502
Kenny Root1b0e3932013-09-05 13:06:32 -07001503const android::String16 KeyStore::sRSAKeyType("RSA");
1504
Kenny Root07438c82012-11-02 15:41:02 -07001505namespace android {
1506class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1507public:
1508 KeyStoreProxy(KeyStore* keyStore)
1509 : mKeyStore(keyStore)
1510 {
Kenny Roota91203b2012-02-15 15:00:46 -08001511 }
Kenny Roota91203b2012-02-15 15:00:46 -08001512
Kenny Root07438c82012-11-02 15:41:02 -07001513 void binderDied(const wp<IBinder>&) {
1514 ALOGE("binder death detected");
Kenny Root822c3a92012-03-23 16:34:39 -07001515 }
Kenny Roota91203b2012-02-15 15:00:46 -08001516
Kenny Root07438c82012-11-02 15:41:02 -07001517 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001518 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001519 pid_t spid = IPCThreadState::self()->getCallingPid();
1520 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001521 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001522 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001523 }
Kenny Roota91203b2012-02-15 15:00:46 -08001524
Kenny Root655b9582013-04-04 08:37:42 -07001525 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001526 }
1527
Kenny Root07438c82012-11-02 15:41:02 -07001528 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001529 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001530 pid_t spid = IPCThreadState::self()->getCallingPid();
1531 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001532 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001533 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001534 }
Kenny Root07438c82012-11-02 15:41:02 -07001535
Kenny Root07438c82012-11-02 15:41:02 -07001536 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001537 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001538
Kenny Root655b9582013-04-04 08:37:42 -07001539 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001540 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001541 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001542 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001543 *item = NULL;
1544 *itemLength = 0;
1545 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001546 }
Kenny Roota91203b2012-02-15 15:00:46 -08001547
Kenny Root07438c82012-11-02 15:41:02 -07001548 *item = (uint8_t*) malloc(keyBlob.getLength());
1549 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1550 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001551
Kenny Root07438c82012-11-02 15:41:02 -07001552 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001553 }
1554
Kenny Rootf9119d62013-04-03 09:22:15 -07001555 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1556 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001557 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001558 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001559 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001560 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001561 return ::PERMISSION_DENIED;
1562 }
Kenny Root07438c82012-11-02 15:41:02 -07001563
Kenny Rootf9119d62013-04-03 09:22:15 -07001564 State state = mKeyStore->getState(callingUid);
1565 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1566 ALOGD("calling get in state: %d", state);
1567 return state;
1568 }
1569
Kenny Root49468902013-03-19 13:41:33 -07001570 if (targetUid == -1) {
1571 targetUid = callingUid;
1572 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001573 return ::PERMISSION_DENIED;
1574 }
1575
Kenny Root07438c82012-11-02 15:41:02 -07001576 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001577 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001578
1579 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001580 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1581
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001582 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001583 }
1584
Kenny Root49468902013-03-19 13:41:33 -07001585 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001586 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001587 pid_t spid = IPCThreadState::self()->getCallingPid();
1588 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001589 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001590 return ::PERMISSION_DENIED;
1591 }
Kenny Root70e3a862012-02-15 17:20:23 -08001592
Kenny Root49468902013-03-19 13:41:33 -07001593 if (targetUid == -1) {
1594 targetUid = callingUid;
1595 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001596 return ::PERMISSION_DENIED;
1597 }
1598
Kenny Root07438c82012-11-02 15:41:02 -07001599 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001600 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001601
1602 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07001603 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, TYPE_GENERIC,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001604 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07001605 if (responseCode != ::NO_ERROR) {
1606 return responseCode;
1607 }
1608 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001609 }
1610
Kenny Root49468902013-03-19 13:41:33 -07001611 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001612 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001613 pid_t spid = IPCThreadState::self()->getCallingPid();
1614 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001615 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001616 return ::PERMISSION_DENIED;
1617 }
Kenny Root70e3a862012-02-15 17:20:23 -08001618
Kenny Root49468902013-03-19 13:41:33 -07001619 if (targetUid == -1) {
1620 targetUid = callingUid;
1621 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001622 return ::PERMISSION_DENIED;
1623 }
1624
Kenny Root07438c82012-11-02 15:41:02 -07001625 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001626 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001627
Kenny Root655b9582013-04-04 08:37:42 -07001628 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001629 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1630 }
1631 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001632 }
1633
Kenny Root49468902013-03-19 13:41:33 -07001634 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001635 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001636 pid_t spid = IPCThreadState::self()->getCallingPid();
1637 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001638 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001639 return ::PERMISSION_DENIED;
1640 }
Kenny Root70e3a862012-02-15 17:20:23 -08001641
Kenny Root49468902013-03-19 13:41:33 -07001642 if (targetUid == -1) {
1643 targetUid = callingUid;
1644 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001645 return ::PERMISSION_DENIED;
1646 }
1647
Kenny Root655b9582013-04-04 08:37:42 -07001648 UserState* userState = mKeyStore->getUserState(targetUid);
1649 DIR* dir = opendir(userState->getUserDirName());
Kenny Root07438c82012-11-02 15:41:02 -07001650 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07001651 ALOGW("can't open directory for user: %s", strerror(errno));
Kenny Root07438c82012-11-02 15:41:02 -07001652 return ::SYSTEM_ERROR;
1653 }
Kenny Root70e3a862012-02-15 17:20:23 -08001654
Kenny Root07438c82012-11-02 15:41:02 -07001655 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001656 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
1657 size_t n = filename.length();
Kenny Root70e3a862012-02-15 17:20:23 -08001658
Kenny Root07438c82012-11-02 15:41:02 -07001659 struct dirent* file;
1660 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001661 // We only care about files.
1662 if (file->d_type != DT_REG) {
1663 continue;
1664 }
1665
1666 // Skip anything that starts with a "."
1667 if (file->d_name[0] == '.') {
1668 continue;
1669 }
1670
1671 if (!strncmp(filename.string(), file->d_name, n)) {
Kenny Root07438c82012-11-02 15:41:02 -07001672 const char* p = &file->d_name[n];
1673 size_t plen = strlen(p);
Kenny Root70e3a862012-02-15 17:20:23 -08001674
Kenny Root07438c82012-11-02 15:41:02 -07001675 size_t extra = decode_key_length(p, plen);
1676 char *match = (char*) malloc(extra + 1);
1677 if (match != NULL) {
1678 decode_key(match, p, plen);
1679 matches->push(String16(match, extra));
1680 free(match);
1681 } else {
1682 ALOGW("could not allocate match of size %zd", extra);
1683 }
Kenny Root9a53d3e2012-08-14 10:47:54 -07001684 }
1685 }
Kenny Root07438c82012-11-02 15:41:02 -07001686 closedir(dir);
1687
1688 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001689 }
1690
Kenny Root07438c82012-11-02 15:41:02 -07001691 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001692 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001693 pid_t spid = IPCThreadState::self()->getCallingPid();
1694 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001695 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001696 return ::PERMISSION_DENIED;
1697 }
1698
Kenny Root655b9582013-04-04 08:37:42 -07001699 ResponseCode rc = mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001700
1701 const keymaster_device_t* device = mKeyStore->getDevice();
1702 if (device == NULL) {
1703 ALOGE("No keymaster device!");
1704 return ::SYSTEM_ERROR;
1705 }
1706
1707 if (device->delete_all == NULL) {
1708 ALOGV("keymaster device doesn't implement delete_all");
1709 return rc;
1710 }
1711
1712 if (device->delete_all(device)) {
1713 ALOGE("Problem calling keymaster's delete_all");
1714 return ::SYSTEM_ERROR;
1715 }
1716
Kenny Root9a53d3e2012-08-14 10:47:54 -07001717 return rc;
Kenny Root70e3a862012-02-15 17:20:23 -08001718 }
1719
Kenny Root07438c82012-11-02 15:41:02 -07001720 /*
1721 * Here is the history. To improve the security, the parameters to generate the
1722 * master key has been changed. To make a seamless transition, we update the
1723 * file using the same password when the user unlock it for the first time. If
1724 * any thing goes wrong during the transition, the new file will not overwrite
1725 * the old one. This avoids permanent damages of the existing data.
1726 */
1727 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001728 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001729 pid_t spid = IPCThreadState::self()->getCallingPid();
1730 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001731 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001732 return ::PERMISSION_DENIED;
1733 }
Kenny Root70e3a862012-02-15 17:20:23 -08001734
Kenny Root07438c82012-11-02 15:41:02 -07001735 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001736
Kenny Root655b9582013-04-04 08:37:42 -07001737 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001738 case ::STATE_UNINITIALIZED: {
1739 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001740 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001741 }
1742 case ::STATE_NO_ERROR: {
1743 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001744 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001745 }
1746 case ::STATE_LOCKED: {
1747 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001748 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001749 }
1750 }
1751 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001752 }
1753
Kenny Root07438c82012-11-02 15:41:02 -07001754 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001755 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001756 pid_t spid = IPCThreadState::self()->getCallingPid();
1757 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001758 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001759 return ::PERMISSION_DENIED;
1760 }
Kenny Root70e3a862012-02-15 17:20:23 -08001761
Kenny Root655b9582013-04-04 08:37:42 -07001762 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001763 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001764 ALOGD("calling lock in state: %d", state);
1765 return state;
1766 }
1767
Kenny Root655b9582013-04-04 08:37:42 -07001768 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001769 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001770 }
1771
Kenny Root07438c82012-11-02 15:41:02 -07001772 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001773 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001774 pid_t spid = IPCThreadState::self()->getCallingPid();
1775 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001776 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001777 return ::PERMISSION_DENIED;
1778 }
1779
Kenny Root655b9582013-04-04 08:37:42 -07001780 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001781 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001782 ALOGD("calling unlock when not locked");
1783 return state;
1784 }
1785
1786 const String8 password8(pw);
1787 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001788 }
1789
Kenny Root07438c82012-11-02 15:41:02 -07001790 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001791 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001792 pid_t spid = IPCThreadState::self()->getCallingPid();
1793 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001794 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001795 return -1;
1796 }
Kenny Root70e3a862012-02-15 17:20:23 -08001797
Kenny Root655b9582013-04-04 08:37:42 -07001798 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001799 }
1800
Kenny Root96427ba2013-08-16 14:02:41 -07001801 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1802 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001803 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001804 pid_t spid = IPCThreadState::self()->getCallingPid();
1805 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001806 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001807 return ::PERMISSION_DENIED;
1808 }
Kenny Root70e3a862012-02-15 17:20:23 -08001809
Kenny Root49468902013-03-19 13:41:33 -07001810 if (targetUid == -1) {
1811 targetUid = callingUid;
1812 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001813 return ::PERMISSION_DENIED;
1814 }
1815
Kenny Root655b9582013-04-04 08:37:42 -07001816 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001817 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1818 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001819 return state;
1820 }
Kenny Root70e3a862012-02-15 17:20:23 -08001821
Kenny Root07438c82012-11-02 15:41:02 -07001822 uint8_t* data;
1823 size_t dataLength;
1824 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001825 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001826
1827 const keymaster_device_t* device = mKeyStore->getDevice();
1828 if (device == NULL) {
1829 return ::SYSTEM_ERROR;
1830 }
1831
1832 if (device->generate_keypair == NULL) {
1833 return ::SYSTEM_ERROR;
1834 }
1835
Kenny Root17208e02013-09-04 13:56:03 -07001836 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001837 keymaster_dsa_keygen_params_t dsa_params;
1838 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001839
Kenny Root96427ba2013-08-16 14:02:41 -07001840 if (keySize == -1) {
1841 keySize = DSA_DEFAULT_KEY_SIZE;
1842 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1843 || keySize > DSA_MAX_KEY_SIZE) {
1844 ALOGI("invalid key size %d", keySize);
1845 return ::SYSTEM_ERROR;
1846 }
1847 dsa_params.key_size = keySize;
1848
1849 if (args->size() == 3) {
1850 sp<KeystoreArg> gArg = args->itemAt(0);
1851 sp<KeystoreArg> pArg = args->itemAt(1);
1852 sp<KeystoreArg> qArg = args->itemAt(2);
1853
1854 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1855 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1856 dsa_params.generator_len = gArg->size();
1857
1858 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1859 dsa_params.prime_p_len = pArg->size();
1860
1861 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1862 dsa_params.prime_q_len = qArg->size();
1863 } else {
1864 ALOGI("not all DSA parameters were read");
1865 return ::SYSTEM_ERROR;
1866 }
1867 } else if (args->size() != 0) {
1868 ALOGI("DSA args must be 3");
1869 return ::SYSTEM_ERROR;
1870 }
1871
Kenny Root1d448c02013-11-21 10:36:53 -08001872 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001873 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1874 } else {
1875 isFallback = true;
1876 rc = openssl_generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1877 }
1878 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001879 keymaster_ec_keygen_params_t ec_params;
1880 memset(&ec_params, '\0', sizeof(ec_params));
1881
1882 if (keySize == -1) {
1883 keySize = EC_DEFAULT_KEY_SIZE;
1884 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1885 ALOGI("invalid key size %d", keySize);
1886 return ::SYSTEM_ERROR;
1887 }
1888 ec_params.field_size = keySize;
1889
Kenny Root1d448c02013-11-21 10:36:53 -08001890 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001891 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1892 } else {
1893 isFallback = true;
1894 rc = openssl_generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1895 }
Kenny Root96427ba2013-08-16 14:02:41 -07001896 } else if (keyType == EVP_PKEY_RSA) {
1897 keymaster_rsa_keygen_params_t rsa_params;
1898 memset(&rsa_params, '\0', sizeof(rsa_params));
1899 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1900
1901 if (keySize == -1) {
1902 keySize = RSA_DEFAULT_KEY_SIZE;
1903 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1904 ALOGI("invalid key size %d", keySize);
1905 return ::SYSTEM_ERROR;
1906 }
1907 rsa_params.modulus_size = keySize;
1908
1909 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001910 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001911 return ::SYSTEM_ERROR;
1912 } else if (args->size() == 1) {
1913 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1914 if (pubExpBlob != NULL) {
1915 Unique_BIGNUM pubExpBn(
1916 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1917 pubExpBlob->size(), NULL));
1918 if (pubExpBn.get() == NULL) {
1919 ALOGI("Could not convert public exponent to BN");
1920 return ::SYSTEM_ERROR;
1921 }
1922 unsigned long pubExp = BN_get_word(pubExpBn.get());
1923 if (pubExp == 0xFFFFFFFFL) {
1924 ALOGI("cannot represent public exponent as a long value");
1925 return ::SYSTEM_ERROR;
1926 }
1927 rsa_params.public_exponent = pubExp;
1928 }
1929 }
1930
1931 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1932 } else {
1933 ALOGW("Unsupported key type %d", keyType);
1934 rc = -1;
1935 }
1936
Kenny Root07438c82012-11-02 15:41:02 -07001937 if (rc) {
1938 return ::SYSTEM_ERROR;
1939 }
1940
Kenny Root655b9582013-04-04 08:37:42 -07001941 String8 name8(name);
1942 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07001943
1944 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1945 free(data);
1946
Kenny Rootee8068b2013-10-07 09:49:15 -07001947 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001948 keyBlob.setFallback(isFallback);
1949
Kenny Root655b9582013-04-04 08:37:42 -07001950 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001951 }
1952
Kenny Rootf9119d62013-04-03 09:22:15 -07001953 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1954 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001955 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001956 pid_t spid = IPCThreadState::self()->getCallingPid();
1957 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001958 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001959 return ::PERMISSION_DENIED;
1960 }
Kenny Root07438c82012-11-02 15:41:02 -07001961
Kenny Root49468902013-03-19 13:41:33 -07001962 if (targetUid == -1) {
1963 targetUid = callingUid;
1964 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001965 return ::PERMISSION_DENIED;
1966 }
1967
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001968 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001969 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07001970 ALOGD("calling import in state: %d", state);
1971 return state;
1972 }
1973
1974 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07001975 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001976
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001977 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08001978 }
1979
Kenny Root07438c82012-11-02 15:41:02 -07001980 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
1981 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001982 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001983 pid_t spid = IPCThreadState::self()->getCallingPid();
1984 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001985 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001986 return ::PERMISSION_DENIED;
1987 }
Kenny Root07438c82012-11-02 15:41:02 -07001988
Kenny Root07438c82012-11-02 15:41:02 -07001989 Blob keyBlob;
1990 String8 name8(name);
1991
Kenny Rootd38a0b02013-02-13 12:59:14 -08001992 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001993 int rc;
1994
Kenny Root655b9582013-04-04 08:37:42 -07001995 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08001996 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07001997 if (responseCode != ::NO_ERROR) {
1998 return responseCode;
1999 }
2000
2001 const keymaster_device_t* device = mKeyStore->getDevice();
2002 if (device == NULL) {
2003 ALOGE("no keymaster device; cannot sign");
2004 return ::SYSTEM_ERROR;
2005 }
2006
2007 if (device->sign_data == NULL) {
2008 ALOGE("device doesn't implement signing");
2009 return ::SYSTEM_ERROR;
2010 }
2011
2012 keymaster_rsa_sign_params_t params;
2013 params.digest_type = DIGEST_NONE;
2014 params.padding_type = PADDING_NONE;
2015
Kenny Root17208e02013-09-04 13:56:03 -07002016 if (keyBlob.isFallback()) {
2017 rc = openssl_sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2018 length, out, outLength);
2019 } else {
2020 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2021 length, out, outLength);
2022 }
Kenny Root07438c82012-11-02 15:41:02 -07002023 if (rc) {
2024 ALOGW("device couldn't sign data");
2025 return ::SYSTEM_ERROR;
2026 }
2027
2028 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002029 }
2030
Kenny Root07438c82012-11-02 15:41:02 -07002031 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2032 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002033 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002034 pid_t spid = IPCThreadState::self()->getCallingPid();
2035 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002036 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002037 return ::PERMISSION_DENIED;
2038 }
Kenny Root70e3a862012-02-15 17:20:23 -08002039
Kenny Root655b9582013-04-04 08:37:42 -07002040 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002041 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002042 ALOGD("calling verify in state: %d", state);
2043 return state;
2044 }
Kenny Root70e3a862012-02-15 17:20:23 -08002045
Kenny Root07438c82012-11-02 15:41:02 -07002046 Blob keyBlob;
2047 String8 name8(name);
2048 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002049
Kenny Root655b9582013-04-04 08:37:42 -07002050 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002051 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002052 if (responseCode != ::NO_ERROR) {
2053 return responseCode;
2054 }
Kenny Root70e3a862012-02-15 17:20:23 -08002055
Kenny Root07438c82012-11-02 15:41:02 -07002056 const keymaster_device_t* device = mKeyStore->getDevice();
2057 if (device == NULL) {
2058 return ::SYSTEM_ERROR;
2059 }
Kenny Root70e3a862012-02-15 17:20:23 -08002060
Kenny Root07438c82012-11-02 15:41:02 -07002061 if (device->verify_data == NULL) {
2062 return ::SYSTEM_ERROR;
2063 }
Kenny Root70e3a862012-02-15 17:20:23 -08002064
Kenny Root07438c82012-11-02 15:41:02 -07002065 keymaster_rsa_sign_params_t params;
2066 params.digest_type = DIGEST_NONE;
2067 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002068
Kenny Root17208e02013-09-04 13:56:03 -07002069 if (keyBlob.isFallback()) {
2070 rc = openssl_verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2071 dataLength, signature, signatureLength);
2072 } else {
2073 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2074 dataLength, signature, signatureLength);
2075 }
Kenny Root07438c82012-11-02 15:41:02 -07002076 if (rc) {
2077 return ::SYSTEM_ERROR;
2078 } else {
2079 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002080 }
2081 }
Kenny Root07438c82012-11-02 15:41:02 -07002082
2083 /*
2084 * TODO: The abstraction between things stored in hardware and regular blobs
2085 * of data stored on the filesystem should be moved down to keystore itself.
2086 * Unfortunately the Java code that calls this has naming conventions that it
2087 * knows about. Ideally keystore shouldn't be used to store random blobs of
2088 * data.
2089 *
2090 * Until that happens, it's necessary to have a separate "get_pubkey" and
2091 * "del_key" since the Java code doesn't really communicate what it's
2092 * intentions are.
2093 */
2094 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002095 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002096 pid_t spid = IPCThreadState::self()->getCallingPid();
2097 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002098 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002099 return ::PERMISSION_DENIED;
2100 }
Kenny Root07438c82012-11-02 15:41:02 -07002101
Kenny Root07438c82012-11-02 15:41:02 -07002102 Blob keyBlob;
2103 String8 name8(name);
2104
Kenny Rootd38a0b02013-02-13 12:59:14 -08002105 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002106
Kenny Root655b9582013-04-04 08:37:42 -07002107 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002108 TYPE_KEY_PAIR);
2109 if (responseCode != ::NO_ERROR) {
2110 return responseCode;
2111 }
2112
2113 const keymaster_device_t* device = mKeyStore->getDevice();
2114 if (device == NULL) {
2115 return ::SYSTEM_ERROR;
2116 }
2117
2118 if (device->get_keypair_public == NULL) {
2119 ALOGE("device has no get_keypair_public implementation!");
2120 return ::SYSTEM_ERROR;
2121 }
2122
Kenny Root17208e02013-09-04 13:56:03 -07002123 int rc;
2124 if (keyBlob.isFallback()) {
2125 rc = openssl_get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2126 pubkeyLength);
2127 } else {
2128 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2129 pubkeyLength);
2130 }
Kenny Root07438c82012-11-02 15:41:02 -07002131 if (rc) {
2132 return ::SYSTEM_ERROR;
2133 }
2134
2135 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002136 }
Kenny Root07438c82012-11-02 15:41:02 -07002137
Kenny Root49468902013-03-19 13:41:33 -07002138 int32_t del_key(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002139 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002140 pid_t spid = IPCThreadState::self()->getCallingPid();
2141 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002142 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002143 return ::PERMISSION_DENIED;
2144 }
Kenny Root07438c82012-11-02 15:41:02 -07002145
Kenny Root49468902013-03-19 13:41:33 -07002146 if (targetUid == -1) {
2147 targetUid = callingUid;
2148 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002149 return ::PERMISSION_DENIED;
2150 }
2151
Kenny Root07438c82012-11-02 15:41:02 -07002152 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002153 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002154
2155 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002156 ResponseCode responseCode = mKeyStore->get(filename.string(), &keyBlob, ::TYPE_KEY_PAIR,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002157 targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002158 if (responseCode != ::NO_ERROR) {
2159 return responseCode;
2160 }
2161
2162 ResponseCode rc = ::NO_ERROR;
2163
2164 const keymaster_device_t* device = mKeyStore->getDevice();
2165 if (device == NULL) {
2166 rc = ::SYSTEM_ERROR;
2167 } else {
2168 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002169 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Root07438c82012-11-02 15:41:02 -07002170 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2171 rc = ::SYSTEM_ERROR;
2172 }
2173 }
2174 }
2175
2176 if (rc != ::NO_ERROR) {
2177 return rc;
2178 }
2179
2180 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
2181 }
2182
2183 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002184 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002185 pid_t spid = IPCThreadState::self()->getCallingPid();
2186 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002187 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002188 return ::PERMISSION_DENIED;
2189 }
Kenny Root07438c82012-11-02 15:41:02 -07002190
Kenny Root655b9582013-04-04 08:37:42 -07002191 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002192 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002193 ALOGD("calling grant in state: %d", state);
2194 return state;
2195 }
2196
2197 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002198 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002199
Kenny Root655b9582013-04-04 08:37:42 -07002200 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002201 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2202 }
2203
Kenny Root655b9582013-04-04 08:37:42 -07002204 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002205 return ::NO_ERROR;
2206 }
2207
2208 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002209 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002210 pid_t spid = IPCThreadState::self()->getCallingPid();
2211 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002212 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002213 return ::PERMISSION_DENIED;
2214 }
Kenny Root07438c82012-11-02 15:41:02 -07002215
Kenny Root655b9582013-04-04 08:37:42 -07002216 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002217 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002218 ALOGD("calling ungrant in state: %d", state);
2219 return state;
2220 }
2221
2222 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002223 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002224
Kenny Root655b9582013-04-04 08:37:42 -07002225 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002226 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2227 }
2228
Kenny Root655b9582013-04-04 08:37:42 -07002229 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002230 }
2231
2232 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002233 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002234 pid_t spid = IPCThreadState::self()->getCallingPid();
2235 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002236 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002237 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002238 }
Kenny Root07438c82012-11-02 15:41:02 -07002239
2240 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002241 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002242
Kenny Root655b9582013-04-04 08:37:42 -07002243 if (access(filename.string(), R_OK) == -1) {
2244 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002245 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002246 }
2247
Kenny Root655b9582013-04-04 08:37:42 -07002248 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002249 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002250 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002251 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002252 }
2253
2254 struct stat s;
2255 int ret = fstat(fd, &s);
2256 close(fd);
2257 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002258 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002259 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002260 }
2261
Kenny Root36a9e232013-02-04 14:24:15 -08002262 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002263 }
2264
Kenny Rootd53bc922013-03-21 14:10:15 -07002265 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2266 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002267 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002268 pid_t spid = IPCThreadState::self()->getCallingPid();
2269 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002270 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002271 return -1L;
2272 }
2273
Kenny Root655b9582013-04-04 08:37:42 -07002274 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002275 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002276 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002277 return state;
2278 }
2279
Kenny Rootd53bc922013-03-21 14:10:15 -07002280 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2281 srcUid = callingUid;
2282 } else if (!is_granted_to(callingUid, srcUid)) {
2283 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002284 return ::PERMISSION_DENIED;
2285 }
2286
Kenny Rootd53bc922013-03-21 14:10:15 -07002287 if (destUid == -1) {
2288 destUid = callingUid;
2289 }
2290
2291 if (srcUid != destUid) {
2292 if (static_cast<uid_t>(srcUid) != callingUid) {
2293 ALOGD("can only duplicate from caller to other or to same uid: "
2294 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2295 return ::PERMISSION_DENIED;
2296 }
2297
2298 if (!is_granted_to(callingUid, destUid)) {
2299 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2300 return ::PERMISSION_DENIED;
2301 }
2302 }
2303
2304 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002305 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002306
Kenny Rootd53bc922013-03-21 14:10:15 -07002307 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002308 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002309
Kenny Root655b9582013-04-04 08:37:42 -07002310 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2311 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002312 return ::SYSTEM_ERROR;
2313 }
2314
Kenny Rootd53bc922013-03-21 14:10:15 -07002315 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002316 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002317 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002318 if (responseCode != ::NO_ERROR) {
2319 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002320 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002321
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002322 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002323 }
2324
Kenny Root1b0e3932013-09-05 13:06:32 -07002325 int32_t is_hardware_backed(const String16& keyType) {
2326 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002327 }
2328
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002329 int32_t clear_uid(int64_t targetUid64) {
2330 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002331 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002332 pid_t spid = IPCThreadState::self()->getCallingPid();
2333 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002334 ALOGW("permission denied for %d: clear_uid", callingUid);
2335 return ::PERMISSION_DENIED;
2336 }
2337
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002338 if (targetUid64 == -1) {
2339 targetUid = callingUid;
Kenny Root007cb232014-07-30 16:59:42 -07002340 } else if (!is_self_or_system(callingUid, targetUid)) {
2341 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002342 return ::PERMISSION_DENIED;
2343 }
2344
Kenny Roota9bb5492013-04-01 16:29:11 -07002345 const keymaster_device_t* device = mKeyStore->getDevice();
2346 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002347 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002348 return ::SYSTEM_ERROR;
2349 }
2350
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002351 UserState* userState = mKeyStore->getUserState(targetUid);
Kenny Root655b9582013-04-04 08:37:42 -07002352 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota9bb5492013-04-01 16:29:11 -07002353 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -07002354 ALOGW("can't open user directory: %s", strerror(errno));
Kenny Roota9bb5492013-04-01 16:29:11 -07002355 return ::SYSTEM_ERROR;
2356 }
2357
Kenny Root655b9582013-04-04 08:37:42 -07002358 char prefix[NAME_MAX];
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002359 int n = snprintf(prefix, NAME_MAX, "%u_", targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002360
2361 ResponseCode rc = ::NO_ERROR;
2362
2363 struct dirent* file;
2364 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002365 // We only care about files.
2366 if (file->d_type != DT_REG) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002367 continue;
2368 }
2369
Kenny Root655b9582013-04-04 08:37:42 -07002370 // Skip anything that starts with a "."
2371 if (file->d_name[0] == '.') {
2372 continue;
2373 }
Kenny Roota9bb5492013-04-01 16:29:11 -07002374
Kenny Root655b9582013-04-04 08:37:42 -07002375 if (strncmp(prefix, file->d_name, n)) {
2376 continue;
2377 }
2378
2379 String8 filename(String8::format("%s/%s", userState->getUserDirName(), file->d_name));
Kenny Roota9bb5492013-04-01 16:29:11 -07002380 Blob keyBlob;
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002381 if (mKeyStore->get(filename.string(), &keyBlob, ::TYPE_ANY, targetUid)
Kenny Root655b9582013-04-04 08:37:42 -07002382 != ::NO_ERROR) {
2383 ALOGW("couldn't open %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002384 continue;
2385 }
2386
2387 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
2388 // A device doesn't have to implement delete_keypair.
Kenny Root17208e02013-09-04 13:56:03 -07002389 if (device->delete_keypair != NULL && !keyBlob.isFallback()) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002390 if (device->delete_keypair(device, keyBlob.getValue(), keyBlob.getLength())) {
2391 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002392 ALOGW("device couldn't remove %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002393 }
2394 }
2395 }
2396
Kenny Root5f531242013-04-12 11:31:50 -07002397 if (unlinkat(dirfd(dir), file->d_name, 0) && errno != ENOENT) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002398 rc = ::SYSTEM_ERROR;
Kenny Root655b9582013-04-04 08:37:42 -07002399 ALOGW("couldn't unlink %s", filename.string());
Kenny Roota9bb5492013-04-01 16:29:11 -07002400 }
2401 }
2402 closedir(dir);
2403
2404 return rc;
2405 }
2406
Robin Lee4e865752014-08-19 17:37:55 +01002407 int32_t reset_uid(int32_t uid) {
2408 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2409 pid_t spid = IPCThreadState::self()->getCallingPid();
2410 if (!has_permission(callingUid, P_RESET_UID, spid)) {
2411 ALOGW("permission denied for %d: reset_uid %d", callingUid, uid);
2412 return ::PERMISSION_DENIED;
2413 }
2414 if (callingUid != AID_SYSTEM) {
2415 ALOGW("permission denied for %d: reset_uid %d", callingUid, uid);
2416 return ::PERMISSION_DENIED;
2417 }
2418
2419 return mKeyStore->reset(uid) ? ::NO_ERROR : ::SYSTEM_ERROR;
2420 }
2421
2422 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
2423 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2424 pid_t spid = IPCThreadState::self()->getCallingPid();
2425 if (!has_permission(callingUid, P_SYNC_UID, spid)) {
2426 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2427 return ::PERMISSION_DENIED;
2428 }
2429 if (callingUid != AID_SYSTEM) {
2430 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2431 return ::PERMISSION_DENIED;
2432 }
2433 if (sourceUid == targetUid) {
2434 return ::SYSTEM_ERROR;
2435 }
2436
2437 // Initialise user keystore with existing master key held in-memory
2438 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2439 }
2440
2441 int32_t password_uid(const String16& pw, int32_t targetUid) {
2442 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2443 pid_t spid = IPCThreadState::self()->getCallingPid();
2444 if (!has_permission(callingUid, P_PASSWORD_UID, spid)) {
2445 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2446 return ::PERMISSION_DENIED;
2447 }
2448 if (callingUid != AID_SYSTEM) {
2449 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2450 return ::PERMISSION_DENIED;
2451 }
2452
2453 const String8 password8(pw);
2454
2455 switch (mKeyStore->getState(targetUid)) {
2456 case ::STATE_UNINITIALIZED: {
2457 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2458 return mKeyStore->initializeUser(password8, targetUid);
2459 }
2460 case ::STATE_NO_ERROR: {
2461 // rewrite master key with new password.
2462 return mKeyStore->writeMasterKey(password8, targetUid);
2463 }
2464 case ::STATE_LOCKED: {
2465 // read master key, decrypt with password, initialize mMasterKey*.
2466 return mKeyStore->readMasterKey(password8, targetUid);
2467 }
2468 }
2469 return ::SYSTEM_ERROR;
2470 }
2471
Kenny Root07438c82012-11-02 15:41:02 -07002472private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002473 inline bool isKeystoreUnlocked(State state) {
2474 switch (state) {
2475 case ::STATE_NO_ERROR:
2476 return true;
2477 case ::STATE_UNINITIALIZED:
2478 case ::STATE_LOCKED:
2479 return false;
2480 }
2481 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002482 }
2483
Kenny Root1d448c02013-11-21 10:36:53 -08002484 bool isKeyTypeSupported(const keymaster_device_t* device, keymaster_keypair_t keyType) {
2485 const int32_t device_api = device->common.module->module_api_version;
2486 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2487 switch (keyType) {
2488 case TYPE_RSA:
2489 case TYPE_DSA:
2490 case TYPE_EC:
2491 return true;
2492 default:
2493 return false;
2494 }
2495 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2496 switch (keyType) {
2497 case TYPE_RSA:
2498 return true;
2499 case TYPE_DSA:
2500 return device->flags & KEYMASTER_SUPPORTS_DSA;
2501 case TYPE_EC:
2502 return device->flags & KEYMASTER_SUPPORTS_EC;
2503 default:
2504 return false;
2505 }
2506 } else {
2507 return keyType == TYPE_RSA;
2508 }
2509 }
2510
Kenny Root07438c82012-11-02 15:41:02 -07002511 ::KeyStore* mKeyStore;
2512};
2513
2514}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002515
2516int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002517 if (argc < 2) {
2518 ALOGE("A directory must be specified!");
2519 return 1;
2520 }
2521 if (chdir(argv[1]) == -1) {
2522 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2523 return 1;
2524 }
2525
2526 Entropy entropy;
2527 if (!entropy.open()) {
2528 return 1;
2529 }
Kenny Root70e3a862012-02-15 17:20:23 -08002530
2531 keymaster_device_t* dev;
2532 if (keymaster_device_initialize(&dev)) {
2533 ALOGE("keystore keymaster could not be initialized; exiting");
2534 return 1;
2535 }
2536
Riley Spahneaabae92014-06-30 12:39:52 -07002537 ks_is_selinux_enabled = is_selinux_enabled();
2538 if (ks_is_selinux_enabled) {
2539 union selinux_callback cb;
2540 cb.func_log = selinux_log_callback;
2541 selinux_set_callback(SELINUX_CB_LOG, cb);
2542 if (getcon(&tctx) != 0) {
2543 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2544 return -1;
2545 }
2546 } else {
2547 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2548 }
2549
Kenny Root70e3a862012-02-15 17:20:23 -08002550 KeyStore keyStore(&entropy, dev);
Kenny Root655b9582013-04-04 08:37:42 -07002551 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002552 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2553 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2554 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2555 if (ret != android::OK) {
2556 ALOGE("Couldn't register binder service!");
2557 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002558 }
Kenny Root07438c82012-11-02 15:41:02 -07002559
2560 /*
2561 * We're the only thread in existence, so we're just going to process
2562 * Binder transaction as a single-threaded program.
2563 */
2564 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002565
2566 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002567 return 1;
2568}