blob: 5997cd553a4e37977da410b83a9eb37024bef14b [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>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willdena5bbf2f2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Kenny Root17208e02013-09-04 13:56:03 -070046#include <keymaster/softkeymaster.h>
Chad Brubaker919cb2a2015-02-05 21:58:25 -080047#include <keymaster/soft_keymaster_device.h>
Kenny Root17208e02013-09-04 13:56:03 -070048
Kenny Root26cfc082013-09-11 14:38:56 -070049#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070050#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080052
Kenny Root07438c82012-11-02 15:41:02 -070053#include <keystore/IKeystoreService.h>
54#include <binder/IPCThreadState.h>
55#include <binder/IServiceManager.h>
56
Kenny Roota91203b2012-02-15 15:00:46 -080057#include <cutils/log.h>
58#include <cutils/sockets.h>
59#include <private/android_filesystem_config.h>
60
Kenny Root07438c82012-11-02 15:41:02 -070061#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080062
Riley Spahneaabae92014-06-30 12:39:52 -070063#include <selinux/android.h>
64
Kenny Root96427ba2013-08-16 14:02:41 -070065#include "defaults.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080066#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070067
Kenny Roota91203b2012-02-15 15:00:46 -080068/* KeyStore is a secured storage for key-value pairs. In this implementation,
69 * each file stores one key-value pair. Keys are encoded in file names, and
70 * values are encrypted with checksums. The encryption key is protected by a
71 * user-defined password. To keep things simple, buffers are always larger than
72 * the maximum space we needed, so boundary checks on buffers are omitted. */
73
74#define KEY_SIZE ((NAME_MAX - 15) / 2)
75#define VALUE_SIZE 32768
76#define PASSWORD_SIZE VALUE_SIZE
77
Kenny Root822c3a92012-03-23 16:34:39 -070078
Kenny Root96427ba2013-08-16 14:02:41 -070079struct BIGNUM_Delete {
80 void operator()(BIGNUM* p) const {
81 BN_free(p);
82 }
83};
84typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
85
Kenny Root822c3a92012-03-23 16:34:39 -070086struct BIO_Delete {
87 void operator()(BIO* p) const {
88 BIO_free(p);
89 }
90};
91typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
92
93struct EVP_PKEY_Delete {
94 void operator()(EVP_PKEY* p) const {
95 EVP_PKEY_free(p);
96 }
97};
98typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
99
100struct PKCS8_PRIV_KEY_INFO_Delete {
101 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
102 PKCS8_PRIV_KEY_INFO_free(p);
103 }
104};
105typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
106
107
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700108static int keymaster_device_initialize(keymaster0_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800109 int rc;
110
111 const hw_module_t* mod;
112 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
113 if (rc) {
114 ALOGE("could not find any keystore module");
115 goto out;
116 }
117
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700118 rc = keymaster0_open(mod, dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800119 if (rc) {
120 ALOGE("could not open keymaster device in %s (%s)",
121 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
122 goto out;
123 }
124
125 return 0;
126
127out:
128 *dev = NULL;
129 return rc;
130}
131
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800132static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
133 keymaster::SoftKeymasterDevice* softkeymaster =
134 new keymaster::SoftKeymasterDevice();
135 // SoftKeymasterDevice is designed to make this cast safe.
136 *dev = reinterpret_cast<keymaster1_device_t*>(softkeymaster);
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800137 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800138}
139
Shawn Willdena5bbf2f2015-02-24 09:31:25 -0700140static void keymaster_device_release(keymaster0_device_t* dev) {
141 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800142}
143
Kenny Root07438c82012-11-02 15:41:02 -0700144/***************
145 * PERMISSIONS *
146 ***************/
147
148/* Here are the permissions, actions, users, and the main function. */
149typedef enum {
Robin Lee4e865752014-08-19 17:37:55 +0100150 P_TEST = 1 << 0,
151 P_GET = 1 << 1,
152 P_INSERT = 1 << 2,
153 P_DELETE = 1 << 3,
154 P_EXIST = 1 << 4,
155 P_SAW = 1 << 5,
156 P_RESET = 1 << 6,
157 P_PASSWORD = 1 << 7,
158 P_LOCK = 1 << 8,
159 P_UNLOCK = 1 << 9,
160 P_ZERO = 1 << 10,
161 P_SIGN = 1 << 11,
162 P_VERIFY = 1 << 12,
163 P_GRANT = 1 << 13,
164 P_DUPLICATE = 1 << 14,
165 P_CLEAR_UID = 1 << 15,
166 P_RESET_UID = 1 << 16,
167 P_SYNC_UID = 1 << 17,
168 P_PASSWORD_UID = 1 << 18,
Kenny Root07438c82012-11-02 15:41:02 -0700169} perm_t;
170
171static struct user_euid {
172 uid_t uid;
173 uid_t euid;
174} user_euids[] = {
175 {AID_VPN, AID_SYSTEM},
176 {AID_WIFI, AID_SYSTEM},
177 {AID_ROOT, AID_SYSTEM},
178};
179
Riley Spahneaabae92014-06-30 12:39:52 -0700180/* perm_labels associcated with keystore_key SELinux class verbs. */
181const char *perm_labels[] = {
182 "test",
183 "get",
184 "insert",
185 "delete",
186 "exist",
187 "saw",
188 "reset",
189 "password",
190 "lock",
191 "unlock",
192 "zero",
193 "sign",
194 "verify",
195 "grant",
196 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100197 "clear_uid",
198 "reset_uid",
199 "sync_uid",
200 "password_uid",
Riley Spahneaabae92014-06-30 12:39:52 -0700201};
202
Kenny Root07438c82012-11-02 15:41:02 -0700203static struct user_perm {
204 uid_t uid;
205 perm_t perms;
206} user_perms[] = {
207 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
208 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
209 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
210 {AID_ROOT, static_cast<perm_t>(P_GET) },
211};
212
213static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
214 | P_VERIFY);
215
Riley Spahneaabae92014-06-30 12:39:52 -0700216static char *tctx;
217static int ks_is_selinux_enabled;
218
219static const char *get_perm_label(perm_t perm) {
220 unsigned int index = ffs(perm);
221 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
222 return perm_labels[index - 1];
223 } else {
224 ALOGE("Keystore: Failed to retrieve permission label.\n");
225 abort();
226 }
227}
228
Kenny Root655b9582013-04-04 08:37:42 -0700229/**
230 * Returns the app ID (in the Android multi-user sense) for the current
231 * UNIX UID.
232 */
233static uid_t get_app_id(uid_t uid) {
234 return uid % AID_USER;
235}
236
237/**
238 * Returns the user ID (in the Android multi-user sense) for the current
239 * UNIX UID.
240 */
241static uid_t get_user_id(uid_t uid) {
242 return uid / AID_USER;
243}
244
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700245static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700246 if (!ks_is_selinux_enabled) {
247 return true;
248 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000249
Riley Spahneaabae92014-06-30 12:39:52 -0700250 char *sctx = NULL;
251 const char *selinux_class = "keystore_key";
252 const char *str_perm = get_perm_label(perm);
253
254 if (!str_perm) {
255 return false;
256 }
257
258 if (getpidcon(spid, &sctx) != 0) {
259 ALOGE("SELinux: Failed to get source pid context.\n");
260 return false;
261 }
262
263 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
264 NULL) == 0;
265 freecon(sctx);
266 return allowed;
267}
268
269static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700270 // All system users are equivalent for multi-user support.
271 if (get_app_id(uid) == AID_SYSTEM) {
272 uid = AID_SYSTEM;
273 }
274
Kenny Root07438c82012-11-02 15:41:02 -0700275 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
276 struct user_perm user = user_perms[i];
277 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700278 return (user.perms & perm) &&
279 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700280 }
281 }
282
Riley Spahneaabae92014-06-30 12:39:52 -0700283 return (DEFAULT_PERMS & perm) &&
284 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700285}
286
Kenny Root49468902013-03-19 13:41:33 -0700287/**
288 * Returns the UID that the callingUid should act as. This is here for
289 * legacy support of the WiFi and VPN systems and should be removed
290 * when WiFi can operate in its own namespace.
291 */
Kenny Root07438c82012-11-02 15:41:02 -0700292static uid_t get_keystore_euid(uid_t uid) {
293 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
294 struct user_euid user = user_euids[i];
295 if (user.uid == uid) {
296 return user.euid;
297 }
298 }
299
300 return uid;
301}
302
Kenny Root49468902013-03-19 13:41:33 -0700303/**
304 * Returns true if the callingUid is allowed to interact in the targetUid's
305 * namespace.
306 */
307static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
308 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
309 struct user_euid user = user_euids[i];
310 if (user.euid == callingUid && user.uid == targetUid) {
311 return true;
312 }
313 }
314
315 return false;
316}
317
Kenny Root007cb232014-07-30 16:59:42 -0700318/**
319 * Allow the system to perform some privileged tasks that have to do with
320 * system maintenance. This should not be used for any function that uses
321 * the keys in any way (e.g., signing).
322 */
323static bool is_self_or_system(uid_t callingUid, uid_t targetUid) {
324 return callingUid == targetUid || callingUid == AID_SYSTEM;
325}
326
Kenny Roota91203b2012-02-15 15:00:46 -0800327/* Here is the encoding of keys. This is necessary in order to allow arbitrary
328 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
329 * into two bytes. The first byte is one of [+-.] which represents the first
330 * two bits of the character. The second byte encodes the rest of the bits into
331 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
332 * that Base64 cannot be used here due to the need of prefix match on keys. */
333
Kenny Root655b9582013-04-04 08:37:42 -0700334static size_t encode_key_length(const android::String8& keyName) {
335 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
336 size_t length = keyName.length();
337 for (int i = length; i > 0; --i, ++in) {
338 if (*in < '0' || *in > '~') {
339 ++length;
340 }
341 }
342 return length;
343}
344
Kenny Root07438c82012-11-02 15:41:02 -0700345static int encode_key(char* out, const android::String8& keyName) {
346 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
347 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800348 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700349 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800350 *out = '+' + (*in >> 6);
351 *++out = '0' + (*in & 0x3F);
352 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700353 } else {
354 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800355 }
356 }
357 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800358 return length;
359}
360
Kenny Root07438c82012-11-02 15:41:02 -0700361/*
362 * Converts from the "escaped" format on disk to actual name.
363 * This will be smaller than the input string.
364 *
365 * Characters that should combine with the next at the end will be truncated.
366 */
367static size_t decode_key_length(const char* in, size_t length) {
368 size_t outLength = 0;
369
370 for (const char* end = in + length; in < end; in++) {
371 /* This combines with the next character. */
372 if (*in < '0' || *in > '~') {
373 continue;
374 }
375
376 outLength++;
377 }
378 return outLength;
379}
380
381static void decode_key(char* out, const char* in, size_t length) {
382 for (const char* end = in + length; in < end; in++) {
383 if (*in < '0' || *in > '~') {
384 /* Truncate combining characters at the end. */
385 if (in + 1 >= end) {
386 break;
387 }
388
389 *out = (*in++ - '+') << 6;
390 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800391 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700392 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800393 }
394 }
395 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800396}
397
398static size_t readFully(int fd, uint8_t* data, size_t size) {
399 size_t remaining = size;
400 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800401 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800402 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800403 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800404 }
405 data += n;
406 remaining -= n;
407 }
408 return size;
409}
410
411static size_t writeFully(int fd, uint8_t* data, size_t size) {
412 size_t remaining = size;
413 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800414 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
415 if (n < 0) {
416 ALOGW("write failed: %s", strerror(errno));
417 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800418 }
419 data += n;
420 remaining -= n;
421 }
422 return size;
423}
424
425class Entropy {
426public:
427 Entropy() : mRandom(-1) {}
428 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800429 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800430 close(mRandom);
431 }
432 }
433
434 bool open() {
435 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800436 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
437 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800438 ALOGE("open: %s: %s", randomDevice, strerror(errno));
439 return false;
440 }
441 return true;
442 }
443
Kenny Root51878182012-03-13 12:53:19 -0700444 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800445 return (readFully(mRandom, data, size) == size);
446 }
447
448private:
449 int mRandom;
450};
451
452/* Here is the file format. There are two parts in blob.value, the secret and
453 * the description. The secret is stored in ciphertext, and its original size
454 * can be found in blob.length. The description is stored after the secret in
455 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700456 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700457 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800458 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
459 * and decryptBlob(). Thus they should not be accessed from outside. */
460
Kenny Root822c3a92012-03-23 16:34:39 -0700461/* ** Note to future implementors of encryption: **
462 * Currently this is the construction:
463 * metadata || Enc(MD5(data) || data)
464 *
465 * This should be the construction used for encrypting if re-implementing:
466 *
467 * Derive independent keys for encryption and MAC:
468 * Kenc = AES_encrypt(masterKey, "Encrypt")
469 * Kmac = AES_encrypt(masterKey, "MAC")
470 *
471 * Store this:
472 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
473 * HMAC(Kmac, metadata || Enc(data))
474 */
Kenny Roota91203b2012-02-15 15:00:46 -0800475struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700476 uint8_t version;
477 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700478 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800479 uint8_t info;
480 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700481 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800482 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700483 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800484 int32_t length; // in network byte order when encrypted
485 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
486};
487
Kenny Root822c3a92012-03-23 16:34:39 -0700488typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700489 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700490 TYPE_GENERIC = 1,
491 TYPE_MASTER_KEY = 2,
492 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800493 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700494} BlobType;
495
Kenny Rootf9119d62013-04-03 09:22:15 -0700496static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700497
Kenny Roota91203b2012-02-15 15:00:46 -0800498class Blob {
499public:
Kenny Root07438c82012-11-02 15:41:02 -0700500 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
501 BlobType type) {
Kenny Roota91203b2012-02-15 15:00:46 -0800502 mBlob.length = valueLength;
503 memcpy(mBlob.value, value, valueLength);
504
505 mBlob.info = infoLength;
506 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700507
Kenny Root07438c82012-11-02 15:41:02 -0700508 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700509 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700510
Kenny Rootee8068b2013-10-07 09:49:15 -0700511 if (type == TYPE_MASTER_KEY) {
512 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
513 } else {
514 mBlob.flags = KEYSTORE_FLAG_NONE;
515 }
Kenny Roota91203b2012-02-15 15:00:46 -0800516 }
517
518 Blob(blob b) {
519 mBlob = b;
520 }
521
522 Blob() {}
523
Kenny Root51878182012-03-13 12:53:19 -0700524 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800525 return mBlob.value;
526 }
527
Kenny Root51878182012-03-13 12:53:19 -0700528 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800529 return mBlob.length;
530 }
531
Kenny Root51878182012-03-13 12:53:19 -0700532 const uint8_t* getInfo() const {
533 return mBlob.value + mBlob.length;
534 }
535
536 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800537 return mBlob.info;
538 }
539
Kenny Root822c3a92012-03-23 16:34:39 -0700540 uint8_t getVersion() const {
541 return mBlob.version;
542 }
543
Kenny Rootf9119d62013-04-03 09:22:15 -0700544 bool isEncrypted() const {
545 if (mBlob.version < 2) {
546 return true;
547 }
548
549 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
550 }
551
552 void setEncrypted(bool encrypted) {
553 if (encrypted) {
554 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
555 } else {
556 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
557 }
558 }
559
Kenny Root17208e02013-09-04 13:56:03 -0700560 bool isFallback() const {
561 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
562 }
563
564 void setFallback(bool fallback) {
565 if (fallback) {
566 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
567 } else {
568 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
569 }
570 }
571
Kenny Root822c3a92012-03-23 16:34:39 -0700572 void setVersion(uint8_t version) {
573 mBlob.version = version;
574 }
575
576 BlobType getType() const {
577 return BlobType(mBlob.type);
578 }
579
580 void setType(BlobType type) {
581 mBlob.type = uint8_t(type);
582 }
583
Kenny Rootf9119d62013-04-03 09:22:15 -0700584 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
585 ALOGV("writing blob %s", filename);
586 if (isEncrypted()) {
587 if (state != STATE_NO_ERROR) {
588 ALOGD("couldn't insert encrypted blob while not unlocked");
589 return LOCKED;
590 }
591
592 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
593 ALOGW("Could not read random data for: %s", filename);
594 return SYSTEM_ERROR;
595 }
Kenny Roota91203b2012-02-15 15:00:46 -0800596 }
597
598 // data includes the value and the value's length
599 size_t dataLength = mBlob.length + sizeof(mBlob.length);
600 // pad data to the AES_BLOCK_SIZE
601 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
602 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
603 // encrypted data includes the digest value
604 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
605 // move info after space for padding
606 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
607 // zero padding area
608 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
609
610 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800611
Kenny Rootf9119d62013-04-03 09:22:15 -0700612 if (isEncrypted()) {
613 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800614
Kenny Rootf9119d62013-04-03 09:22:15 -0700615 uint8_t vector[AES_BLOCK_SIZE];
616 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
617 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
618 aes_key, vector, AES_ENCRYPT);
619 }
620
Kenny Roota91203b2012-02-15 15:00:46 -0800621 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
622 size_t fileLength = encryptedLength + headerLength + mBlob.info;
623
624 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800625 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
626 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
627 if (out < 0) {
628 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800629 return SYSTEM_ERROR;
630 }
631 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
632 if (close(out) != 0) {
633 return SYSTEM_ERROR;
634 }
635 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800636 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800637 unlink(tmpFileName);
638 return SYSTEM_ERROR;
639 }
Kenny Root150ca932012-11-14 14:29:02 -0800640 if (rename(tmpFileName, filename) == -1) {
641 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
642 return SYSTEM_ERROR;
643 }
644 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800645 }
646
Kenny Rootf9119d62013-04-03 09:22:15 -0700647 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
648 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800649 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
650 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800651 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
652 }
653 // fileLength may be less than sizeof(mBlob) since the in
654 // memory version has extra padding to tolerate rounding up to
655 // the AES_BLOCK_SIZE
656 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
657 if (close(in) != 0) {
658 return SYSTEM_ERROR;
659 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700660
661 if (isEncrypted() && (state != STATE_NO_ERROR)) {
662 return LOCKED;
663 }
664
Kenny Roota91203b2012-02-15 15:00:46 -0800665 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
666 if (fileLength < headerLength) {
667 return VALUE_CORRUPTED;
668 }
669
670 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700671 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800672 return VALUE_CORRUPTED;
673 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700674
675 ssize_t digestedLength;
676 if (isEncrypted()) {
677 if (encryptedLength % AES_BLOCK_SIZE != 0) {
678 return VALUE_CORRUPTED;
679 }
680
681 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
682 mBlob.vector, AES_DECRYPT);
683 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
684 uint8_t computedDigest[MD5_DIGEST_LENGTH];
685 MD5(mBlob.digested, digestedLength, computedDigest);
686 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
687 return VALUE_CORRUPTED;
688 }
689 } else {
690 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800691 }
692
693 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
694 mBlob.length = ntohl(mBlob.length);
695 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
696 return VALUE_CORRUPTED;
697 }
698 if (mBlob.info != 0) {
699 // move info from after padding to after data
700 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
701 }
Kenny Root07438c82012-11-02 15:41:02 -0700702 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800703 }
704
705private:
706 struct blob mBlob;
707};
708
Kenny Root655b9582013-04-04 08:37:42 -0700709class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800710public:
Kenny Root655b9582013-04-04 08:37:42 -0700711 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
712 asprintf(&mUserDir, "user_%u", mUserId);
713 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
714 }
715
716 ~UserState() {
717 free(mUserDir);
718 free(mMasterKeyFile);
719 }
720
721 bool initialize() {
722 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
723 ALOGE("Could not create directory '%s'", mUserDir);
724 return false;
725 }
726
727 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800728 setState(STATE_LOCKED);
729 } else {
730 setState(STATE_UNINITIALIZED);
731 }
Kenny Root70e3a862012-02-15 17:20:23 -0800732
Kenny Root655b9582013-04-04 08:37:42 -0700733 return true;
734 }
735
736 uid_t getUserId() const {
737 return mUserId;
738 }
739
740 const char* getUserDirName() const {
741 return mUserDir;
742 }
743
744 const char* getMasterKeyFileName() const {
745 return mMasterKeyFile;
746 }
747
748 void setState(State state) {
749 mState = state;
750 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
751 mRetry = MAX_RETRY;
752 }
Kenny Roota91203b2012-02-15 15:00:46 -0800753 }
754
Kenny Root51878182012-03-13 12:53:19 -0700755 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800756 return mState;
757 }
758
Kenny Root51878182012-03-13 12:53:19 -0700759 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800760 return mRetry;
761 }
762
Kenny Root655b9582013-04-04 08:37:42 -0700763 void zeroizeMasterKeysInMemory() {
764 memset(mMasterKey, 0, sizeof(mMasterKey));
765 memset(mSalt, 0, sizeof(mSalt));
766 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
767 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800768 }
769
Kenny Root655b9582013-04-04 08:37:42 -0700770 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
771 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800772 return SYSTEM_ERROR;
773 }
Kenny Root655b9582013-04-04 08:37:42 -0700774 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800775 if (response != NO_ERROR) {
776 return response;
777 }
778 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700779 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800780 }
781
Robin Lee4e865752014-08-19 17:37:55 +0100782 ResponseCode copyMasterKey(UserState* src) {
783 if (mState != STATE_UNINITIALIZED) {
784 return ::SYSTEM_ERROR;
785 }
786 if (src->getState() != STATE_NO_ERROR) {
787 return ::SYSTEM_ERROR;
788 }
789 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
790 setupMasterKeys();
791 return ::NO_ERROR;
792 }
793
Kenny Root655b9582013-04-04 08:37:42 -0700794 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800795 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
796 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
797 AES_KEY passwordAesKey;
798 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700799 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700800 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800801 }
802
Kenny Root655b9582013-04-04 08:37:42 -0700803 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
804 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800805 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800806 return SYSTEM_ERROR;
807 }
808
809 // we read the raw blob to just to get the salt to generate
810 // the AES key, then we create the Blob to use with decryptBlob
811 blob rawBlob;
812 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
813 if (close(in) != 0) {
814 return SYSTEM_ERROR;
815 }
816 // find salt at EOF if present, otherwise we have an old file
817 uint8_t* salt;
818 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
819 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
820 } else {
821 salt = NULL;
822 }
823 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
824 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
825 AES_KEY passwordAesKey;
826 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
827 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700828 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
829 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800830 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700831 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800832 }
833 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
834 // if salt was missing, generate one and write a new master key file with the salt.
835 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700836 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800837 return SYSTEM_ERROR;
838 }
Kenny Root655b9582013-04-04 08:37:42 -0700839 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800840 }
841 if (response == NO_ERROR) {
842 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
843 setupMasterKeys();
844 }
845 return response;
846 }
847 if (mRetry <= 0) {
848 reset();
849 return UNINITIALIZED;
850 }
851 --mRetry;
852 switch (mRetry) {
853 case 0: return WRONG_PASSWORD_0;
854 case 1: return WRONG_PASSWORD_1;
855 case 2: return WRONG_PASSWORD_2;
856 case 3: return WRONG_PASSWORD_3;
857 default: return WRONG_PASSWORD_3;
858 }
859 }
860
Kenny Root655b9582013-04-04 08:37:42 -0700861 AES_KEY* getEncryptionKey() {
862 return &mMasterKeyEncryption;
863 }
864
865 AES_KEY* getDecryptionKey() {
866 return &mMasterKeyDecryption;
867 }
868
Kenny Roota91203b2012-02-15 15:00:46 -0800869 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700870 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800871 if (!dir) {
Kenny Root655b9582013-04-04 08:37:42 -0700872 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800873 return false;
874 }
Kenny Root655b9582013-04-04 08:37:42 -0700875
876 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800877 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700878 // We only care about files.
879 if (file->d_type != DT_REG) {
880 continue;
881 }
882
883 // Skip anything that starts with a "."
Kenny Root931fac02014-07-30 16:39:40 -0700884 if (file->d_name[0] == '.' && strcmp(".masterkey", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700885 continue;
886 }
887
888 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800889 }
890 closedir(dir);
891 return true;
892 }
893
Kenny Root655b9582013-04-04 08:37:42 -0700894private:
895 static const int MASTER_KEY_SIZE_BYTES = 16;
896 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
897
898 static const int MAX_RETRY = 4;
899 static const size_t SALT_SIZE = 16;
900
901 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
902 uint8_t* salt) {
903 size_t saltSize;
904 if (salt != NULL) {
905 saltSize = SALT_SIZE;
906 } else {
907 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
908 salt = (uint8_t*) "keystore";
909 // sizeof = 9, not strlen = 8
910 saltSize = sizeof("keystore");
911 }
912
913 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
914 saltSize, 8192, keySize, key);
915 }
916
917 bool generateSalt(Entropy* entropy) {
918 return entropy->generate_random_data(mSalt, sizeof(mSalt));
919 }
920
921 bool generateMasterKey(Entropy* entropy) {
922 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
923 return false;
924 }
925 if (!generateSalt(entropy)) {
926 return false;
927 }
928 return true;
929 }
930
931 void setupMasterKeys() {
932 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
933 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
934 setState(STATE_NO_ERROR);
935 }
936
937 uid_t mUserId;
938
939 char* mUserDir;
940 char* mMasterKeyFile;
941
942 State mState;
943 int8_t mRetry;
944
945 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
946 uint8_t mSalt[SALT_SIZE];
947
948 AES_KEY mMasterKeyEncryption;
949 AES_KEY mMasterKeyDecryption;
950};
951
952typedef struct {
953 uint32_t uid;
954 const uint8_t* filename;
955} grant_t;
956
957class KeyStore {
958public:
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800959 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700960 : mEntropy(entropy)
961 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800962 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700963 {
964 memset(&mMetaData, '\0', sizeof(mMetaData));
965 }
966
967 ~KeyStore() {
968 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
969 it != mGrants.end(); it++) {
970 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700971 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800972 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700973
974 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
975 it != mMasterKeys.end(); it++) {
976 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700977 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800978 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700979 }
980
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800981 /**
982 * Depending on the hardware keymaster version is this may return a
983 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
984 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
985 * be guarded by a check on the device's version.
986 */
987 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700988 return mDevice;
989 }
990
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800991 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800992 return mFallbackDevice;
993 }
994
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800995 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800996 return blob.isFallback() ? mFallbackDevice: mDevice;
997 }
998
Kenny Root655b9582013-04-04 08:37:42 -0700999 ResponseCode initialize() {
1000 readMetaData();
1001 if (upgradeKeystore()) {
1002 writeMetaData();
1003 }
1004
1005 return ::NO_ERROR;
1006 }
1007
1008 State getState(uid_t uid) {
1009 return getUserState(uid)->getState();
1010 }
1011
1012 ResponseCode initializeUser(const android::String8& pw, uid_t uid) {
1013 UserState* userState = getUserState(uid);
1014 return userState->initialize(pw, mEntropy);
1015 }
1016
Robin Lee4e865752014-08-19 17:37:55 +01001017 ResponseCode copyMasterKey(uid_t src, uid_t uid) {
1018 UserState *userState = getUserState(uid);
1019 UserState *initState = getUserState(src);
1020 return userState->copyMasterKey(initState);
1021 }
1022
Kenny Root655b9582013-04-04 08:37:42 -07001023 ResponseCode writeMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001024 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001025 return userState->writeMasterKey(pw, mEntropy);
1026 }
1027
1028 ResponseCode readMasterKey(const android::String8& pw, uid_t uid) {
Robin Lee50122db2014-08-12 17:31:40 +01001029 UserState* userState = getUserState(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001030 return userState->readMasterKey(pw, mEntropy);
1031 }
1032
1033 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001034 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001035 encode_key(encoded, keyName);
1036 return android::String8(encoded);
1037 }
1038
1039 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001040 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001041 encode_key(encoded, keyName);
1042 return android::String8::format("%u_%s", uid, encoded);
1043 }
1044
1045 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001046 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001047 encode_key(encoded, keyName);
1048 return android::String8::format("%s/%u_%s", getUserState(uid)->getUserDirName(), uid,
1049 encoded);
1050 }
1051
1052 bool reset(uid_t uid) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001053 android::String8 prefix("");
1054 android::Vector<android::String16> aliases;
1055 if (saw(prefix, &aliases, uid) != ::NO_ERROR) {
1056 return ::SYSTEM_ERROR;
1057 }
1058
Kenny Root655b9582013-04-04 08:37:42 -07001059 UserState* userState = getUserState(uid);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001060 for (uint32_t i = 0; i < aliases.size(); i++) {
1061 android::String8 filename(aliases[i]);
1062 filename = android::String8::format("%s/%s", userState->getUserDirName(),
1063 getKeyName(filename).string());
1064 del(filename, ::TYPE_ANY, uid);
1065 }
1066
Kenny Root655b9582013-04-04 08:37:42 -07001067 userState->zeroizeMasterKeysInMemory();
1068 userState->setState(STATE_UNINITIALIZED);
1069 return userState->reset();
1070 }
1071
1072 bool isEmpty(uid_t uid) const {
1073 const UserState* userState = getUserState(uid);
Kenny Root31e27462014-09-10 11:28:03 -07001074 if (userState == NULL || userState->getState() == STATE_UNINITIALIZED) {
Kenny Root655b9582013-04-04 08:37:42 -07001075 return true;
1076 }
1077
1078 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001079 if (!dir) {
1080 return true;
1081 }
Kenny Root31e27462014-09-10 11:28:03 -07001082
Kenny Roota91203b2012-02-15 15:00:46 -08001083 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001084 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001085 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001086 // We only care about files.
1087 if (file->d_type != DT_REG) {
1088 continue;
1089 }
1090
1091 // Skip anything that starts with a "."
1092 if (file->d_name[0] == '.') {
1093 continue;
1094 }
1095
Kenny Root31e27462014-09-10 11:28:03 -07001096 result = false;
1097 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001098 }
1099 closedir(dir);
1100 return result;
1101 }
1102
Kenny Root655b9582013-04-04 08:37:42 -07001103 void lock(uid_t uid) {
1104 UserState* userState = getUserState(uid);
1105 userState->zeroizeMasterKeysInMemory();
1106 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001107 }
1108
Kenny Root655b9582013-04-04 08:37:42 -07001109 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t uid) {
1110 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001111 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1112 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001113 if (rc != NO_ERROR) {
1114 return rc;
1115 }
1116
1117 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001118 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001119 /* If we upgrade the key, we need to write it to disk again. Then
1120 * it must be read it again since the blob is encrypted each time
1121 * it's written.
1122 */
Kenny Root655b9582013-04-04 08:37:42 -07001123 if (upgradeBlob(filename, keyBlob, version, type, uid)) {
1124 if ((rc = this->put(filename, keyBlob, uid)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001125 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1126 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001127 return rc;
1128 }
1129 }
Kenny Root822c3a92012-03-23 16:34:39 -07001130 }
1131
Kenny Root17208e02013-09-04 13:56:03 -07001132 /*
1133 * This will upgrade software-backed keys to hardware-backed keys when
1134 * the HAL for the device supports the newer key types.
1135 */
1136 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1137 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1138 && keyBlob->isFallback()) {
1139 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
1140 uid, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
1141
1142 // The HAL allowed the import, reget the key to have the "fresh"
1143 // version.
1144 if (imported == NO_ERROR) {
1145 rc = get(filename, keyBlob, TYPE_KEY_PAIR, uid);
1146 }
1147 }
1148
Kenny Rootd53bc922013-03-21 14:10:15 -07001149 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001150 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1151 return KEY_NOT_FOUND;
1152 }
1153
1154 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001155 }
1156
Kenny Root655b9582013-04-04 08:37:42 -07001157 ResponseCode put(const char* filename, Blob* keyBlob, uid_t uid) {
1158 UserState* userState = getUserState(uid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001159 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1160 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001161 }
1162
Robin Lee4b84fdc2014-09-24 11:56:57 +01001163 ResponseCode del(const char *filename, const BlobType type, uid_t uid) {
1164 Blob keyBlob;
1165 ResponseCode rc = get(filename, &keyBlob, type, uid);
1166 if (rc != ::NO_ERROR) {
1167 return rc;
1168 }
1169
1170 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1171 // A device doesn't have to implement delete_keypair.
1172 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1173 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1174 rc = ::SYSTEM_ERROR;
1175 }
1176 }
1177 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001178 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1179 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1180 if (dev->delete_key) {
1181 keymaster_key_blob_t blob;
1182 blob.key_material = keyBlob.getValue();
1183 blob.key_material_size = keyBlob.getLength();
1184 dev->delete_key(dev, &blob);
1185 }
1186 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001187 if (rc != ::NO_ERROR) {
1188 return rc;
1189 }
1190
1191 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1192 }
1193
1194 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
1195 uid_t uid) {
1196
1197 UserState* userState = getUserState(uid);
1198 size_t n = prefix.length();
1199
1200 DIR* dir = opendir(userState->getUserDirName());
1201 if (!dir) {
1202 ALOGW("can't open directory for user: %s", strerror(errno));
1203 return ::SYSTEM_ERROR;
1204 }
1205
1206 struct dirent* file;
1207 while ((file = readdir(dir)) != NULL) {
1208 // We only care about files.
1209 if (file->d_type != DT_REG) {
1210 continue;
1211 }
1212
1213 // Skip anything that starts with a "."
1214 if (file->d_name[0] == '.') {
1215 continue;
1216 }
1217
1218 if (!strncmp(prefix.string(), file->d_name, n)) {
1219 const char* p = &file->d_name[n];
1220 size_t plen = strlen(p);
1221
1222 size_t extra = decode_key_length(p, plen);
1223 char *match = (char*) malloc(extra + 1);
1224 if (match != NULL) {
1225 decode_key(match, p, plen);
1226 matches->push(android::String16(match, extra));
1227 free(match);
1228 } else {
1229 ALOGW("could not allocate match of size %zd", extra);
1230 }
1231 }
1232 }
1233 closedir(dir);
1234 return ::NO_ERROR;
1235 }
1236
Kenny Root07438c82012-11-02 15:41:02 -07001237 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001238 const grant_t* existing = getGrant(filename, granteeUid);
1239 if (existing == NULL) {
1240 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001241 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001242 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001243 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001244 }
1245 }
1246
Kenny Root07438c82012-11-02 15:41:02 -07001247 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001248 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1249 it != mGrants.end(); it++) {
1250 grant_t* grant = *it;
1251 if (grant->uid == granteeUid
1252 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1253 mGrants.erase(it);
1254 return true;
1255 }
Kenny Root70e3a862012-02-15 17:20:23 -08001256 }
Kenny Root70e3a862012-02-15 17:20:23 -08001257 return false;
1258 }
1259
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001260 bool hasGrant(const char* filename, const uid_t uid) const {
1261 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001262 }
1263
Kenny Rootf9119d62013-04-03 09:22:15 -07001264 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t uid,
1265 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001266 uint8_t* data;
1267 size_t dataLength;
1268 int rc;
1269
1270 if (mDevice->import_keypair == NULL) {
1271 ALOGE("Keymaster doesn't support import!");
1272 return SYSTEM_ERROR;
1273 }
1274
Kenny Root17208e02013-09-04 13:56:03 -07001275 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001276 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001277 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001278 /*
1279 * Maybe the device doesn't support this type of key. Try to use the
1280 * software fallback keymaster implementation. This is a little bit
1281 * lazier than checking the PKCS#8 key type, but the software
1282 * implementation will do that anyway.
1283 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001284 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001285 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001286
1287 if (rc) {
1288 ALOGE("Error while importing keypair: %d", rc);
1289 return SYSTEM_ERROR;
1290 }
Kenny Root822c3a92012-03-23 16:34:39 -07001291 }
1292
1293 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1294 free(data);
1295
Kenny Rootf9119d62013-04-03 09:22:15 -07001296 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001297 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001298
Kenny Root655b9582013-04-04 08:37:42 -07001299 return put(filename, &keyBlob, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001300 }
1301
Kenny Root1b0e3932013-09-05 13:06:32 -07001302 bool isHardwareBacked(const android::String16& keyType) const {
1303 if (mDevice == NULL) {
1304 ALOGW("can't get keymaster device");
1305 return false;
1306 }
1307
1308 if (sRSAKeyType == keyType) {
1309 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1310 } else {
1311 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1312 && (mDevice->common.module->module_api_version
1313 >= KEYMASTER_MODULE_API_VERSION_0_2);
1314 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001315 }
1316
Kenny Root655b9582013-04-04 08:37:42 -07001317 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1318 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001319 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Kenny Root655b9582013-04-04 08:37:42 -07001320
1321 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
1322 if (responseCode == NO_ERROR) {
1323 return responseCode;
1324 }
1325
1326 // If this is one of the legacy UID->UID mappings, use it.
1327 uid_t euid = get_keystore_euid(uid);
1328 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001329 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Kenny Root655b9582013-04-04 08:37:42 -07001330 responseCode = get(filepath8.string(), keyBlob, type, uid);
1331 if (responseCode == NO_ERROR) {
1332 return responseCode;
1333 }
1334 }
1335
1336 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001337 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001338 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001339 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001340 if (end[0] != '_' || end[1] == 0) {
1341 return KEY_NOT_FOUND;
1342 }
Kenny Root86b16e82013-09-09 11:15:54 -07001343 filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
1344 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001345 if (!hasGrant(filepath8.string(), uid)) {
1346 return responseCode;
1347 }
1348
1349 // It is a granted key. Try to load it.
1350 return get(filepath8.string(), keyBlob, type, uid);
1351 }
1352
1353 /**
1354 * Returns any existing UserState or creates it if it doesn't exist.
1355 */
1356 UserState* getUserState(uid_t uid) {
1357 uid_t userId = get_user_id(uid);
1358
1359 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1360 it != mMasterKeys.end(); it++) {
1361 UserState* state = *it;
1362 if (state->getUserId() == userId) {
1363 return state;
1364 }
1365 }
1366
1367 UserState* userState = new UserState(userId);
1368 if (!userState->initialize()) {
1369 /* There's not much we can do if initialization fails. Trying to
1370 * unlock the keystore for that user will fail as well, so any
1371 * subsequent request for this user will just return SYSTEM_ERROR.
1372 */
1373 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1374 }
1375 mMasterKeys.add(userState);
1376 return userState;
1377 }
1378
1379 /**
1380 * Returns NULL if the UserState doesn't already exist.
1381 */
1382 const UserState* getUserState(uid_t uid) const {
1383 uid_t userId = get_user_id(uid);
1384
1385 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1386 it != mMasterKeys.end(); it++) {
1387 UserState* state = *it;
1388 if (state->getUserId() == userId) {
1389 return state;
1390 }
1391 }
1392
1393 return NULL;
1394 }
1395
Kenny Roota91203b2012-02-15 15:00:46 -08001396private:
Kenny Root655b9582013-04-04 08:37:42 -07001397 static const char* sOldMasterKey;
1398 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001399 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001400 Entropy* mEntropy;
1401
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001402 keymaster1_device_t* mDevice;
1403 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001404
Kenny Root655b9582013-04-04 08:37:42 -07001405 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001406
Kenny Root655b9582013-04-04 08:37:42 -07001407 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001408
Kenny Root655b9582013-04-04 08:37:42 -07001409 typedef struct {
1410 uint32_t version;
1411 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001412
Kenny Root655b9582013-04-04 08:37:42 -07001413 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001414
Kenny Root655b9582013-04-04 08:37:42 -07001415 const grant_t* getGrant(const char* filename, uid_t uid) const {
1416 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1417 it != mGrants.end(); it++) {
1418 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001419 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001420 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001421 return grant;
1422 }
1423 }
Kenny Root70e3a862012-02-15 17:20:23 -08001424 return NULL;
1425 }
1426
Kenny Root822c3a92012-03-23 16:34:39 -07001427 /**
1428 * Upgrade code. This will upgrade the key from the current version
1429 * to whatever is newest.
1430 */
Kenny Root655b9582013-04-04 08:37:42 -07001431 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1432 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001433 bool updated = false;
1434 uint8_t version = oldVersion;
1435
1436 /* From V0 -> V1: All old types were unknown */
1437 if (version == 0) {
1438 ALOGV("upgrading to version 1 and setting type %d", type);
1439
1440 blob->setType(type);
1441 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001442 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001443 }
1444 version = 1;
1445 updated = true;
1446 }
1447
Kenny Rootf9119d62013-04-03 09:22:15 -07001448 /* From V1 -> V2: All old keys were encrypted */
1449 if (version == 1) {
1450 ALOGV("upgrading to version 2");
1451
1452 blob->setEncrypted(true);
1453 version = 2;
1454 updated = true;
1455 }
1456
Kenny Root822c3a92012-03-23 16:34:39 -07001457 /*
1458 * If we've updated, set the key blob to the right version
1459 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001460 */
Kenny Root822c3a92012-03-23 16:34:39 -07001461 if (updated) {
1462 ALOGV("updated and writing file %s", filename);
1463 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001464 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001465
1466 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001467 }
1468
1469 /**
1470 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1471 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1472 * Then it overwrites the original blob with the new blob
1473 * format that is returned from the keymaster.
1474 */
Kenny Root655b9582013-04-04 08:37:42 -07001475 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001476 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1477 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1478 if (b.get() == NULL) {
1479 ALOGE("Problem instantiating BIO");
1480 return SYSTEM_ERROR;
1481 }
1482
1483 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1484 if (pkey.get() == NULL) {
1485 ALOGE("Couldn't read old PEM file");
1486 return SYSTEM_ERROR;
1487 }
1488
1489 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1490 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1491 if (len < 0) {
1492 ALOGE("Couldn't measure PKCS#8 length");
1493 return SYSTEM_ERROR;
1494 }
1495
Kenny Root70c98892013-02-07 09:10:36 -08001496 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1497 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001498 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1499 ALOGE("Couldn't convert to PKCS#8");
1500 return SYSTEM_ERROR;
1501 }
1502
Kenny Rootf9119d62013-04-03 09:22:15 -07001503 ResponseCode rc = importKey(pkcs8key.get(), len, filename, uid,
1504 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001505 if (rc != NO_ERROR) {
1506 return rc;
1507 }
1508
Kenny Root655b9582013-04-04 08:37:42 -07001509 return get(filename, blob, TYPE_KEY_PAIR, uid);
1510 }
1511
1512 void readMetaData() {
1513 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1514 if (in < 0) {
1515 return;
1516 }
1517 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1518 if (fileLength != sizeof(mMetaData)) {
1519 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1520 sizeof(mMetaData));
1521 }
1522 close(in);
1523 }
1524
1525 void writeMetaData() {
1526 const char* tmpFileName = ".metadata.tmp";
1527 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1528 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1529 if (out < 0) {
1530 ALOGE("couldn't write metadata file: %s", strerror(errno));
1531 return;
1532 }
1533 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1534 if (fileLength != sizeof(mMetaData)) {
1535 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1536 sizeof(mMetaData));
1537 }
1538 close(out);
1539 rename(tmpFileName, sMetaDataFile);
1540 }
1541
1542 bool upgradeKeystore() {
1543 bool upgraded = false;
1544
1545 if (mMetaData.version == 0) {
1546 UserState* userState = getUserState(0);
1547
1548 // Initialize first so the directory is made.
1549 userState->initialize();
1550
1551 // Migrate the old .masterkey file to user 0.
1552 if (access(sOldMasterKey, R_OK) == 0) {
1553 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1554 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1555 return false;
1556 }
1557 }
1558
1559 // Initialize again in case we had a key.
1560 userState->initialize();
1561
1562 // Try to migrate existing keys.
1563 DIR* dir = opendir(".");
1564 if (!dir) {
1565 // Give up now; maybe we can upgrade later.
1566 ALOGE("couldn't open keystore's directory; something is wrong");
1567 return false;
1568 }
1569
1570 struct dirent* file;
1571 while ((file = readdir(dir)) != NULL) {
1572 // We only care about files.
1573 if (file->d_type != DT_REG) {
1574 continue;
1575 }
1576
1577 // Skip anything that starts with a "."
1578 if (file->d_name[0] == '.') {
1579 continue;
1580 }
1581
1582 // Find the current file's user.
1583 char* end;
1584 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1585 if (end[0] != '_' || end[1] == 0) {
1586 continue;
1587 }
1588 UserState* otherUser = getUserState(thisUid);
1589 if (otherUser->getUserId() != 0) {
1590 unlinkat(dirfd(dir), file->d_name, 0);
1591 }
1592
1593 // Rename the file into user directory.
1594 DIR* otherdir = opendir(otherUser->getUserDirName());
1595 if (otherdir == NULL) {
1596 ALOGW("couldn't open user directory for rename");
1597 continue;
1598 }
1599 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1600 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1601 }
1602 closedir(otherdir);
1603 }
1604 closedir(dir);
1605
1606 mMetaData.version = 1;
1607 upgraded = true;
1608 }
1609
1610 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001611 }
Kenny Roota91203b2012-02-15 15:00:46 -08001612};
1613
Kenny Root655b9582013-04-04 08:37:42 -07001614const char* KeyStore::sOldMasterKey = ".masterkey";
1615const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001616
Kenny Root1b0e3932013-09-05 13:06:32 -07001617const android::String16 KeyStore::sRSAKeyType("RSA");
1618
Kenny Root07438c82012-11-02 15:41:02 -07001619namespace android {
1620class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1621public:
1622 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001623 : mKeyStore(keyStore),
1624 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001625 {
Kenny Roota91203b2012-02-15 15:00:46 -08001626 }
Kenny Roota91203b2012-02-15 15:00:46 -08001627
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001628 void binderDied(const wp<IBinder>& who) {
1629 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1630 for (auto token: operations) {
1631 abort(token);
1632 }
Kenny Root822c3a92012-03-23 16:34:39 -07001633 }
Kenny Roota91203b2012-02-15 15:00:46 -08001634
Kenny Root07438c82012-11-02 15:41:02 -07001635 int32_t test() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001636 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001637 pid_t spid = IPCThreadState::self()->getCallingPid();
1638 if (!has_permission(callingUid, P_TEST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001639 ALOGW("permission denied for %d: test", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001640 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001641 }
Kenny Roota91203b2012-02-15 15:00:46 -08001642
Kenny Root655b9582013-04-04 08:37:42 -07001643 return mKeyStore->getState(callingUid);
Kenny Root298e7b12012-03-26 13:54:44 -07001644 }
1645
Kenny Root07438c82012-11-02 15:41:02 -07001646 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001647 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001648 pid_t spid = IPCThreadState::self()->getCallingPid();
1649 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001650 ALOGW("permission denied for %d: get", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001651 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001652 }
Kenny Root07438c82012-11-02 15:41:02 -07001653
Kenny Root07438c82012-11-02 15:41:02 -07001654 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001655 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001656
Kenny Root655b9582013-04-04 08:37:42 -07001657 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001658 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001659 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001660 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001661 *item = NULL;
1662 *itemLength = 0;
1663 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001664 }
Kenny Roota91203b2012-02-15 15:00:46 -08001665
Kenny Root07438c82012-11-02 15:41:02 -07001666 *item = (uint8_t*) malloc(keyBlob.getLength());
1667 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1668 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001669
Kenny Root07438c82012-11-02 15:41:02 -07001670 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001671 }
1672
Kenny Rootf9119d62013-04-03 09:22:15 -07001673 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1674 int32_t flags) {
Riley Spahneaabae92014-06-30 12:39:52 -07001675 pid_t spid = IPCThreadState::self()->getCallingPid();
Kenny Rootd38a0b02013-02-13 12:59:14 -08001676 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001677 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001678 ALOGW("permission denied for %d: insert", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001679 return ::PERMISSION_DENIED;
1680 }
Kenny Root07438c82012-11-02 15:41:02 -07001681
Kenny Rootf9119d62013-04-03 09:22:15 -07001682 State state = mKeyStore->getState(callingUid);
1683 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1684 ALOGD("calling get in state: %d", state);
1685 return state;
1686 }
1687
Kenny Root49468902013-03-19 13:41:33 -07001688 if (targetUid == -1) {
1689 targetUid = callingUid;
1690 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001691 return ::PERMISSION_DENIED;
1692 }
1693
Kenny Root07438c82012-11-02 15:41:02 -07001694 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001695 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001696
1697 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001698 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1699
Kenny Rootfa27d5b2013-10-15 09:01:08 -07001700 return mKeyStore->put(filename.string(), &keyBlob, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001701 }
1702
Kenny Root49468902013-03-19 13:41:33 -07001703 int32_t del(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001704 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001705 pid_t spid = IPCThreadState::self()->getCallingPid();
1706 if (!has_permission(callingUid, P_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001707 ALOGW("permission denied for %d: del", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001708 return ::PERMISSION_DENIED;
1709 }
Kenny Root70e3a862012-02-15 17:20:23 -08001710
Kenny Root49468902013-03-19 13:41:33 -07001711 if (targetUid == -1) {
1712 targetUid = callingUid;
1713 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001714 return ::PERMISSION_DENIED;
1715 }
1716
Kenny Root07438c82012-11-02 15:41:02 -07001717 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001718 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker17d68b92015-02-05 22:04:16 -08001719 return mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Root70e3a862012-02-15 17:20:23 -08001720 }
1721
Kenny Root49468902013-03-19 13:41:33 -07001722 int32_t exist(const String16& name, int targetUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001723 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001724 pid_t spid = IPCThreadState::self()->getCallingPid();
1725 if (!has_permission(callingUid, P_EXIST, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001726 ALOGW("permission denied for %d: exist", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001727 return ::PERMISSION_DENIED;
1728 }
Kenny Root70e3a862012-02-15 17:20:23 -08001729
Kenny Root49468902013-03-19 13:41:33 -07001730 if (targetUid == -1) {
1731 targetUid = callingUid;
1732 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001733 return ::PERMISSION_DENIED;
1734 }
1735
Kenny Root07438c82012-11-02 15:41:02 -07001736 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001737 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001738
Kenny Root655b9582013-04-04 08:37:42 -07001739 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001740 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1741 }
1742 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001743 }
1744
Kenny Root49468902013-03-19 13:41:33 -07001745 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001746 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001747 pid_t spid = IPCThreadState::self()->getCallingPid();
1748 if (!has_permission(callingUid, P_SAW, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001749 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001750 return ::PERMISSION_DENIED;
1751 }
Kenny Root70e3a862012-02-15 17:20:23 -08001752
Kenny Root49468902013-03-19 13:41:33 -07001753 if (targetUid == -1) {
1754 targetUid = callingUid;
1755 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001756 return ::PERMISSION_DENIED;
1757 }
1758
Kenny Root07438c82012-11-02 15:41:02 -07001759 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001760 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001761
Robin Lee4b84fdc2014-09-24 11:56:57 +01001762 if (mKeyStore->saw(filename, matches, targetUid) != ::NO_ERROR) {
1763 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001764 }
Kenny Root07438c82012-11-02 15:41:02 -07001765 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001766 }
1767
Kenny Root07438c82012-11-02 15:41:02 -07001768 int32_t reset() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001769 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001770 pid_t spid = IPCThreadState::self()->getCallingPid();
1771 if (!has_permission(callingUid, P_RESET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001772 ALOGW("permission denied for %d: reset", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001773 return ::PERMISSION_DENIED;
1774 }
1775
Robin Lee4b84fdc2014-09-24 11:56:57 +01001776 return mKeyStore->reset(callingUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001777 }
1778
Kenny Root07438c82012-11-02 15:41:02 -07001779 /*
1780 * Here is the history. To improve the security, the parameters to generate the
1781 * master key has been changed. To make a seamless transition, we update the
1782 * file using the same password when the user unlock it for the first time. If
1783 * any thing goes wrong during the transition, the new file will not overwrite
1784 * the old one. This avoids permanent damages of the existing data.
1785 */
1786 int32_t password(const String16& password) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001787 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001788 pid_t spid = IPCThreadState::self()->getCallingPid();
1789 if (!has_permission(callingUid, P_PASSWORD, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001790 ALOGW("permission denied for %d: password", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001791 return ::PERMISSION_DENIED;
1792 }
Kenny Root70e3a862012-02-15 17:20:23 -08001793
Kenny Root07438c82012-11-02 15:41:02 -07001794 const String8 password8(password);
Kenny Root70e3a862012-02-15 17:20:23 -08001795
Kenny Root655b9582013-04-04 08:37:42 -07001796 switch (mKeyStore->getState(callingUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001797 case ::STATE_UNINITIALIZED: {
1798 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001799 return mKeyStore->initializeUser(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001800 }
1801 case ::STATE_NO_ERROR: {
1802 // rewrite master key with new password.
Kenny Root655b9582013-04-04 08:37:42 -07001803 return mKeyStore->writeMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001804 }
1805 case ::STATE_LOCKED: {
1806 // read master key, decrypt with password, initialize mMasterKey*.
Kenny Root655b9582013-04-04 08:37:42 -07001807 return mKeyStore->readMasterKey(password8, callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001808 }
1809 }
1810 return ::SYSTEM_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001811 }
1812
Kenny Root07438c82012-11-02 15:41:02 -07001813 int32_t lock() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001814 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001815 pid_t spid = IPCThreadState::self()->getCallingPid();
1816 if (!has_permission(callingUid, P_LOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001817 ALOGW("permission denied for %d: lock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001818 return ::PERMISSION_DENIED;
1819 }
Kenny Root70e3a862012-02-15 17:20:23 -08001820
Kenny Root655b9582013-04-04 08:37:42 -07001821 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001822 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001823 ALOGD("calling lock in state: %d", state);
1824 return state;
1825 }
1826
Kenny Root655b9582013-04-04 08:37:42 -07001827 mKeyStore->lock(callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001828 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001829 }
1830
Kenny Root07438c82012-11-02 15:41:02 -07001831 int32_t unlock(const String16& pw) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001832 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001833 pid_t spid = IPCThreadState::self()->getCallingPid();
1834 if (!has_permission(callingUid, P_UNLOCK, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001835 ALOGW("permission denied for %d: unlock", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001836 return ::PERMISSION_DENIED;
1837 }
1838
Kenny Root655b9582013-04-04 08:37:42 -07001839 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001840 if (state != ::STATE_LOCKED) {
Kenny Root07438c82012-11-02 15:41:02 -07001841 ALOGD("calling unlock when not locked");
1842 return state;
1843 }
1844
1845 const String8 password8(pw);
1846 return password(pw);
Kenny Root70e3a862012-02-15 17:20:23 -08001847 }
1848
Kenny Root07438c82012-11-02 15:41:02 -07001849 int32_t zero() {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001850 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001851 pid_t spid = IPCThreadState::self()->getCallingPid();
1852 if (!has_permission(callingUid, P_ZERO, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001853 ALOGW("permission denied for %d: zero", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001854 return -1;
1855 }
Kenny Root70e3a862012-02-15 17:20:23 -08001856
Kenny Root655b9582013-04-04 08:37:42 -07001857 return mKeyStore->isEmpty(callingUid) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001858 }
1859
Kenny Root96427ba2013-08-16 14:02:41 -07001860 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1861 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001862 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07001863 pid_t spid = IPCThreadState::self()->getCallingPid();
1864 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08001865 ALOGW("permission denied for %d: generate", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07001866 return ::PERMISSION_DENIED;
1867 }
Kenny Root70e3a862012-02-15 17:20:23 -08001868
Kenny Root49468902013-03-19 13:41:33 -07001869 if (targetUid == -1) {
1870 targetUid = callingUid;
1871 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001872 return ::PERMISSION_DENIED;
1873 }
1874
Kenny Root655b9582013-04-04 08:37:42 -07001875 State state = mKeyStore->getState(callingUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07001876 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
1877 ALOGW("calling generate in state: %d", state);
Kenny Root07438c82012-11-02 15:41:02 -07001878 return state;
1879 }
Kenny Root70e3a862012-02-15 17:20:23 -08001880
Kenny Root07438c82012-11-02 15:41:02 -07001881 uint8_t* data;
1882 size_t dataLength;
1883 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001884 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001885
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001886 const keymaster1_device_t* device = mKeyStore->getDevice();
1887 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001888 if (device == NULL) {
1889 return ::SYSTEM_ERROR;
1890 }
1891
1892 if (device->generate_keypair == NULL) {
1893 return ::SYSTEM_ERROR;
1894 }
1895
Kenny Root17208e02013-09-04 13:56:03 -07001896 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001897 keymaster_dsa_keygen_params_t dsa_params;
1898 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001899
Kenny Root96427ba2013-08-16 14:02:41 -07001900 if (keySize == -1) {
1901 keySize = DSA_DEFAULT_KEY_SIZE;
1902 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1903 || keySize > DSA_MAX_KEY_SIZE) {
1904 ALOGI("invalid key size %d", keySize);
1905 return ::SYSTEM_ERROR;
1906 }
1907 dsa_params.key_size = keySize;
1908
1909 if (args->size() == 3) {
1910 sp<KeystoreArg> gArg = args->itemAt(0);
1911 sp<KeystoreArg> pArg = args->itemAt(1);
1912 sp<KeystoreArg> qArg = args->itemAt(2);
1913
1914 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1915 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1916 dsa_params.generator_len = gArg->size();
1917
1918 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1919 dsa_params.prime_p_len = pArg->size();
1920
1921 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1922 dsa_params.prime_q_len = qArg->size();
1923 } else {
1924 ALOGI("not all DSA parameters were read");
1925 return ::SYSTEM_ERROR;
1926 }
1927 } else if (args->size() != 0) {
1928 ALOGI("DSA args must be 3");
1929 return ::SYSTEM_ERROR;
1930 }
1931
Kenny Root1d448c02013-11-21 10:36:53 -08001932 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001933 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1934 } else {
1935 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001936 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1937 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001938 }
1939 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001940 keymaster_ec_keygen_params_t ec_params;
1941 memset(&ec_params, '\0', sizeof(ec_params));
1942
1943 if (keySize == -1) {
1944 keySize = EC_DEFAULT_KEY_SIZE;
1945 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1946 ALOGI("invalid key size %d", keySize);
1947 return ::SYSTEM_ERROR;
1948 }
1949 ec_params.field_size = keySize;
1950
Kenny Root1d448c02013-11-21 10:36:53 -08001951 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001952 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1953 } else {
1954 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001955 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001956 }
Kenny Root96427ba2013-08-16 14:02:41 -07001957 } else if (keyType == EVP_PKEY_RSA) {
1958 keymaster_rsa_keygen_params_t rsa_params;
1959 memset(&rsa_params, '\0', sizeof(rsa_params));
1960 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1961
1962 if (keySize == -1) {
1963 keySize = RSA_DEFAULT_KEY_SIZE;
1964 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1965 ALOGI("invalid key size %d", keySize);
1966 return ::SYSTEM_ERROR;
1967 }
1968 rsa_params.modulus_size = keySize;
1969
1970 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001971 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001972 return ::SYSTEM_ERROR;
1973 } else if (args->size() == 1) {
1974 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1975 if (pubExpBlob != NULL) {
1976 Unique_BIGNUM pubExpBn(
1977 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1978 pubExpBlob->size(), NULL));
1979 if (pubExpBn.get() == NULL) {
1980 ALOGI("Could not convert public exponent to BN");
1981 return ::SYSTEM_ERROR;
1982 }
1983 unsigned long pubExp = BN_get_word(pubExpBn.get());
1984 if (pubExp == 0xFFFFFFFFL) {
1985 ALOGI("cannot represent public exponent as a long value");
1986 return ::SYSTEM_ERROR;
1987 }
1988 rsa_params.public_exponent = pubExp;
1989 }
1990 }
1991
1992 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
1993 } else {
1994 ALOGW("Unsupported key type %d", keyType);
1995 rc = -1;
1996 }
1997
Kenny Root07438c82012-11-02 15:41:02 -07001998 if (rc) {
1999 return ::SYSTEM_ERROR;
2000 }
2001
Kenny Root655b9582013-04-04 08:37:42 -07002002 String8 name8(name);
2003 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002004
2005 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
2006 free(data);
2007
Kenny Rootee8068b2013-10-07 09:49:15 -07002008 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07002009 keyBlob.setFallback(isFallback);
2010
Kenny Root655b9582013-04-04 08:37:42 -07002011 return mKeyStore->put(filename.string(), &keyBlob, callingUid);
Kenny Root70e3a862012-02-15 17:20:23 -08002012 }
2013
Kenny Rootf9119d62013-04-03 09:22:15 -07002014 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2015 int32_t flags) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002016 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002017 pid_t spid = IPCThreadState::self()->getCallingPid();
2018 if (!has_permission(callingUid, P_INSERT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002019 ALOGW("permission denied for %d: import", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002020 return ::PERMISSION_DENIED;
2021 }
Kenny Root07438c82012-11-02 15:41:02 -07002022
Kenny Root49468902013-03-19 13:41:33 -07002023 if (targetUid == -1) {
2024 targetUid = callingUid;
2025 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002026 return ::PERMISSION_DENIED;
2027 }
2028
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002029 State state = mKeyStore->getState(targetUid);
Kenny Rootf9119d62013-04-03 09:22:15 -07002030 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002031 ALOGD("calling import in state: %d", state);
2032 return state;
2033 }
2034
2035 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002036 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002037
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002038 return mKeyStore->importKey(data, length, filename.string(), targetUid, flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002039 }
2040
Kenny Root07438c82012-11-02 15:41:02 -07002041 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2042 size_t* outLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002043 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002044 pid_t spid = IPCThreadState::self()->getCallingPid();
2045 if (!has_permission(callingUid, P_SIGN, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002046 ALOGW("permission denied for %d: saw", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002047 return ::PERMISSION_DENIED;
2048 }
Kenny Root07438c82012-11-02 15:41:02 -07002049
Kenny Root07438c82012-11-02 15:41:02 -07002050 Blob keyBlob;
2051 String8 name8(name);
2052
Kenny Rootd38a0b02013-02-13 12:59:14 -08002053 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002054 int rc;
2055
Kenny Root655b9582013-04-04 08:37:42 -07002056 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002057 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002058 if (responseCode != ::NO_ERROR) {
2059 return responseCode;
2060 }
2061
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002062 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002063 if (device == NULL) {
2064 ALOGE("no keymaster device; cannot sign");
2065 return ::SYSTEM_ERROR;
2066 }
2067
2068 if (device->sign_data == NULL) {
2069 ALOGE("device doesn't implement signing");
2070 return ::SYSTEM_ERROR;
2071 }
2072
2073 keymaster_rsa_sign_params_t params;
2074 params.digest_type = DIGEST_NONE;
2075 params.padding_type = PADDING_NONE;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002076 rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2077 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002078 if (rc) {
2079 ALOGW("device couldn't sign data");
2080 return ::SYSTEM_ERROR;
2081 }
2082
2083 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002084 }
2085
Kenny Root07438c82012-11-02 15:41:02 -07002086 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2087 const uint8_t* signature, size_t signatureLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002088 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002089 pid_t spid = IPCThreadState::self()->getCallingPid();
2090 if (!has_permission(callingUid, P_VERIFY, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002091 ALOGW("permission denied for %d: verify", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002092 return ::PERMISSION_DENIED;
2093 }
Kenny Root70e3a862012-02-15 17:20:23 -08002094
Kenny Root655b9582013-04-04 08:37:42 -07002095 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002096 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002097 ALOGD("calling verify in state: %d", state);
2098 return state;
2099 }
Kenny Root70e3a862012-02-15 17:20:23 -08002100
Kenny Root07438c82012-11-02 15:41:02 -07002101 Blob keyBlob;
2102 String8 name8(name);
2103 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002104
Kenny Root655b9582013-04-04 08:37:42 -07002105 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002106 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002107 if (responseCode != ::NO_ERROR) {
2108 return responseCode;
2109 }
Kenny Root70e3a862012-02-15 17:20:23 -08002110
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002111 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002112 if (device == NULL) {
2113 return ::SYSTEM_ERROR;
2114 }
Kenny Root70e3a862012-02-15 17:20:23 -08002115
Kenny Root07438c82012-11-02 15:41:02 -07002116 if (device->verify_data == NULL) {
2117 return ::SYSTEM_ERROR;
2118 }
Kenny Root70e3a862012-02-15 17:20:23 -08002119
Kenny Root07438c82012-11-02 15:41:02 -07002120 keymaster_rsa_sign_params_t params;
2121 params.digest_type = DIGEST_NONE;
2122 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002123
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002124 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2125 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002126 if (rc) {
2127 return ::SYSTEM_ERROR;
2128 } else {
2129 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002130 }
2131 }
Kenny Root07438c82012-11-02 15:41:02 -07002132
2133 /*
2134 * TODO: The abstraction between things stored in hardware and regular blobs
2135 * of data stored on the filesystem should be moved down to keystore itself.
2136 * Unfortunately the Java code that calls this has naming conventions that it
2137 * knows about. Ideally keystore shouldn't be used to store random blobs of
2138 * data.
2139 *
2140 * Until that happens, it's necessary to have a separate "get_pubkey" and
2141 * "del_key" since the Java code doesn't really communicate what it's
2142 * intentions are.
2143 */
2144 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002145 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002146 pid_t spid = IPCThreadState::self()->getCallingPid();
2147 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002148 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002149 return ::PERMISSION_DENIED;
2150 }
Kenny Root07438c82012-11-02 15:41:02 -07002151
Kenny Root07438c82012-11-02 15:41:02 -07002152 Blob keyBlob;
2153 String8 name8(name);
2154
Kenny Rootd38a0b02013-02-13 12:59:14 -08002155 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002156
Kenny Root655b9582013-04-04 08:37:42 -07002157 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002158 TYPE_KEY_PAIR);
2159 if (responseCode != ::NO_ERROR) {
2160 return responseCode;
2161 }
2162
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002163 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002164 if (device == NULL) {
2165 return ::SYSTEM_ERROR;
2166 }
2167
2168 if (device->get_keypair_public == NULL) {
2169 ALOGE("device has no get_keypair_public implementation!");
2170 return ::SYSTEM_ERROR;
2171 }
2172
Kenny Root17208e02013-09-04 13:56:03 -07002173 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002174 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2175 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002176 if (rc) {
2177 return ::SYSTEM_ERROR;
2178 }
2179
2180 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002181 }
Kenny Root07438c82012-11-02 15:41:02 -07002182
Kenny Root49468902013-03-19 13:41:33 -07002183 int32_t del_key(const String16& name, int targetUid) {
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_DELETE, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002187 ALOGW("permission denied for %d: del_key", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002188 return ::PERMISSION_DENIED;
2189 }
Kenny Root07438c82012-11-02 15:41:02 -07002190
Kenny Root49468902013-03-19 13:41:33 -07002191 if (targetUid == -1) {
2192 targetUid = callingUid;
2193 } else if (!is_granted_to(callingUid, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08002194 return ::PERMISSION_DENIED;
2195 }
2196
Kenny Root07438c82012-11-02 15:41:02 -07002197 String8 name8(name);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002198 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Robin Lee4b84fdc2014-09-24 11:56:57 +01002199 return mKeyStore->del(filename.string(), ::TYPE_KEY_PAIR, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002200 }
2201
2202 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002203 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002204 pid_t spid = IPCThreadState::self()->getCallingPid();
2205 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002206 ALOGW("permission denied for %d: grant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002207 return ::PERMISSION_DENIED;
2208 }
Kenny Root07438c82012-11-02 15:41:02 -07002209
Kenny Root655b9582013-04-04 08:37:42 -07002210 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002211 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002212 ALOGD("calling grant in state: %d", state);
2213 return state;
2214 }
2215
2216 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002217 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002218
Kenny Root655b9582013-04-04 08:37:42 -07002219 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002220 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2221 }
2222
Kenny Root655b9582013-04-04 08:37:42 -07002223 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002224 return ::NO_ERROR;
2225 }
2226
2227 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002228 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002229 pid_t spid = IPCThreadState::self()->getCallingPid();
2230 if (!has_permission(callingUid, P_GRANT, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002231 ALOGW("permission denied for %d: ungrant", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002232 return ::PERMISSION_DENIED;
2233 }
Kenny Root07438c82012-11-02 15:41:02 -07002234
Kenny Root655b9582013-04-04 08:37:42 -07002235 State state = mKeyStore->getState(callingUid);
Kenny Root9d45d1c2013-02-14 10:32:30 -08002236 if (!isKeystoreUnlocked(state)) {
Kenny Root07438c82012-11-02 15:41:02 -07002237 ALOGD("calling ungrant in state: %d", state);
2238 return state;
2239 }
2240
2241 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002242 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002243
Kenny Root655b9582013-04-04 08:37:42 -07002244 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002245 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2246 }
2247
Kenny Root655b9582013-04-04 08:37:42 -07002248 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002249 }
2250
2251 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002252 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002253 pid_t spid = IPCThreadState::self()->getCallingPid();
2254 if (!has_permission(callingUid, P_GET, spid)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002255 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002256 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002257 }
Kenny Root07438c82012-11-02 15:41:02 -07002258
2259 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002260 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002261
Kenny Root655b9582013-04-04 08:37:42 -07002262 if (access(filename.string(), R_OK) == -1) {
2263 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002264 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002265 }
2266
Kenny Root655b9582013-04-04 08:37:42 -07002267 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002268 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002269 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002270 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002271 }
2272
2273 struct stat s;
2274 int ret = fstat(fd, &s);
2275 close(fd);
2276 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002277 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002278 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002279 }
2280
Kenny Root36a9e232013-02-04 14:24:15 -08002281 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002282 }
2283
Kenny Rootd53bc922013-03-21 14:10:15 -07002284 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2285 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002286 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002287 pid_t spid = IPCThreadState::self()->getCallingPid();
2288 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002289 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002290 return -1L;
2291 }
2292
Kenny Root655b9582013-04-04 08:37:42 -07002293 State state = mKeyStore->getState(callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002294 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002295 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002296 return state;
2297 }
2298
Kenny Rootd53bc922013-03-21 14:10:15 -07002299 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2300 srcUid = callingUid;
2301 } else if (!is_granted_to(callingUid, srcUid)) {
2302 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002303 return ::PERMISSION_DENIED;
2304 }
2305
Kenny Rootd53bc922013-03-21 14:10:15 -07002306 if (destUid == -1) {
2307 destUid = callingUid;
2308 }
2309
2310 if (srcUid != destUid) {
2311 if (static_cast<uid_t>(srcUid) != callingUid) {
2312 ALOGD("can only duplicate from caller to other or to same uid: "
2313 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2314 return ::PERMISSION_DENIED;
2315 }
2316
2317 if (!is_granted_to(callingUid, destUid)) {
2318 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2319 return ::PERMISSION_DENIED;
2320 }
2321 }
2322
2323 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002324 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002325
Kenny Rootd53bc922013-03-21 14:10:15 -07002326 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002327 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002328
Kenny Root655b9582013-04-04 08:37:42 -07002329 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2330 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002331 return ::SYSTEM_ERROR;
2332 }
2333
Kenny Rootd53bc922013-03-21 14:10:15 -07002334 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002335 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002336 srcUid);
Kenny Rootd53bc922013-03-21 14:10:15 -07002337 if (responseCode != ::NO_ERROR) {
2338 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002339 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002340
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002341 return mKeyStore->put(targetFile.string(), &keyBlob, destUid);
Kenny Root02254072013-03-20 11:48:19 -07002342 }
2343
Kenny Root1b0e3932013-09-05 13:06:32 -07002344 int32_t is_hardware_backed(const String16& keyType) {
2345 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002346 }
2347
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002348 int32_t clear_uid(int64_t targetUid64) {
2349 uid_t targetUid = static_cast<uid_t>(targetUid64);
Kenny Roota9bb5492013-04-01 16:29:11 -07002350 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002351 pid_t spid = IPCThreadState::self()->getCallingPid();
2352 if (!has_permission(callingUid, P_CLEAR_UID, spid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002353 ALOGW("permission denied for %d: clear_uid", callingUid);
2354 return ::PERMISSION_DENIED;
2355 }
2356
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002357 if (targetUid64 == -1) {
2358 targetUid = callingUid;
Kenny Root007cb232014-07-30 16:59:42 -07002359 } else if (!is_self_or_system(callingUid, targetUid)) {
2360 ALOGW("permission denied for %d: clear_uid %d", callingUid, targetUid);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002361 return ::PERMISSION_DENIED;
2362 }
2363
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002364 const keymaster1_device_t* device = mKeyStore->getDevice();
Kenny Roota9bb5492013-04-01 16:29:11 -07002365 if (device == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07002366 ALOGW("can't get keymaster device");
Kenny Roota9bb5492013-04-01 16:29:11 -07002367 return ::SYSTEM_ERROR;
2368 }
2369
Robin Lee4b84fdc2014-09-24 11:56:57 +01002370 String8 prefix = String8::format("%u_", targetUid);
2371 Vector<String16> aliases;
2372 if (mKeyStore->saw(prefix, &aliases, targetUid) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002373 return ::SYSTEM_ERROR;
2374 }
2375
Robin Lee4b84fdc2014-09-24 11:56:57 +01002376 for (uint32_t i = 0; i < aliases.size(); i++) {
2377 String8 name8(aliases[i]);
2378 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
2379 mKeyStore->del(filename.string(), ::TYPE_ANY, targetUid);
Kenny Roota9bb5492013-04-01 16:29:11 -07002380 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002381 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002382 }
2383
Robin Lee4b84fdc2014-09-24 11:56:57 +01002384 int32_t reset_uid(int32_t targetUid) {
Robin Lee4e865752014-08-19 17:37:55 +01002385 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2386 pid_t spid = IPCThreadState::self()->getCallingPid();
Robin Lee4b84fdc2014-09-24 11:56:57 +01002387
Robin Lee4e865752014-08-19 17:37:55 +01002388 if (!has_permission(callingUid, P_RESET_UID, spid)) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01002389 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002390 return ::PERMISSION_DENIED;
2391 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002392 if (!is_self_or_system(callingUid, targetUid)) {
2393 ALOGW("permission denied for %d: reset_uid %d", callingUid, targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002394 return ::PERMISSION_DENIED;
2395 }
2396
Robin Lee4b84fdc2014-09-24 11:56:57 +01002397 return mKeyStore->reset(targetUid) ? ::NO_ERROR : ::SYSTEM_ERROR;
Robin Lee4e865752014-08-19 17:37:55 +01002398 }
2399
2400 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
2401 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2402 pid_t spid = IPCThreadState::self()->getCallingPid();
2403 if (!has_permission(callingUid, P_SYNC_UID, spid)) {
2404 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2405 return ::PERMISSION_DENIED;
2406 }
2407 if (callingUid != AID_SYSTEM) {
2408 ALOGW("permission denied for %d: sync_uid %d -> %d", callingUid, sourceUid, targetUid);
2409 return ::PERMISSION_DENIED;
2410 }
2411 if (sourceUid == targetUid) {
2412 return ::SYSTEM_ERROR;
2413 }
2414
2415 // Initialise user keystore with existing master key held in-memory
2416 return mKeyStore->copyMasterKey(sourceUid, targetUid);
2417 }
2418
2419 int32_t password_uid(const String16& pw, int32_t targetUid) {
2420 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2421 pid_t spid = IPCThreadState::self()->getCallingPid();
2422 if (!has_permission(callingUid, P_PASSWORD_UID, spid)) {
2423 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2424 return ::PERMISSION_DENIED;
2425 }
2426 if (callingUid != AID_SYSTEM) {
2427 ALOGW("permission denied for %d: password_uid %d", callingUid, targetUid);
2428 return ::PERMISSION_DENIED;
2429 }
2430
2431 const String8 password8(pw);
2432
2433 switch (mKeyStore->getState(targetUid)) {
2434 case ::STATE_UNINITIALIZED: {
2435 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
2436 return mKeyStore->initializeUser(password8, targetUid);
2437 }
2438 case ::STATE_NO_ERROR: {
2439 // rewrite master key with new password.
2440 return mKeyStore->writeMasterKey(password8, targetUid);
2441 }
2442 case ::STATE_LOCKED: {
2443 // read master key, decrypt with password, initialize mMasterKey*.
2444 return mKeyStore->readMasterKey(password8, targetUid);
2445 }
2446 }
2447 return ::SYSTEM_ERROR;
2448 }
2449
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002450 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2451 const keymaster1_device_t* device = mKeyStore->getDevice();
2452 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2453 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2454 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2455 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2456 device->add_rng_entropy != NULL) {
2457 devResult = device->add_rng_entropy(device, data, dataLength);
2458 }
2459 if (fallback->add_rng_entropy) {
2460 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2461 }
2462 if (devResult) {
2463 return devResult;
2464 }
2465 if (fallbackResult) {
2466 return fallbackResult;
2467 }
2468 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002469 }
2470
Chad Brubaker17d68b92015-02-05 22:04:16 -08002471 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002472 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2473 KeyCharacteristics* outCharacteristics) {
Chad Brubaker17d68b92015-02-05 22:04:16 -08002474 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2475 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2476 if (!has_permission(callingUid, P_INSERT, callingPid)) {
2477 ALOGW("permission denied for %d: generateKey", callingUid);
2478 return ::PERMISSION_DENIED;
2479 }
2480
2481 State state = mKeyStore->getState(callingUid);
2482 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
2483 ALOGW("calling generate in state: %d", state);
2484 return state;
2485 }
2486
2487 if (uid == -1) {
2488 uid = callingUid;
2489 } else if (!is_granted_to(callingUid, uid)) {
2490 return ::PERMISSION_DENIED;
2491 }
2492
Chad Brubaker17d68b92015-02-05 22:04:16 -08002493 int rc = KM_ERROR_UNIMPLEMENTED;
2494 bool isFallback = false;
2495 keymaster_key_blob_t blob;
2496 keymaster_key_characteristics_t *out = NULL;
2497
2498 const keymaster1_device_t* device = mKeyStore->getDevice();
2499 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2500 if (device == NULL) {
2501 return ::SYSTEM_ERROR;
2502 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002503 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002504 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2505 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002506 if (!entropy) {
2507 rc = KM_ERROR_OK;
2508 } else if (device->add_rng_entropy) {
2509 rc = device->add_rng_entropy(device, entropy, entropyLength);
2510 } else {
2511 rc = KM_ERROR_UNIMPLEMENTED;
2512 }
2513 if (rc == KM_ERROR_OK) {
2514 rc = device->generate_key(device, params.params.data(), params.params.size(),
2515 &blob, &out);
2516 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002517 }
2518 // If the HW device didn't support generate_key or generate_key failed
2519 // fall back to the software implementation.
2520 if (rc && fallback->generate_key != NULL) {
2521 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002522 if (!entropy) {
2523 rc = KM_ERROR_OK;
2524 } else if (fallback->add_rng_entropy) {
2525 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2526 } else {
2527 rc = KM_ERROR_UNIMPLEMENTED;
2528 }
2529 if (rc == KM_ERROR_OK) {
2530 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2531 &blob,
2532 &out);
2533 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002534 }
2535
2536 if (out) {
2537 if (outCharacteristics) {
2538 outCharacteristics->characteristics = *out;
2539 } else {
2540 keymaster_free_characteristics(out);
2541 }
2542 free(out);
2543 }
2544
2545 if (rc) {
2546 return rc;
2547 }
2548
2549 String8 name8(name);
2550 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2551
2552 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2553 keyBlob.setFallback(isFallback);
2554 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2555
2556 free(const_cast<uint8_t*>(blob.key_material));
2557
2558 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002559 }
2560
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002561 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002562 const keymaster_blob_t* clientId,
2563 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002564 KeyCharacteristics* outCharacteristics) {
2565
2566 if (!outCharacteristics) {
2567 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2568 }
2569
2570 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2571
2572 Blob keyBlob;
2573 String8 name8(name);
2574 int rc;
2575
2576 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2577 TYPE_KEYMASTER_10);
2578 if (responseCode != ::NO_ERROR) {
2579 return responseCode;
2580 }
2581 keymaster_key_blob_t key;
2582 key.key_material_size = keyBlob.getLength();
2583 key.key_material = keyBlob.getValue();
2584 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2585 keymaster_key_characteristics_t *out = NULL;
2586 if (!dev->get_key_characteristics) {
2587 ALOGW("device does not implement get_key_characteristics");
2588 return KM_ERROR_UNIMPLEMENTED;
2589 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002590 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002591 if (out) {
2592 outCharacteristics->characteristics = *out;
2593 free(out);
2594 }
2595 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002596 }
2597
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002598 int32_t importKey(const String16& name, const KeymasterArguments& params,
2599 keymaster_key_format_t format, const uint8_t *keyData,
2600 size_t keyLength, int uid, int flags,
2601 KeyCharacteristics* outCharacteristics) {
2602 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2603 pid_t spid = IPCThreadState::self()->getCallingPid();
2604 if (!has_permission(callingUid, P_INSERT, spid)) {
2605 ALOGW("permission denied for %d: importKey", callingUid);
2606 return ::PERMISSION_DENIED;
2607 }
2608
2609 State state = mKeyStore->getState(callingUid);
2610 if ((flags & KEYSTORE_FLAG_ENCRYPTED) && !isKeystoreUnlocked(state)) {
2611 ALOGW("calling importKey in state: %d", state);
2612 return state;
2613 }
2614
2615 if (uid == -1) {
2616 uid = callingUid;
2617 } else if (!is_granted_to(callingUid, uid)) {
2618 ALOGW("not granted to %d %d", callingUid, uid);
2619 return ::PERMISSION_DENIED;
2620 }
2621
2622 int rc = KM_ERROR_UNIMPLEMENTED;
2623 bool isFallback = false;
2624 keymaster_key_blob_t blob;
2625 keymaster_key_characteristics_t *out = NULL;
2626
2627 const keymaster1_device_t* device = mKeyStore->getDevice();
2628 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2629 if (device == NULL) {
2630 return ::SYSTEM_ERROR;
2631 }
2632 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2633 device->import_key != NULL) {
2634 rc = device->import_key(device, params.params.data(), params.params.size(),
2635 format, keyData, keyLength, &blob, &out);
2636 }
2637 if (rc && fallback->import_key != NULL) {
2638 isFallback = true;
2639 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2640 format, keyData, keyLength, &blob, &out);
2641 }
2642 if (out) {
2643 if (outCharacteristics) {
2644 outCharacteristics->characteristics = *out;
2645 } else {
2646 keymaster_free_characteristics(out);
2647 }
2648 free(out);
2649 }
2650 if (rc) {
2651 return rc;
2652 }
2653
2654 String8 name8(name);
2655 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2656
2657 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2658 keyBlob.setFallback(isFallback);
2659 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2660
2661 free((void*) blob.key_material);
2662
2663 return mKeyStore->put(filename.string(), &keyBlob, uid);
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002664 }
2665
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002666 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002667 const keymaster_blob_t* clientId,
2668 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002669
2670 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2671
2672 Blob keyBlob;
2673 String8 name8(name);
2674 int rc;
2675
2676 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2677 TYPE_KEYMASTER_10);
2678 if (responseCode != ::NO_ERROR) {
2679 result->resultCode = responseCode;
2680 return;
2681 }
2682 keymaster_key_blob_t key;
2683 key.key_material_size = keyBlob.getLength();
2684 key.key_material = keyBlob.getValue();
2685 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2686 if (!dev->export_key) {
2687 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2688 return;
2689 }
2690 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002691 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002692 &ptr, &result->dataLength);
2693 result->exportData.reset(ptr);
2694 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002695 }
2696
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002697 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002698 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2699 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002700 if (!result || !outParams) {
2701 ALOGE("Unexpected null arguments to begin()");
2702 return;
2703 }
2704 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2705 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2706 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2707 result->resultCode = ::PERMISSION_DENIED;
2708 return;
2709 }
2710 Blob keyBlob;
2711 String8 name8(name);
2712 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2713 TYPE_KEYMASTER_10);
2714 if (responseCode != ::NO_ERROR) {
2715 result->resultCode = responseCode;
2716 return;
2717 }
2718 keymaster_key_blob_t key;
2719 key.key_material_size = keyBlob.getLength();
2720 key.key_material = keyBlob.getValue();
2721 keymaster_key_param_t* out;
2722 size_t outSize;
2723 keymaster_operation_handle_t handle;
2724 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002725 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
2726 // Add entropy to the device first.
2727 if (entropy) {
2728 if (dev->add_rng_entropy) {
2729 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2730 } else {
2731 err = KM_ERROR_UNIMPLEMENTED;
2732 }
2733 if (err) {
2734 result->resultCode = err;
2735 return;
2736 }
2737 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002738 // TODO: Check authorization.
Chad Brubaker154d7692015-03-27 13:59:31 -07002739 err = dev->begin(dev, purpose, &key, params.params.data(), params.params.size(), &out,
2740 &outSize, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002741
2742 // If there are too many operations abort the oldest operation that was
2743 // started as pruneable and try again.
2744 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2745 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2746 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2747 if (abort(oldest) != ::NO_ERROR) {
2748 break;
2749 }
2750 err = dev->begin(dev, purpose, &key, params.params.data(),
2751 params.params.size(), &out, &outSize,
2752 &handle);
2753 }
2754 if (err) {
2755 result->resultCode = err;
2756 return;
2757 }
2758 if (out) {
2759 outParams->params.assign(out, out + outSize);
2760 free(out);
2761 }
2762
2763 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken, pruneable);
2764 result->resultCode = ::NO_ERROR;
2765 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002766 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002767 }
2768
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002769 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2770 size_t dataLength, OperationResult* result) {
2771 const keymaster1_device_t* dev;
2772 keymaster_operation_handle_t handle;
2773 if (!mOperationMap.getOperation(token, &handle, &dev)) {
2774 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2775 return;
2776 }
2777 uint8_t* output_buf = NULL;
2778 size_t output_length = 0;
2779 size_t consumed = 0;
2780 // TODO: Check authorization.
2781 keymaster_error_t err = dev->update(dev, handle, params.params.data(),
2782 params.params.size(), data, dataLength,
2783 &consumed, &output_buf, &output_length);
2784 result->data.reset(output_buf);
2785 result->dataLength = output_length;
2786 result->inputConsumed = consumed;
2787 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002788 }
2789
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002790 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2791 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
2792 const keymaster1_device_t* dev;
2793 keymaster_operation_handle_t handle;
2794 if (!mOperationMap.getOperation(token, &handle, &dev)) {
2795 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2796 return;
2797 }
2798 uint8_t* output_buf = NULL;
2799 size_t output_length = 0;
2800 // TODO: Check authorization.
2801 keymaster_error_t err = dev->finish(dev, handle, params.params.data(),
2802 params.params.size(), signature, signatureLength,
2803 &output_buf, &output_length);
2804 // Remove the operation regardless of the result
2805 mOperationMap.removeOperation(token);
2806 result->data.reset(output_buf);
2807 result->dataLength = output_length;
2808 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002809 }
2810
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002811 int32_t abort(const sp<IBinder>& token) {
2812 const keymaster1_device_t* dev;
2813 keymaster_operation_handle_t handle;
2814 if (!mOperationMap.getOperation(token, &handle, &dev)) {
2815 return KM_ERROR_INVALID_OPERATION_HANDLE;
2816 }
2817 mOperationMap.removeOperation(token);
2818 if (!dev->abort) {
2819 return KM_ERROR_UNIMPLEMENTED;
2820 }
2821 int32_t rc = dev->abort(dev, handle);
2822 if (rc) {
2823 return rc;
2824 }
2825 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002826 }
2827
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002828 bool isOperationAuthorized(const sp<IBinder>& token) {
2829 const keymaster1_device_t* dev;
2830 keymaster_operation_handle_t handle;
2831 if(!mOperationMap.getOperation(token, &handle, &dev)) {
2832 return false;
2833 }
2834 // TODO: Check authorization.
2835 return true;
2836 }
2837
2838 int32_t addAuthToken(const uint8_t* /*token*/, size_t /*length*/) {
2839 return KM_ERROR_UNIMPLEMENTED;
2840 }
2841
Kenny Root07438c82012-11-02 15:41:02 -07002842private:
Kenny Root9d45d1c2013-02-14 10:32:30 -08002843 inline bool isKeystoreUnlocked(State state) {
2844 switch (state) {
2845 case ::STATE_NO_ERROR:
2846 return true;
2847 case ::STATE_UNINITIALIZED:
2848 case ::STATE_LOCKED:
2849 return false;
2850 }
2851 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002852 }
2853
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002854 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002855 const int32_t device_api = device->common.module->module_api_version;
2856 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2857 switch (keyType) {
2858 case TYPE_RSA:
2859 case TYPE_DSA:
2860 case TYPE_EC:
2861 return true;
2862 default:
2863 return false;
2864 }
2865 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2866 switch (keyType) {
2867 case TYPE_RSA:
2868 return true;
2869 case TYPE_DSA:
2870 return device->flags & KEYMASTER_SUPPORTS_DSA;
2871 case TYPE_EC:
2872 return device->flags & KEYMASTER_SUPPORTS_EC;
2873 default:
2874 return false;
2875 }
2876 } else {
2877 return keyType == TYPE_RSA;
2878 }
2879 }
2880
Kenny Root07438c82012-11-02 15:41:02 -07002881 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002882 OperationMap mOperationMap;
Kenny Root07438c82012-11-02 15:41:02 -07002883};
2884
2885}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08002886
2887int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08002888 if (argc < 2) {
2889 ALOGE("A directory must be specified!");
2890 return 1;
2891 }
2892 if (chdir(argv[1]) == -1) {
2893 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
2894 return 1;
2895 }
2896
2897 Entropy entropy;
2898 if (!entropy.open()) {
2899 return 1;
2900 }
Kenny Root70e3a862012-02-15 17:20:23 -08002901
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07002902 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08002903 if (keymaster_device_initialize(&dev)) {
2904 ALOGE("keystore keymaster could not be initialized; exiting");
2905 return 1;
2906 }
2907
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002908 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002909 if (fallback_keymaster_device_initialize(&fallback)) {
2910 ALOGE("software keymaster could not be initialized; exiting");
2911 return 1;
2912 }
2913
Riley Spahneaabae92014-06-30 12:39:52 -07002914 ks_is_selinux_enabled = is_selinux_enabled();
2915 if (ks_is_selinux_enabled) {
2916 union selinux_callback cb;
2917 cb.func_log = selinux_log_callback;
2918 selinux_set_callback(SELINUX_CB_LOG, cb);
2919 if (getcon(&tctx) != 0) {
2920 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
2921 return -1;
2922 }
2923 } else {
2924 ALOGI("SELinux: Keystore SELinux is disabled.\n");
2925 }
2926
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002927 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07002928 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07002929 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
2930 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
2931 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
2932 if (ret != android::OK) {
2933 ALOGE("Couldn't register binder service!");
2934 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08002935 }
Kenny Root07438c82012-11-02 15:41:02 -07002936
2937 /*
2938 * We're the only thread in existence, so we're just going to process
2939 * Binder transaction as a single-threaded program.
2940 */
2941 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08002942
2943 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08002944 return 1;
2945}