blob: b23770f1034f2c2075fabbb0a444de345a776d6d [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 Willden80843db2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Chad Brubaker67d2a502015-03-11 17:21:18 +000046#include <keymaster/soft_keymaster_device.h>
Shawn Willden04006752015-04-30 11:12:33 -060047#include <keymaster/soft_keymaster_logger.h>
48#include <keymaster/softkeymaster.h>
Kenny Root17208e02013-09-04 13:56:03 -070049
Kenny Root26cfc082013-09-11 14:38:56 -070050#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070052#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080053
Kenny Root07438c82012-11-02 15:41:02 -070054#include <keystore/IKeystoreService.h>
55#include <binder/IPCThreadState.h>
56#include <binder/IServiceManager.h>
57
Kenny Roota91203b2012-02-15 15:00:46 -080058#include <cutils/log.h>
59#include <cutils/sockets.h>
60#include <private/android_filesystem_config.h>
61
Kenny Root07438c82012-11-02 15:41:02 -070062#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080063
Riley Spahneaabae92014-06-30 12:39:52 -070064#include <selinux/android.h>
65
Chad Brubakerd80c7b42015-03-31 11:04:28 -070066#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070067#include "defaults.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080068#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070069
Kenny Roota91203b2012-02-15 15:00:46 -080070/* KeyStore is a secured storage for key-value pairs. In this implementation,
71 * each file stores one key-value pair. Keys are encoded in file names, and
72 * values are encrypted with checksums. The encryption key is protected by a
73 * user-defined password. To keep things simple, buffers are always larger than
74 * the maximum space we needed, so boundary checks on buffers are omitted. */
75
76#define KEY_SIZE ((NAME_MAX - 15) / 2)
77#define VALUE_SIZE 32768
78#define PASSWORD_SIZE VALUE_SIZE
79
Kenny Root822c3a92012-03-23 16:34:39 -070080
Kenny Root96427ba2013-08-16 14:02:41 -070081struct BIGNUM_Delete {
82 void operator()(BIGNUM* p) const {
83 BN_free(p);
84 }
85};
86typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
87
Kenny Root822c3a92012-03-23 16:34:39 -070088struct BIO_Delete {
89 void operator()(BIO* p) const {
90 BIO_free(p);
91 }
92};
93typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
94
95struct EVP_PKEY_Delete {
96 void operator()(EVP_PKEY* p) const {
97 EVP_PKEY_free(p);
98 }
99};
100typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
101
102struct PKCS8_PRIV_KEY_INFO_Delete {
103 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
104 PKCS8_PRIV_KEY_INFO_free(p);
105 }
106};
107typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
108
Chad Brubakerbd07a232015-06-01 10:44:27 -0700109static int keymaster_device_initialize(keymaster1_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800110 int rc;
111
112 const hw_module_t* mod;
Chad Brubakerbd07a232015-06-01 10:44:27 -0700113 keymaster::SoftKeymasterDevice* softkeymaster = NULL;
Kenny Root70e3a862012-02-15 17:20:23 -0800114 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
115 if (rc) {
116 ALOGE("could not find any keystore module");
117 goto out;
118 }
119
Chad Brubakerbd07a232015-06-01 10:44:27 -0700120 rc = mod->methods->open(mod, KEYSTORE_KEYMASTER, reinterpret_cast<struct hw_device_t**>(dev));
Kenny Root70e3a862012-02-15 17:20:23 -0800121 if (rc) {
122 ALOGE("could not open keymaster device in %s (%s)",
123 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
124 goto out;
125 }
126
Chad Brubakerbd07a232015-06-01 10:44:27 -0700127 // Wrap older hardware modules with a softkeymaster adapter.
128 if ((*dev)->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0) {
129 return 0;
130 }
131 softkeymaster =
132 new keymaster::SoftKeymasterDevice(reinterpret_cast<keymaster0_device_t*>(*dev));
133 *dev = softkeymaster->keymaster_device();
Kenny Root70e3a862012-02-15 17:20:23 -0800134 return 0;
135
136out:
137 *dev = NULL;
138 return rc;
139}
140
Shawn Willden04006752015-04-30 11:12:33 -0600141// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
142// logger used by SoftKeymasterDevice.
143static keymaster::SoftKeymasterLogger softkeymaster_logger;
144
Chad Brubaker67d2a502015-03-11 17:21:18 +0000145static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
146 keymaster::SoftKeymasterDevice* softkeymaster =
147 new keymaster::SoftKeymasterDevice();
Shawn Willden9fd05a92015-04-30 11:01:19 -0600148 *dev = softkeymaster->keymaster_device();
149 // softkeymaster will be freed by *dev->close_device; don't delete here.
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800150 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800151}
152
Chad Brubakerbd07a232015-06-01 10:44:27 -0700153static void keymaster_device_release(keymaster1_device_t* dev) {
154 dev->common.close(&dev->common);
Kenny Root70e3a862012-02-15 17:20:23 -0800155}
156
Kenny Root07438c82012-11-02 15:41:02 -0700157/***************
158 * PERMISSIONS *
159 ***************/
160
161/* Here are the permissions, actions, users, and the main function. */
162typedef enum {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700163 P_GET_STATE = 1 << 0,
Robin Lee4e865752014-08-19 17:37:55 +0100164 P_GET = 1 << 1,
165 P_INSERT = 1 << 2,
166 P_DELETE = 1 << 3,
167 P_EXIST = 1 << 4,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700168 P_LIST = 1 << 5,
Robin Lee4e865752014-08-19 17:37:55 +0100169 P_RESET = 1 << 6,
170 P_PASSWORD = 1 << 7,
171 P_LOCK = 1 << 8,
172 P_UNLOCK = 1 << 9,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700173 P_IS_EMPTY = 1 << 10,
Robin Lee4e865752014-08-19 17:37:55 +0100174 P_SIGN = 1 << 11,
175 P_VERIFY = 1 << 12,
176 P_GRANT = 1 << 13,
177 P_DUPLICATE = 1 << 14,
178 P_CLEAR_UID = 1 << 15,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700179 P_ADD_AUTH = 1 << 16,
180 P_USER_CHANGED = 1 << 17,
Kenny Root07438c82012-11-02 15:41:02 -0700181} perm_t;
182
183static struct user_euid {
184 uid_t uid;
185 uid_t euid;
186} user_euids[] = {
187 {AID_VPN, AID_SYSTEM},
188 {AID_WIFI, AID_SYSTEM},
189 {AID_ROOT, AID_SYSTEM},
190};
191
Riley Spahneaabae92014-06-30 12:39:52 -0700192/* perm_labels associcated with keystore_key SELinux class verbs. */
193const char *perm_labels[] = {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700194 "get_state",
Riley Spahneaabae92014-06-30 12:39:52 -0700195 "get",
196 "insert",
197 "delete",
198 "exist",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700199 "list",
Riley Spahneaabae92014-06-30 12:39:52 -0700200 "reset",
201 "password",
202 "lock",
203 "unlock",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700204 "is_empty",
Riley Spahneaabae92014-06-30 12:39:52 -0700205 "sign",
206 "verify",
207 "grant",
208 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100209 "clear_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700210 "add_auth",
Chad Brubakerc0f031a2015-05-12 10:43:10 -0700211 "user_changed",
Riley Spahneaabae92014-06-30 12:39:52 -0700212};
213
Kenny Root07438c82012-11-02 15:41:02 -0700214static struct user_perm {
215 uid_t uid;
216 perm_t perms;
217} user_perms[] = {
218 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
219 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
220 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
221 {AID_ROOT, static_cast<perm_t>(P_GET) },
222};
223
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700224static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_GET_STATE | P_GET | P_INSERT | P_DELETE
225 | P_EXIST | P_LIST | P_SIGN | P_VERIFY);
Kenny Root07438c82012-11-02 15:41:02 -0700226
Riley Spahneaabae92014-06-30 12:39:52 -0700227static char *tctx;
228static int ks_is_selinux_enabled;
229
230static const char *get_perm_label(perm_t perm) {
231 unsigned int index = ffs(perm);
232 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
233 return perm_labels[index - 1];
234 } else {
235 ALOGE("Keystore: Failed to retrieve permission label.\n");
236 abort();
237 }
238}
239
Kenny Root655b9582013-04-04 08:37:42 -0700240/**
241 * Returns the app ID (in the Android multi-user sense) for the current
242 * UNIX UID.
243 */
244static uid_t get_app_id(uid_t uid) {
245 return uid % AID_USER;
246}
247
248/**
249 * Returns the user ID (in the Android multi-user sense) for the current
250 * UNIX UID.
251 */
252static uid_t get_user_id(uid_t uid) {
253 return uid / AID_USER;
254}
255
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700256static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700257 if (!ks_is_selinux_enabled) {
258 return true;
259 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000260
Riley Spahneaabae92014-06-30 12:39:52 -0700261 char *sctx = NULL;
262 const char *selinux_class = "keystore_key";
263 const char *str_perm = get_perm_label(perm);
264
265 if (!str_perm) {
266 return false;
267 }
268
269 if (getpidcon(spid, &sctx) != 0) {
270 ALOGE("SELinux: Failed to get source pid context.\n");
271 return false;
272 }
273
274 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
275 NULL) == 0;
276 freecon(sctx);
277 return allowed;
278}
279
280static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700281 // All system users are equivalent for multi-user support.
282 if (get_app_id(uid) == AID_SYSTEM) {
283 uid = AID_SYSTEM;
284 }
285
Kenny Root07438c82012-11-02 15:41:02 -0700286 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
287 struct user_perm user = user_perms[i];
288 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700289 return (user.perms & perm) &&
290 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700291 }
292 }
293
Riley Spahneaabae92014-06-30 12:39:52 -0700294 return (DEFAULT_PERMS & perm) &&
295 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700296}
297
Kenny Root49468902013-03-19 13:41:33 -0700298/**
299 * Returns the UID that the callingUid should act as. This is here for
300 * legacy support of the WiFi and VPN systems and should be removed
301 * when WiFi can operate in its own namespace.
302 */
Kenny Root07438c82012-11-02 15:41:02 -0700303static uid_t get_keystore_euid(uid_t uid) {
304 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
305 struct user_euid user = user_euids[i];
306 if (user.uid == uid) {
307 return user.euid;
308 }
309 }
310
311 return uid;
312}
313
Kenny Root49468902013-03-19 13:41:33 -0700314/**
315 * Returns true if the callingUid is allowed to interact in the targetUid's
316 * namespace.
317 */
318static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700319 if (callingUid == targetUid) {
320 return true;
321 }
Kenny Root49468902013-03-19 13:41:33 -0700322 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
323 struct user_euid user = user_euids[i];
324 if (user.euid == callingUid && user.uid == targetUid) {
325 return true;
326 }
327 }
328
329 return false;
330}
331
Kenny Roota91203b2012-02-15 15:00:46 -0800332/* Here is the encoding of keys. This is necessary in order to allow arbitrary
333 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
334 * into two bytes. The first byte is one of [+-.] which represents the first
335 * two bits of the character. The second byte encodes the rest of the bits into
336 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
337 * that Base64 cannot be used here due to the need of prefix match on keys. */
338
Kenny Root655b9582013-04-04 08:37:42 -0700339static size_t encode_key_length(const android::String8& keyName) {
340 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
341 size_t length = keyName.length();
342 for (int i = length; i > 0; --i, ++in) {
343 if (*in < '0' || *in > '~') {
344 ++length;
345 }
346 }
347 return length;
348}
349
Kenny Root07438c82012-11-02 15:41:02 -0700350static int encode_key(char* out, const android::String8& keyName) {
351 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
352 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800353 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700354 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800355 *out = '+' + (*in >> 6);
356 *++out = '0' + (*in & 0x3F);
357 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700358 } else {
359 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800360 }
361 }
362 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800363 return length;
364}
365
Kenny Root07438c82012-11-02 15:41:02 -0700366/*
367 * Converts from the "escaped" format on disk to actual name.
368 * This will be smaller than the input string.
369 *
370 * Characters that should combine with the next at the end will be truncated.
371 */
372static size_t decode_key_length(const char* in, size_t length) {
373 size_t outLength = 0;
374
375 for (const char* end = in + length; in < end; in++) {
376 /* This combines with the next character. */
377 if (*in < '0' || *in > '~') {
378 continue;
379 }
380
381 outLength++;
382 }
383 return outLength;
384}
385
386static void decode_key(char* out, const char* in, size_t length) {
387 for (const char* end = in + length; in < end; in++) {
388 if (*in < '0' || *in > '~') {
389 /* Truncate combining characters at the end. */
390 if (in + 1 >= end) {
391 break;
392 }
393
394 *out = (*in++ - '+') << 6;
395 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800396 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700397 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800398 }
399 }
400 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800401}
402
403static size_t readFully(int fd, uint8_t* data, size_t size) {
404 size_t remaining = size;
405 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800406 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800407 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800408 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800409 }
410 data += n;
411 remaining -= n;
412 }
413 return size;
414}
415
416static size_t writeFully(int fd, uint8_t* data, size_t size) {
417 size_t remaining = size;
418 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800419 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
420 if (n < 0) {
421 ALOGW("write failed: %s", strerror(errno));
422 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800423 }
424 data += n;
425 remaining -= n;
426 }
427 return size;
428}
429
430class Entropy {
431public:
432 Entropy() : mRandom(-1) {}
433 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800434 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800435 close(mRandom);
436 }
437 }
438
439 bool open() {
440 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800441 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
442 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800443 ALOGE("open: %s: %s", randomDevice, strerror(errno));
444 return false;
445 }
446 return true;
447 }
448
Kenny Root51878182012-03-13 12:53:19 -0700449 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800450 return (readFully(mRandom, data, size) == size);
451 }
452
453private:
454 int mRandom;
455};
456
457/* Here is the file format. There are two parts in blob.value, the secret and
458 * the description. The secret is stored in ciphertext, and its original size
459 * can be found in blob.length. The description is stored after the secret in
460 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700461 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700462 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800463 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
464 * and decryptBlob(). Thus they should not be accessed from outside. */
465
Kenny Root822c3a92012-03-23 16:34:39 -0700466/* ** Note to future implementors of encryption: **
467 * Currently this is the construction:
468 * metadata || Enc(MD5(data) || data)
469 *
470 * This should be the construction used for encrypting if re-implementing:
471 *
472 * Derive independent keys for encryption and MAC:
473 * Kenc = AES_encrypt(masterKey, "Encrypt")
474 * Kmac = AES_encrypt(masterKey, "MAC")
475 *
476 * Store this:
477 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
478 * HMAC(Kmac, metadata || Enc(data))
479 */
Kenny Roota91203b2012-02-15 15:00:46 -0800480struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700481 uint8_t version;
482 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700483 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800484 uint8_t info;
485 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700486 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800487 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700488 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800489 int32_t length; // in network byte order when encrypted
490 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
491};
492
Kenny Root822c3a92012-03-23 16:34:39 -0700493typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700494 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700495 TYPE_GENERIC = 1,
496 TYPE_MASTER_KEY = 2,
497 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800498 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700499} BlobType;
500
Kenny Rootf9119d62013-04-03 09:22:15 -0700501static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700502
Kenny Roota91203b2012-02-15 15:00:46 -0800503class Blob {
504public:
Kenny Root07438c82012-11-02 15:41:02 -0700505 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
506 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800507 memset(&mBlob, 0, sizeof(mBlob));
Kenny Roota91203b2012-02-15 15:00:46 -0800508 mBlob.length = valueLength;
509 memcpy(mBlob.value, value, valueLength);
510
511 mBlob.info = infoLength;
512 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700513
Kenny Root07438c82012-11-02 15:41:02 -0700514 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700515 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700516
Kenny Rootee8068b2013-10-07 09:49:15 -0700517 if (type == TYPE_MASTER_KEY) {
518 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
519 } else {
520 mBlob.flags = KEYSTORE_FLAG_NONE;
521 }
Kenny Roota91203b2012-02-15 15:00:46 -0800522 }
523
524 Blob(blob b) {
525 mBlob = b;
526 }
527
Alex Klyubin1773b442015-02-20 12:33:33 -0800528 Blob() {
529 memset(&mBlob, 0, sizeof(mBlob));
530 }
Kenny Roota91203b2012-02-15 15:00:46 -0800531
Kenny Root51878182012-03-13 12:53:19 -0700532 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800533 return mBlob.value;
534 }
535
Kenny Root51878182012-03-13 12:53:19 -0700536 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800537 return mBlob.length;
538 }
539
Kenny Root51878182012-03-13 12:53:19 -0700540 const uint8_t* getInfo() const {
541 return mBlob.value + mBlob.length;
542 }
543
544 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800545 return mBlob.info;
546 }
547
Kenny Root822c3a92012-03-23 16:34:39 -0700548 uint8_t getVersion() const {
549 return mBlob.version;
550 }
551
Kenny Rootf9119d62013-04-03 09:22:15 -0700552 bool isEncrypted() const {
553 if (mBlob.version < 2) {
554 return true;
555 }
556
557 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
558 }
559
560 void setEncrypted(bool encrypted) {
561 if (encrypted) {
562 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
563 } else {
564 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
565 }
566 }
567
Kenny Root17208e02013-09-04 13:56:03 -0700568 bool isFallback() const {
569 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
570 }
571
572 void setFallback(bool fallback) {
573 if (fallback) {
574 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
575 } else {
576 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
577 }
578 }
579
Kenny Root822c3a92012-03-23 16:34:39 -0700580 void setVersion(uint8_t version) {
581 mBlob.version = version;
582 }
583
584 BlobType getType() const {
585 return BlobType(mBlob.type);
586 }
587
588 void setType(BlobType type) {
589 mBlob.type = uint8_t(type);
590 }
591
Kenny Rootf9119d62013-04-03 09:22:15 -0700592 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
593 ALOGV("writing blob %s", filename);
594 if (isEncrypted()) {
595 if (state != STATE_NO_ERROR) {
596 ALOGD("couldn't insert encrypted blob while not unlocked");
597 return LOCKED;
598 }
599
600 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
601 ALOGW("Could not read random data for: %s", filename);
602 return SYSTEM_ERROR;
603 }
Kenny Roota91203b2012-02-15 15:00:46 -0800604 }
605
606 // data includes the value and the value's length
607 size_t dataLength = mBlob.length + sizeof(mBlob.length);
608 // pad data to the AES_BLOCK_SIZE
609 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
610 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
611 // encrypted data includes the digest value
612 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
613 // move info after space for padding
614 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
615 // zero padding area
616 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
617
618 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800619
Kenny Rootf9119d62013-04-03 09:22:15 -0700620 if (isEncrypted()) {
621 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800622
Kenny Rootf9119d62013-04-03 09:22:15 -0700623 uint8_t vector[AES_BLOCK_SIZE];
624 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
625 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
626 aes_key, vector, AES_ENCRYPT);
627 }
628
Kenny Roota91203b2012-02-15 15:00:46 -0800629 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
630 size_t fileLength = encryptedLength + headerLength + mBlob.info;
631
632 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800633 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
634 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
635 if (out < 0) {
636 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800637 return SYSTEM_ERROR;
638 }
639 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
640 if (close(out) != 0) {
641 return SYSTEM_ERROR;
642 }
643 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800644 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800645 unlink(tmpFileName);
646 return SYSTEM_ERROR;
647 }
Kenny Root150ca932012-11-14 14:29:02 -0800648 if (rename(tmpFileName, filename) == -1) {
649 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
650 return SYSTEM_ERROR;
651 }
652 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800653 }
654
Kenny Rootf9119d62013-04-03 09:22:15 -0700655 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
656 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800657 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
658 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800659 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
660 }
661 // fileLength may be less than sizeof(mBlob) since the in
662 // memory version has extra padding to tolerate rounding up to
663 // the AES_BLOCK_SIZE
664 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
665 if (close(in) != 0) {
666 return SYSTEM_ERROR;
667 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700668
669 if (isEncrypted() && (state != STATE_NO_ERROR)) {
670 return LOCKED;
671 }
672
Kenny Roota91203b2012-02-15 15:00:46 -0800673 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
674 if (fileLength < headerLength) {
675 return VALUE_CORRUPTED;
676 }
677
678 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700679 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800680 return VALUE_CORRUPTED;
681 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700682
683 ssize_t digestedLength;
684 if (isEncrypted()) {
685 if (encryptedLength % AES_BLOCK_SIZE != 0) {
686 return VALUE_CORRUPTED;
687 }
688
689 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
690 mBlob.vector, AES_DECRYPT);
691 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
692 uint8_t computedDigest[MD5_DIGEST_LENGTH];
693 MD5(mBlob.digested, digestedLength, computedDigest);
694 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
695 return VALUE_CORRUPTED;
696 }
697 } else {
698 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800699 }
700
701 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
702 mBlob.length = ntohl(mBlob.length);
703 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
704 return VALUE_CORRUPTED;
705 }
706 if (mBlob.info != 0) {
707 // move info from after padding to after data
708 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
709 }
Kenny Root07438c82012-11-02 15:41:02 -0700710 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800711 }
712
713private:
714 struct blob mBlob;
715};
716
Kenny Root655b9582013-04-04 08:37:42 -0700717class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800718public:
Kenny Root655b9582013-04-04 08:37:42 -0700719 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
720 asprintf(&mUserDir, "user_%u", mUserId);
721 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
722 }
723
724 ~UserState() {
725 free(mUserDir);
726 free(mMasterKeyFile);
727 }
728
729 bool initialize() {
730 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
731 ALOGE("Could not create directory '%s'", mUserDir);
732 return false;
733 }
734
735 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800736 setState(STATE_LOCKED);
737 } else {
738 setState(STATE_UNINITIALIZED);
739 }
Kenny Root70e3a862012-02-15 17:20:23 -0800740
Kenny Root655b9582013-04-04 08:37:42 -0700741 return true;
742 }
743
744 uid_t getUserId() const {
745 return mUserId;
746 }
747
748 const char* getUserDirName() const {
749 return mUserDir;
750 }
751
752 const char* getMasterKeyFileName() const {
753 return mMasterKeyFile;
754 }
755
756 void setState(State state) {
757 mState = state;
758 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
759 mRetry = MAX_RETRY;
760 }
Kenny Roota91203b2012-02-15 15:00:46 -0800761 }
762
Kenny Root51878182012-03-13 12:53:19 -0700763 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800764 return mState;
765 }
766
Kenny Root51878182012-03-13 12:53:19 -0700767 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800768 return mRetry;
769 }
770
Kenny Root655b9582013-04-04 08:37:42 -0700771 void zeroizeMasterKeysInMemory() {
772 memset(mMasterKey, 0, sizeof(mMasterKey));
773 memset(mSalt, 0, sizeof(mSalt));
774 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
775 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800776 }
777
Chad Brubaker96d6d782015-05-07 10:19:40 -0700778 bool deleteMasterKey() {
779 setState(STATE_UNINITIALIZED);
780 zeroizeMasterKeysInMemory();
781 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
782 }
783
Kenny Root655b9582013-04-04 08:37:42 -0700784 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
785 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800786 return SYSTEM_ERROR;
787 }
Kenny Root655b9582013-04-04 08:37:42 -0700788 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800789 if (response != NO_ERROR) {
790 return response;
791 }
792 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700793 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800794 }
795
Robin Lee4e865752014-08-19 17:37:55 +0100796 ResponseCode copyMasterKey(UserState* src) {
797 if (mState != STATE_UNINITIALIZED) {
798 return ::SYSTEM_ERROR;
799 }
800 if (src->getState() != STATE_NO_ERROR) {
801 return ::SYSTEM_ERROR;
802 }
803 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
804 setupMasterKeys();
805 return ::NO_ERROR;
806 }
807
Kenny Root655b9582013-04-04 08:37:42 -0700808 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800809 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
810 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
811 AES_KEY passwordAesKey;
812 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700813 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700814 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800815 }
816
Kenny Root655b9582013-04-04 08:37:42 -0700817 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
818 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800819 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800820 return SYSTEM_ERROR;
821 }
822
823 // we read the raw blob to just to get the salt to generate
824 // the AES key, then we create the Blob to use with decryptBlob
825 blob rawBlob;
826 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
827 if (close(in) != 0) {
828 return SYSTEM_ERROR;
829 }
830 // find salt at EOF if present, otherwise we have an old file
831 uint8_t* salt;
832 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
833 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
834 } else {
835 salt = NULL;
836 }
837 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
838 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
839 AES_KEY passwordAesKey;
840 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
841 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700842 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
843 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800844 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700845 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800846 }
847 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
848 // if salt was missing, generate one and write a new master key file with the salt.
849 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700850 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800851 return SYSTEM_ERROR;
852 }
Kenny Root655b9582013-04-04 08:37:42 -0700853 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800854 }
855 if (response == NO_ERROR) {
856 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
857 setupMasterKeys();
858 }
859 return response;
860 }
861 if (mRetry <= 0) {
862 reset();
863 return UNINITIALIZED;
864 }
865 --mRetry;
866 switch (mRetry) {
867 case 0: return WRONG_PASSWORD_0;
868 case 1: return WRONG_PASSWORD_1;
869 case 2: return WRONG_PASSWORD_2;
870 case 3: return WRONG_PASSWORD_3;
871 default: return WRONG_PASSWORD_3;
872 }
873 }
874
Kenny Root655b9582013-04-04 08:37:42 -0700875 AES_KEY* getEncryptionKey() {
876 return &mMasterKeyEncryption;
877 }
878
879 AES_KEY* getDecryptionKey() {
880 return &mMasterKeyDecryption;
881 }
882
Kenny Roota91203b2012-02-15 15:00:46 -0800883 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700884 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800885 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700886 // If the directory doesn't exist then nothing to do.
887 if (errno == ENOENT) {
888 return true;
889 }
Kenny Root655b9582013-04-04 08:37:42 -0700890 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800891 return false;
892 }
Kenny Root655b9582013-04-04 08:37:42 -0700893
894 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800895 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700896 // skip . and ..
897 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700898 continue;
899 }
900
901 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800902 }
903 closedir(dir);
904 return true;
905 }
906
Kenny Root655b9582013-04-04 08:37:42 -0700907private:
908 static const int MASTER_KEY_SIZE_BYTES = 16;
909 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
910
911 static const int MAX_RETRY = 4;
912 static const size_t SALT_SIZE = 16;
913
914 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
915 uint8_t* salt) {
916 size_t saltSize;
917 if (salt != NULL) {
918 saltSize = SALT_SIZE;
919 } else {
920 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
921 salt = (uint8_t*) "keystore";
922 // sizeof = 9, not strlen = 8
923 saltSize = sizeof("keystore");
924 }
925
926 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
927 saltSize, 8192, keySize, key);
928 }
929
930 bool generateSalt(Entropy* entropy) {
931 return entropy->generate_random_data(mSalt, sizeof(mSalt));
932 }
933
934 bool generateMasterKey(Entropy* entropy) {
935 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
936 return false;
937 }
938 if (!generateSalt(entropy)) {
939 return false;
940 }
941 return true;
942 }
943
944 void setupMasterKeys() {
945 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
946 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
947 setState(STATE_NO_ERROR);
948 }
949
950 uid_t mUserId;
951
952 char* mUserDir;
953 char* mMasterKeyFile;
954
955 State mState;
956 int8_t mRetry;
957
958 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
959 uint8_t mSalt[SALT_SIZE];
960
961 AES_KEY mMasterKeyEncryption;
962 AES_KEY mMasterKeyDecryption;
963};
964
965typedef struct {
966 uint32_t uid;
967 const uint8_t* filename;
968} grant_t;
969
970class KeyStore {
971public:
Chad Brubaker67d2a502015-03-11 17:21:18 +0000972 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700973 : mEntropy(entropy)
974 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800975 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700976 {
977 memset(&mMetaData, '\0', sizeof(mMetaData));
978 }
979
980 ~KeyStore() {
981 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
982 it != mGrants.end(); it++) {
983 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700984 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800985 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700986
987 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
988 it != mMasterKeys.end(); it++) {
989 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700990 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800991 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700992 }
993
Chad Brubaker67d2a502015-03-11 17:21:18 +0000994 /**
995 * Depending on the hardware keymaster version is this may return a
996 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
997 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
998 * be guarded by a check on the device's version.
999 */
1000 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001001 return mDevice;
1002 }
1003
Chad Brubaker67d2a502015-03-11 17:21:18 +00001004 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001005 return mFallbackDevice;
1006 }
1007
Chad Brubaker67d2a502015-03-11 17:21:18 +00001008 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001009 return blob.isFallback() ? mFallbackDevice: mDevice;
1010 }
1011
Kenny Root655b9582013-04-04 08:37:42 -07001012 ResponseCode initialize() {
1013 readMetaData();
1014 if (upgradeKeystore()) {
1015 writeMetaData();
1016 }
1017
1018 return ::NO_ERROR;
1019 }
1020
Chad Brubaker72593ee2015-05-12 10:42:00 -07001021 State getState(uid_t userId) {
1022 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001023 }
1024
Chad Brubaker72593ee2015-05-12 10:42:00 -07001025 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1026 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001027 return userState->initialize(pw, mEntropy);
1028 }
1029
Chad Brubaker72593ee2015-05-12 10:42:00 -07001030 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1031 UserState *userState = getUserState(dstUser);
1032 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001033 return userState->copyMasterKey(initState);
1034 }
1035
Chad Brubaker72593ee2015-05-12 10:42:00 -07001036 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1037 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001038 return userState->writeMasterKey(pw, mEntropy);
1039 }
1040
Chad Brubaker72593ee2015-05-12 10:42:00 -07001041 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1042 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001043 return userState->readMasterKey(pw, mEntropy);
1044 }
1045
1046 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001047 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001048 encode_key(encoded, keyName);
1049 return android::String8(encoded);
1050 }
1051
1052 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001053 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001054 encode_key(encoded, keyName);
1055 return android::String8::format("%u_%s", uid, encoded);
1056 }
1057
1058 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001059 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001060 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001061 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001062 encoded);
1063 }
1064
Chad Brubaker96d6d782015-05-07 10:19:40 -07001065 /*
1066 * Delete entries owned by userId. If keepUnencryptedEntries is true
1067 * then only encrypted entries will be removed, otherwise all entries will
1068 * be removed.
1069 */
1070 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001071 android::String8 prefix("");
1072 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001073 UserState* userState = getUserState(userId);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001074 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001075 return;
1076 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001077 for (uint32_t i = 0; i < aliases.size(); i++) {
1078 android::String8 filename(aliases[i]);
1079 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001080 getKeyName(filename).string());
1081 bool shouldDelete = true;
1082 if (keepUnenryptedEntries) {
1083 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001084 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001085
Chad Brubaker96d6d782015-05-07 10:19:40 -07001086 /* get can fail if the blob is encrypted and the state is
1087 * not unlocked, only skip deleting blobs that were loaded and
1088 * who are not encrypted. If there are blobs we fail to read for
1089 * other reasons err on the safe side and delete them since we
1090 * can't tell if they're encrypted.
1091 */
1092 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1093 }
1094 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001095 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001096 }
1097 }
1098 if (!userState->deleteMasterKey()) {
1099 ALOGE("Failed to delete user %d's master key", userId);
1100 }
1101 if (!keepUnenryptedEntries) {
1102 if(!userState->reset()) {
1103 ALOGE("Failed to remove user %d's directory", userId);
1104 }
1105 }
Kenny Root655b9582013-04-04 08:37:42 -07001106 }
1107
Chad Brubaker72593ee2015-05-12 10:42:00 -07001108 bool isEmpty(uid_t userId) const {
1109 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001110 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001111 return true;
1112 }
1113
1114 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001115 if (!dir) {
1116 return true;
1117 }
Kenny Root31e27462014-09-10 11:28:03 -07001118
Kenny Roota91203b2012-02-15 15:00:46 -08001119 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001120 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001121 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001122 // We only care about files.
1123 if (file->d_type != DT_REG) {
1124 continue;
1125 }
1126
1127 // Skip anything that starts with a "."
1128 if (file->d_name[0] == '.') {
1129 continue;
1130 }
1131
Kenny Root31e27462014-09-10 11:28:03 -07001132 result = false;
1133 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001134 }
1135 closedir(dir);
1136 return result;
1137 }
1138
Chad Brubaker72593ee2015-05-12 10:42:00 -07001139 void lock(uid_t userId) {
1140 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001141 userState->zeroizeMasterKeysInMemory();
1142 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001143 }
1144
Chad Brubaker72593ee2015-05-12 10:42:00 -07001145 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1146 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001147 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1148 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001149 if (rc != NO_ERROR) {
1150 return rc;
1151 }
1152
1153 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001154 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001155 /* If we upgrade the key, we need to write it to disk again. Then
1156 * it must be read it again since the blob is encrypted each time
1157 * it's written.
1158 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001159 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1160 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001161 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1162 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001163 return rc;
1164 }
1165 }
Kenny Root822c3a92012-03-23 16:34:39 -07001166 }
1167
Kenny Root17208e02013-09-04 13:56:03 -07001168 /*
1169 * This will upgrade software-backed keys to hardware-backed keys when
1170 * the HAL for the device supports the newer key types.
1171 */
1172 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1173 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1174 && keyBlob->isFallback()) {
1175 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001176 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001177
1178 // The HAL allowed the import, reget the key to have the "fresh"
1179 // version.
1180 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001181 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001182 }
1183 }
1184
Chad Brubaker3cc40122015-06-04 13:49:44 -07001185 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade
1186 // them if needed.
1187 if (type == TYPE_KEYMASTER_10 && keyBlob->getType() == TYPE_KEY_PAIR) {
1188 keyBlob->setType(TYPE_KEYMASTER_10);
1189 }
1190
Kenny Rootd53bc922013-03-21 14:10:15 -07001191 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001192 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1193 return KEY_NOT_FOUND;
1194 }
1195
1196 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001197 }
1198
Chad Brubaker72593ee2015-05-12 10:42:00 -07001199 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1200 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001201 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1202 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001203 }
1204
Chad Brubaker72593ee2015-05-12 10:42:00 -07001205 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001206 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001207 ResponseCode rc = get(filename, &keyBlob, type, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001208 if (rc != ::NO_ERROR) {
1209 return rc;
1210 }
1211
1212 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1213 // A device doesn't have to implement delete_keypair.
1214 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1215 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1216 rc = ::SYSTEM_ERROR;
1217 }
1218 }
1219 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001220 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1221 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1222 if (dev->delete_key) {
1223 keymaster_key_blob_t blob;
1224 blob.key_material = keyBlob.getValue();
1225 blob.key_material_size = keyBlob.getLength();
1226 dev->delete_key(dev, &blob);
1227 }
1228 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001229 if (rc != ::NO_ERROR) {
1230 return rc;
1231 }
1232
1233 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1234 }
1235
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001236 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001237 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001238
Chad Brubaker72593ee2015-05-12 10:42:00 -07001239 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001240 size_t n = prefix.length();
1241
1242 DIR* dir = opendir(userState->getUserDirName());
1243 if (!dir) {
1244 ALOGW("can't open directory for user: %s", strerror(errno));
1245 return ::SYSTEM_ERROR;
1246 }
1247
1248 struct dirent* file;
1249 while ((file = readdir(dir)) != NULL) {
1250 // We only care about files.
1251 if (file->d_type != DT_REG) {
1252 continue;
1253 }
1254
1255 // Skip anything that starts with a "."
1256 if (file->d_name[0] == '.') {
1257 continue;
1258 }
1259
1260 if (!strncmp(prefix.string(), file->d_name, n)) {
1261 const char* p = &file->d_name[n];
1262 size_t plen = strlen(p);
1263
1264 size_t extra = decode_key_length(p, plen);
1265 char *match = (char*) malloc(extra + 1);
1266 if (match != NULL) {
1267 decode_key(match, p, plen);
1268 matches->push(android::String16(match, extra));
1269 free(match);
1270 } else {
1271 ALOGW("could not allocate match of size %zd", extra);
1272 }
1273 }
1274 }
1275 closedir(dir);
1276 return ::NO_ERROR;
1277 }
1278
Kenny Root07438c82012-11-02 15:41:02 -07001279 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001280 const grant_t* existing = getGrant(filename, granteeUid);
1281 if (existing == NULL) {
1282 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001283 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001284 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001285 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001286 }
1287 }
1288
Kenny Root07438c82012-11-02 15:41:02 -07001289 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001290 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1291 it != mGrants.end(); it++) {
1292 grant_t* grant = *it;
1293 if (grant->uid == granteeUid
1294 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1295 mGrants.erase(it);
1296 return true;
1297 }
Kenny Root70e3a862012-02-15 17:20:23 -08001298 }
Kenny Root70e3a862012-02-15 17:20:23 -08001299 return false;
1300 }
1301
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001302 bool hasGrant(const char* filename, const uid_t uid) const {
1303 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001304 }
1305
Chad Brubaker72593ee2015-05-12 10:42:00 -07001306 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001307 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001308 uint8_t* data;
1309 size_t dataLength;
1310 int rc;
1311
1312 if (mDevice->import_keypair == NULL) {
1313 ALOGE("Keymaster doesn't support import!");
1314 return SYSTEM_ERROR;
1315 }
1316
Kenny Root17208e02013-09-04 13:56:03 -07001317 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001318 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001319 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001320 /*
1321 * Maybe the device doesn't support this type of key. Try to use the
1322 * software fallback keymaster implementation. This is a little bit
1323 * lazier than checking the PKCS#8 key type, but the software
1324 * implementation will do that anyway.
1325 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001326 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001327 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001328
1329 if (rc) {
1330 ALOGE("Error while importing keypair: %d", rc);
1331 return SYSTEM_ERROR;
1332 }
Kenny Root822c3a92012-03-23 16:34:39 -07001333 }
1334
1335 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1336 free(data);
1337
Kenny Rootf9119d62013-04-03 09:22:15 -07001338 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001339 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001340
Chad Brubaker72593ee2015-05-12 10:42:00 -07001341 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001342 }
1343
Kenny Root1b0e3932013-09-05 13:06:32 -07001344 bool isHardwareBacked(const android::String16& keyType) const {
1345 if (mDevice == NULL) {
1346 ALOGW("can't get keymaster device");
1347 return false;
1348 }
1349
1350 if (sRSAKeyType == keyType) {
1351 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1352 } else {
1353 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1354 && (mDevice->common.module->module_api_version
1355 >= KEYMASTER_MODULE_API_VERSION_0_2);
1356 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001357 }
1358
Kenny Root655b9582013-04-04 08:37:42 -07001359 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1360 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001361 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001362 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001363
Chad Brubaker72593ee2015-05-12 10:42:00 -07001364 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001365 if (responseCode == NO_ERROR) {
1366 return responseCode;
1367 }
1368
1369 // If this is one of the legacy UID->UID mappings, use it.
1370 uid_t euid = get_keystore_euid(uid);
1371 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001372 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001373 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001374 if (responseCode == NO_ERROR) {
1375 return responseCode;
1376 }
1377 }
1378
1379 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001380 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001381 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001382 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001383 if (end[0] != '_' || end[1] == 0) {
1384 return KEY_NOT_FOUND;
1385 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001386 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001387 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001388 if (!hasGrant(filepath8.string(), uid)) {
1389 return responseCode;
1390 }
1391
1392 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001393 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001394 }
1395
1396 /**
1397 * Returns any existing UserState or creates it if it doesn't exist.
1398 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001399 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001400 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1401 it != mMasterKeys.end(); it++) {
1402 UserState* state = *it;
1403 if (state->getUserId() == userId) {
1404 return state;
1405 }
1406 }
1407
1408 UserState* userState = new UserState(userId);
1409 if (!userState->initialize()) {
1410 /* There's not much we can do if initialization fails. Trying to
1411 * unlock the keystore for that user will fail as well, so any
1412 * subsequent request for this user will just return SYSTEM_ERROR.
1413 */
1414 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1415 }
1416 mMasterKeys.add(userState);
1417 return userState;
1418 }
1419
1420 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001421 * Returns any existing UserState or creates it if it doesn't exist.
1422 */
1423 UserState* getUserStateByUid(uid_t uid) {
1424 uid_t userId = get_user_id(uid);
1425 return getUserState(userId);
1426 }
1427
1428 /**
Kenny Root655b9582013-04-04 08:37:42 -07001429 * Returns NULL if the UserState doesn't already exist.
1430 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001431 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001432 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1433 it != mMasterKeys.end(); it++) {
1434 UserState* state = *it;
1435 if (state->getUserId() == userId) {
1436 return state;
1437 }
1438 }
1439
1440 return NULL;
1441 }
1442
Chad Brubaker72593ee2015-05-12 10:42:00 -07001443 /**
1444 * Returns NULL if the UserState doesn't already exist.
1445 */
1446 const UserState* getUserStateByUid(uid_t uid) const {
1447 uid_t userId = get_user_id(uid);
1448 return getUserState(userId);
1449 }
1450
Kenny Roota91203b2012-02-15 15:00:46 -08001451private:
Kenny Root655b9582013-04-04 08:37:42 -07001452 static const char* sOldMasterKey;
1453 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001454 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001455 Entropy* mEntropy;
1456
Chad Brubaker67d2a502015-03-11 17:21:18 +00001457 keymaster1_device_t* mDevice;
1458 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001459
Kenny Root655b9582013-04-04 08:37:42 -07001460 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001461
Kenny Root655b9582013-04-04 08:37:42 -07001462 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001463
Kenny Root655b9582013-04-04 08:37:42 -07001464 typedef struct {
1465 uint32_t version;
1466 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001467
Kenny Root655b9582013-04-04 08:37:42 -07001468 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001469
Kenny Root655b9582013-04-04 08:37:42 -07001470 const grant_t* getGrant(const char* filename, uid_t uid) const {
1471 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1472 it != mGrants.end(); it++) {
1473 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001474 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001475 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001476 return grant;
1477 }
1478 }
Kenny Root70e3a862012-02-15 17:20:23 -08001479 return NULL;
1480 }
1481
Kenny Root822c3a92012-03-23 16:34:39 -07001482 /**
1483 * Upgrade code. This will upgrade the key from the current version
1484 * to whatever is newest.
1485 */
Kenny Root655b9582013-04-04 08:37:42 -07001486 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1487 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001488 bool updated = false;
1489 uint8_t version = oldVersion;
1490
1491 /* From V0 -> V1: All old types were unknown */
1492 if (version == 0) {
1493 ALOGV("upgrading to version 1 and setting type %d", type);
1494
1495 blob->setType(type);
1496 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001497 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001498 }
1499 version = 1;
1500 updated = true;
1501 }
1502
Kenny Rootf9119d62013-04-03 09:22:15 -07001503 /* From V1 -> V2: All old keys were encrypted */
1504 if (version == 1) {
1505 ALOGV("upgrading to version 2");
1506
1507 blob->setEncrypted(true);
1508 version = 2;
1509 updated = true;
1510 }
1511
Kenny Root822c3a92012-03-23 16:34:39 -07001512 /*
1513 * If we've updated, set the key blob to the right version
1514 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001515 */
Kenny Root822c3a92012-03-23 16:34:39 -07001516 if (updated) {
1517 ALOGV("updated and writing file %s", filename);
1518 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001519 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001520
1521 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001522 }
1523
1524 /**
1525 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1526 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1527 * Then it overwrites the original blob with the new blob
1528 * format that is returned from the keymaster.
1529 */
Kenny Root655b9582013-04-04 08:37:42 -07001530 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001531 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1532 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1533 if (b.get() == NULL) {
1534 ALOGE("Problem instantiating BIO");
1535 return SYSTEM_ERROR;
1536 }
1537
1538 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1539 if (pkey.get() == NULL) {
1540 ALOGE("Couldn't read old PEM file");
1541 return SYSTEM_ERROR;
1542 }
1543
1544 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1545 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1546 if (len < 0) {
1547 ALOGE("Couldn't measure PKCS#8 length");
1548 return SYSTEM_ERROR;
1549 }
1550
Kenny Root70c98892013-02-07 09:10:36 -08001551 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1552 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001553 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1554 ALOGE("Couldn't convert to PKCS#8");
1555 return SYSTEM_ERROR;
1556 }
1557
Chad Brubaker72593ee2015-05-12 10:42:00 -07001558 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001559 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001560 if (rc != NO_ERROR) {
1561 return rc;
1562 }
1563
Kenny Root655b9582013-04-04 08:37:42 -07001564 return get(filename, blob, TYPE_KEY_PAIR, uid);
1565 }
1566
1567 void readMetaData() {
1568 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1569 if (in < 0) {
1570 return;
1571 }
1572 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1573 if (fileLength != sizeof(mMetaData)) {
1574 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1575 sizeof(mMetaData));
1576 }
1577 close(in);
1578 }
1579
1580 void writeMetaData() {
1581 const char* tmpFileName = ".metadata.tmp";
1582 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1583 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1584 if (out < 0) {
1585 ALOGE("couldn't write metadata file: %s", strerror(errno));
1586 return;
1587 }
1588 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1589 if (fileLength != sizeof(mMetaData)) {
1590 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1591 sizeof(mMetaData));
1592 }
1593 close(out);
1594 rename(tmpFileName, sMetaDataFile);
1595 }
1596
1597 bool upgradeKeystore() {
1598 bool upgraded = false;
1599
1600 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001601 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001602
1603 // Initialize first so the directory is made.
1604 userState->initialize();
1605
1606 // Migrate the old .masterkey file to user 0.
1607 if (access(sOldMasterKey, R_OK) == 0) {
1608 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1609 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1610 return false;
1611 }
1612 }
1613
1614 // Initialize again in case we had a key.
1615 userState->initialize();
1616
1617 // Try to migrate existing keys.
1618 DIR* dir = opendir(".");
1619 if (!dir) {
1620 // Give up now; maybe we can upgrade later.
1621 ALOGE("couldn't open keystore's directory; something is wrong");
1622 return false;
1623 }
1624
1625 struct dirent* file;
1626 while ((file = readdir(dir)) != NULL) {
1627 // We only care about files.
1628 if (file->d_type != DT_REG) {
1629 continue;
1630 }
1631
1632 // Skip anything that starts with a "."
1633 if (file->d_name[0] == '.') {
1634 continue;
1635 }
1636
1637 // Find the current file's user.
1638 char* end;
1639 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1640 if (end[0] != '_' || end[1] == 0) {
1641 continue;
1642 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001643 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001644 if (otherUser->getUserId() != 0) {
1645 unlinkat(dirfd(dir), file->d_name, 0);
1646 }
1647
1648 // Rename the file into user directory.
1649 DIR* otherdir = opendir(otherUser->getUserDirName());
1650 if (otherdir == NULL) {
1651 ALOGW("couldn't open user directory for rename");
1652 continue;
1653 }
1654 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1655 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1656 }
1657 closedir(otherdir);
1658 }
1659 closedir(dir);
1660
1661 mMetaData.version = 1;
1662 upgraded = true;
1663 }
1664
1665 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001666 }
Kenny Roota91203b2012-02-15 15:00:46 -08001667};
1668
Kenny Root655b9582013-04-04 08:37:42 -07001669const char* KeyStore::sOldMasterKey = ".masterkey";
1670const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001671
Kenny Root1b0e3932013-09-05 13:06:32 -07001672const android::String16 KeyStore::sRSAKeyType("RSA");
1673
Kenny Root07438c82012-11-02 15:41:02 -07001674namespace android {
1675class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1676public:
1677 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001678 : mKeyStore(keyStore),
1679 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001680 {
Kenny Roota91203b2012-02-15 15:00:46 -08001681 }
Kenny Roota91203b2012-02-15 15:00:46 -08001682
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001683 void binderDied(const wp<IBinder>& who) {
1684 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1685 for (auto token: operations) {
1686 abort(token);
1687 }
Kenny Root822c3a92012-03-23 16:34:39 -07001688 }
Kenny Roota91203b2012-02-15 15:00:46 -08001689
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001690 int32_t getState(int32_t userId) {
1691 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001692 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001693 }
Kenny Roota91203b2012-02-15 15:00:46 -08001694
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001695 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001696 }
1697
Kenny Root07438c82012-11-02 15:41:02 -07001698 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001699 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001700 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001701 }
Kenny Root07438c82012-11-02 15:41:02 -07001702
Chad Brubaker9489b792015-04-14 11:01:45 -07001703 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001704 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001705 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001706
Kenny Root655b9582013-04-04 08:37:42 -07001707 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001708 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001709 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001710 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001711 *item = NULL;
1712 *itemLength = 0;
1713 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001714 }
Kenny Roota91203b2012-02-15 15:00:46 -08001715
Kenny Root07438c82012-11-02 15:41:02 -07001716 *item = (uint8_t*) malloc(keyBlob.getLength());
1717 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1718 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001719
Kenny Root07438c82012-11-02 15:41:02 -07001720 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001721 }
1722
Kenny Rootf9119d62013-04-03 09:22:15 -07001723 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1724 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001725 targetUid = getEffectiveUid(targetUid);
1726 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1727 flags & KEYSTORE_FLAG_ENCRYPTED);
1728 if (result != ::NO_ERROR) {
1729 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001730 }
1731
Kenny Root07438c82012-11-02 15:41:02 -07001732 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001733 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001734
1735 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001736 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1737
Chad Brubaker72593ee2015-05-12 10:42:00 -07001738 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001739 }
1740
Kenny Root49468902013-03-19 13:41:33 -07001741 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001742 targetUid = getEffectiveUid(targetUid);
1743 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001744 return ::PERMISSION_DENIED;
1745 }
Kenny Root07438c82012-11-02 15:41:02 -07001746 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001747 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001748 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001749 }
1750
Kenny Root49468902013-03-19 13:41:33 -07001751 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001752 targetUid = getEffectiveUid(targetUid);
1753 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001754 return ::PERMISSION_DENIED;
1755 }
1756
Kenny Root07438c82012-11-02 15:41:02 -07001757 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001758 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001759
Kenny Root655b9582013-04-04 08:37:42 -07001760 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001761 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1762 }
1763 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001764 }
1765
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001766 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001767 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001768 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001769 return ::PERMISSION_DENIED;
1770 }
Kenny Root07438c82012-11-02 15:41:02 -07001771 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001772 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001773
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001774 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001775 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001776 }
Kenny Root07438c82012-11-02 15:41:02 -07001777 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001778 }
1779
Kenny Root07438c82012-11-02 15:41:02 -07001780 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001781 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001782 return ::PERMISSION_DENIED;
1783 }
1784
Chad Brubaker9489b792015-04-14 11:01:45 -07001785 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001786 mKeyStore->resetUser(get_user_id(callingUid), false);
1787 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001788 }
1789
Chad Brubaker96d6d782015-05-07 10:19:40 -07001790 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001791 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001792 return ::PERMISSION_DENIED;
1793 }
Kenny Root70e3a862012-02-15 17:20:23 -08001794
Kenny Root07438c82012-11-02 15:41:02 -07001795 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001796 // Flush the auth token table to prevent stale tokens from sticking
1797 // around.
1798 mAuthTokenTable.Clear();
1799
1800 if (password.size() == 0) {
1801 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001802 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001803 return ::NO_ERROR;
1804 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001805 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001806 case ::STATE_UNINITIALIZED: {
1807 // generate master key, encrypt with password, write to file,
1808 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001809 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001810 }
1811 case ::STATE_NO_ERROR: {
1812 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001813 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001814 }
1815 case ::STATE_LOCKED: {
1816 ALOGE("Changing user %d's password while locked, clearing old encryption",
1817 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001818 mKeyStore->resetUser(userId, true);
1819 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001820 }
Kenny Root07438c82012-11-02 15:41:02 -07001821 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001822 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001823 }
Kenny Root70e3a862012-02-15 17:20:23 -08001824 }
1825
Chad Brubakerc0f031a2015-05-12 10:43:10 -07001826 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1827 if (!checkBinderPermission(P_USER_CHANGED)) {
1828 return ::PERMISSION_DENIED;
1829 }
1830
1831 // Sanity check that the new user has an empty keystore.
1832 if (!mKeyStore->isEmpty(userId)) {
1833 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
1834 }
1835 // Unconditionally clear the keystore, just to be safe.
1836 mKeyStore->resetUser(userId, false);
1837
1838 // If the user has a parent user then use the parent's
1839 // masterkey/password, otherwise there's nothing to do.
1840 if (parentId != -1) {
1841 return mKeyStore->copyMasterKey(parentId, userId);
1842 } else {
1843 return ::NO_ERROR;
1844 }
1845 }
1846
1847 int32_t onUserRemoved(int32_t userId) {
1848 if (!checkBinderPermission(P_USER_CHANGED)) {
1849 return ::PERMISSION_DENIED;
1850 }
1851
1852 mKeyStore->resetUser(userId, false);
1853 return ::NO_ERROR;
1854 }
1855
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001856 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001857 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001858 return ::PERMISSION_DENIED;
1859 }
Kenny Root70e3a862012-02-15 17:20:23 -08001860
Chad Brubaker72593ee2015-05-12 10:42:00 -07001861 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001862 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001863 ALOGD("calling lock in state: %d", state);
1864 return state;
1865 }
1866
Chad Brubaker72593ee2015-05-12 10:42:00 -07001867 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07001868 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001869 }
1870
Chad Brubaker96d6d782015-05-07 10:19:40 -07001871 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001872 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001873 return ::PERMISSION_DENIED;
1874 }
1875
Chad Brubaker72593ee2015-05-12 10:42:00 -07001876 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001877 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001878 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001879 return state;
1880 }
1881
1882 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001883 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001884 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001885 }
1886
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001887 bool isEmpty(int32_t userId) {
1888 if (!checkBinderPermission(P_IS_EMPTY)) {
1889 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001890 }
Kenny Root70e3a862012-02-15 17:20:23 -08001891
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001892 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001893 }
1894
Kenny Root96427ba2013-08-16 14:02:41 -07001895 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1896 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001897 targetUid = getEffectiveUid(targetUid);
1898 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1899 flags & KEYSTORE_FLAG_ENCRYPTED);
1900 if (result != ::NO_ERROR) {
1901 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001902 }
Kenny Root07438c82012-11-02 15:41:02 -07001903 uint8_t* data;
1904 size_t dataLength;
1905 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001906 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001907
Chad Brubaker67d2a502015-03-11 17:21:18 +00001908 const keymaster1_device_t* device = mKeyStore->getDevice();
1909 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001910 if (device == NULL) {
1911 return ::SYSTEM_ERROR;
1912 }
1913
1914 if (device->generate_keypair == NULL) {
1915 return ::SYSTEM_ERROR;
1916 }
1917
Kenny Root17208e02013-09-04 13:56:03 -07001918 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001919 keymaster_dsa_keygen_params_t dsa_params;
1920 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001921
Kenny Root96427ba2013-08-16 14:02:41 -07001922 if (keySize == -1) {
1923 keySize = DSA_DEFAULT_KEY_SIZE;
1924 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1925 || keySize > DSA_MAX_KEY_SIZE) {
1926 ALOGI("invalid key size %d", keySize);
1927 return ::SYSTEM_ERROR;
1928 }
1929 dsa_params.key_size = keySize;
1930
1931 if (args->size() == 3) {
1932 sp<KeystoreArg> gArg = args->itemAt(0);
1933 sp<KeystoreArg> pArg = args->itemAt(1);
1934 sp<KeystoreArg> qArg = args->itemAt(2);
1935
1936 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1937 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1938 dsa_params.generator_len = gArg->size();
1939
1940 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1941 dsa_params.prime_p_len = pArg->size();
1942
1943 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1944 dsa_params.prime_q_len = qArg->size();
1945 } else {
1946 ALOGI("not all DSA parameters were read");
1947 return ::SYSTEM_ERROR;
1948 }
1949 } else if (args->size() != 0) {
1950 ALOGI("DSA args must be 3");
1951 return ::SYSTEM_ERROR;
1952 }
1953
Kenny Root1d448c02013-11-21 10:36:53 -08001954 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001955 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1956 } else {
1957 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001958 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1959 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001960 }
1961 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001962 keymaster_ec_keygen_params_t ec_params;
1963 memset(&ec_params, '\0', sizeof(ec_params));
1964
1965 if (keySize == -1) {
1966 keySize = EC_DEFAULT_KEY_SIZE;
1967 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1968 ALOGI("invalid key size %d", keySize);
1969 return ::SYSTEM_ERROR;
1970 }
1971 ec_params.field_size = keySize;
1972
Kenny Root1d448c02013-11-21 10:36:53 -08001973 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001974 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1975 } else {
1976 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001977 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001978 }
Kenny Root96427ba2013-08-16 14:02:41 -07001979 } else if (keyType == EVP_PKEY_RSA) {
1980 keymaster_rsa_keygen_params_t rsa_params;
1981 memset(&rsa_params, '\0', sizeof(rsa_params));
1982 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1983
1984 if (keySize == -1) {
1985 keySize = RSA_DEFAULT_KEY_SIZE;
1986 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1987 ALOGI("invalid key size %d", keySize);
1988 return ::SYSTEM_ERROR;
1989 }
1990 rsa_params.modulus_size = keySize;
1991
1992 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001993 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001994 return ::SYSTEM_ERROR;
1995 } else if (args->size() == 1) {
1996 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1997 if (pubExpBlob != NULL) {
1998 Unique_BIGNUM pubExpBn(
1999 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
2000 pubExpBlob->size(), NULL));
2001 if (pubExpBn.get() == NULL) {
2002 ALOGI("Could not convert public exponent to BN");
2003 return ::SYSTEM_ERROR;
2004 }
2005 unsigned long pubExp = BN_get_word(pubExpBn.get());
2006 if (pubExp == 0xFFFFFFFFL) {
2007 ALOGI("cannot represent public exponent as a long value");
2008 return ::SYSTEM_ERROR;
2009 }
2010 rsa_params.public_exponent = pubExp;
2011 }
2012 }
2013
2014 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
2015 } else {
2016 ALOGW("Unsupported key type %d", keyType);
2017 rc = -1;
2018 }
2019
Kenny Root07438c82012-11-02 15:41:02 -07002020 if (rc) {
2021 return ::SYSTEM_ERROR;
2022 }
2023
Kenny Root655b9582013-04-04 08:37:42 -07002024 String8 name8(name);
Chad Brubaker9489b792015-04-14 11:01:45 -07002025 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002026
2027 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
2028 free(data);
2029
Kenny Rootee8068b2013-10-07 09:49:15 -07002030 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07002031 keyBlob.setFallback(isFallback);
2032
Chad Brubaker72593ee2015-05-12 10:42:00 -07002033 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08002034 }
2035
Kenny Rootf9119d62013-04-03 09:22:15 -07002036 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2037 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002038 targetUid = getEffectiveUid(targetUid);
2039 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2040 flags & KEYSTORE_FLAG_ENCRYPTED);
2041 if (result != ::NO_ERROR) {
2042 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002043 }
Kenny Root07438c82012-11-02 15:41:02 -07002044 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002045 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002046
Chad Brubaker72593ee2015-05-12 10:42:00 -07002047 return mKeyStore->importKey(data, length, filename.string(), get_user_id(targetUid),
2048 flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002049 }
2050
Kenny Root07438c82012-11-02 15:41:02 -07002051 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2052 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002053 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002054 return ::PERMISSION_DENIED;
2055 }
Kenny Root07438c82012-11-02 15:41:02 -07002056
Chad Brubaker9489b792015-04-14 11:01:45 -07002057 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002058 Blob keyBlob;
2059 String8 name8(name);
2060
Kenny Rootd38a0b02013-02-13 12:59:14 -08002061 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002062
Kenny Root655b9582013-04-04 08:37:42 -07002063 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002064 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002065 if (responseCode != ::NO_ERROR) {
2066 return responseCode;
2067 }
2068
Chad Brubaker67d2a502015-03-11 17:21:18 +00002069 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002070 if (device == NULL) {
2071 ALOGE("no keymaster device; cannot sign");
2072 return ::SYSTEM_ERROR;
2073 }
2074
2075 if (device->sign_data == NULL) {
2076 ALOGE("device doesn't implement signing");
2077 return ::SYSTEM_ERROR;
2078 }
2079
2080 keymaster_rsa_sign_params_t params;
2081 params.digest_type = DIGEST_NONE;
2082 params.padding_type = PADDING_NONE;
Chad Brubaker9489b792015-04-14 11:01:45 -07002083 int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002084 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002085 if (rc) {
2086 ALOGW("device couldn't sign data");
2087 return ::SYSTEM_ERROR;
2088 }
2089
2090 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002091 }
2092
Kenny Root07438c82012-11-02 15:41:02 -07002093 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2094 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002095 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002096 return ::PERMISSION_DENIED;
2097 }
Kenny Root70e3a862012-02-15 17:20:23 -08002098
Chad Brubaker9489b792015-04-14 11:01:45 -07002099 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002100 Blob keyBlob;
2101 String8 name8(name);
2102 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002103
Kenny Root655b9582013-04-04 08:37:42 -07002104 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002105 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002106 if (responseCode != ::NO_ERROR) {
2107 return responseCode;
2108 }
Kenny Root70e3a862012-02-15 17:20:23 -08002109
Chad Brubaker67d2a502015-03-11 17:21:18 +00002110 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002111 if (device == NULL) {
2112 return ::SYSTEM_ERROR;
2113 }
Kenny Root70e3a862012-02-15 17:20:23 -08002114
Kenny Root07438c82012-11-02 15:41:02 -07002115 if (device->verify_data == NULL) {
2116 return ::SYSTEM_ERROR;
2117 }
Kenny Root70e3a862012-02-15 17:20:23 -08002118
Kenny Root07438c82012-11-02 15:41:02 -07002119 keymaster_rsa_sign_params_t params;
2120 params.digest_type = DIGEST_NONE;
2121 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002122
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002123 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2124 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002125 if (rc) {
2126 return ::SYSTEM_ERROR;
2127 } else {
2128 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002129 }
2130 }
Kenny Root07438c82012-11-02 15:41:02 -07002131
2132 /*
2133 * TODO: The abstraction between things stored in hardware and regular blobs
2134 * of data stored on the filesystem should be moved down to keystore itself.
2135 * Unfortunately the Java code that calls this has naming conventions that it
2136 * knows about. Ideally keystore shouldn't be used to store random blobs of
2137 * data.
2138 *
2139 * Until that happens, it's necessary to have a separate "get_pubkey" and
2140 * "del_key" since the Java code doesn't really communicate what it's
2141 * intentions are.
2142 */
2143 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002144 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002145 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002146 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002147 return ::PERMISSION_DENIED;
2148 }
Kenny Root07438c82012-11-02 15:41:02 -07002149
Kenny Root07438c82012-11-02 15:41:02 -07002150 Blob keyBlob;
2151 String8 name8(name);
2152
Kenny Rootd38a0b02013-02-13 12:59:14 -08002153 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002154
Kenny Root655b9582013-04-04 08:37:42 -07002155 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002156 TYPE_KEY_PAIR);
2157 if (responseCode != ::NO_ERROR) {
2158 return responseCode;
2159 }
2160
Chad Brubaker67d2a502015-03-11 17:21:18 +00002161 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002162 if (device == NULL) {
2163 return ::SYSTEM_ERROR;
2164 }
2165
2166 if (device->get_keypair_public == NULL) {
2167 ALOGE("device has no get_keypair_public implementation!");
2168 return ::SYSTEM_ERROR;
2169 }
2170
Kenny Root17208e02013-09-04 13:56:03 -07002171 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002172 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2173 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002174 if (rc) {
2175 return ::SYSTEM_ERROR;
2176 }
2177
2178 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002179 }
Kenny Root07438c82012-11-02 15:41:02 -07002180
Kenny Root07438c82012-11-02 15:41:02 -07002181 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002182 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002183 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2184 if (result != ::NO_ERROR) {
2185 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002186 }
2187
2188 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002189 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002190
Kenny Root655b9582013-04-04 08:37:42 -07002191 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002192 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2193 }
2194
Kenny Root655b9582013-04-04 08:37:42 -07002195 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002196 return ::NO_ERROR;
2197 }
2198
2199 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002200 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002201 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2202 if (result != ::NO_ERROR) {
2203 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002204 }
2205
2206 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002207 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002208
Kenny Root655b9582013-04-04 08:37:42 -07002209 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002210 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2211 }
2212
Kenny Root655b9582013-04-04 08:37:42 -07002213 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002214 }
2215
2216 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002217 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002218 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002219 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002220 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002221 }
Kenny Root07438c82012-11-02 15:41:02 -07002222
2223 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002224 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002225
Kenny Root655b9582013-04-04 08:37:42 -07002226 if (access(filename.string(), R_OK) == -1) {
2227 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002228 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002229 }
2230
Kenny Root655b9582013-04-04 08:37:42 -07002231 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002232 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002233 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002234 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002235 }
2236
2237 struct stat s;
2238 int ret = fstat(fd, &s);
2239 close(fd);
2240 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002241 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002242 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002243 }
2244
Kenny Root36a9e232013-02-04 14:24:15 -08002245 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002246 }
2247
Kenny Rootd53bc922013-03-21 14:10:15 -07002248 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2249 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002250 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002251 pid_t spid = IPCThreadState::self()->getCallingPid();
2252 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002253 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002254 return -1L;
2255 }
2256
Chad Brubaker72593ee2015-05-12 10:42:00 -07002257 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002258 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002259 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002260 return state;
2261 }
2262
Kenny Rootd53bc922013-03-21 14:10:15 -07002263 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2264 srcUid = callingUid;
2265 } else if (!is_granted_to(callingUid, srcUid)) {
2266 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002267 return ::PERMISSION_DENIED;
2268 }
2269
Kenny Rootd53bc922013-03-21 14:10:15 -07002270 if (destUid == -1) {
2271 destUid = callingUid;
2272 }
2273
2274 if (srcUid != destUid) {
2275 if (static_cast<uid_t>(srcUid) != callingUid) {
2276 ALOGD("can only duplicate from caller to other or to same uid: "
2277 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2278 return ::PERMISSION_DENIED;
2279 }
2280
2281 if (!is_granted_to(callingUid, destUid)) {
2282 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2283 return ::PERMISSION_DENIED;
2284 }
2285 }
2286
2287 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002288 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002289
Kenny Rootd53bc922013-03-21 14:10:15 -07002290 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002291 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002292
Kenny Root655b9582013-04-04 08:37:42 -07002293 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2294 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002295 return ::SYSTEM_ERROR;
2296 }
2297
Kenny Rootd53bc922013-03-21 14:10:15 -07002298 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002299 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002300 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002301 if (responseCode != ::NO_ERROR) {
2302 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002303 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002304
Chad Brubaker72593ee2015-05-12 10:42:00 -07002305 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002306 }
2307
Kenny Root1b0e3932013-09-05 13:06:32 -07002308 int32_t is_hardware_backed(const String16& keyType) {
2309 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002310 }
2311
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002312 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002313 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002314 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002315 return ::PERMISSION_DENIED;
2316 }
2317
Robin Lee4b84fdc2014-09-24 11:56:57 +01002318 String8 prefix = String8::format("%u_", targetUid);
2319 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002320 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002321 return ::SYSTEM_ERROR;
2322 }
2323
Robin Lee4b84fdc2014-09-24 11:56:57 +01002324 for (uint32_t i = 0; i < aliases.size(); i++) {
2325 String8 name8(aliases[i]);
2326 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002327 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002328 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002329 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002330 }
2331
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002332 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2333 const keymaster1_device_t* device = mKeyStore->getDevice();
2334 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2335 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2336 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2337 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2338 device->add_rng_entropy != NULL) {
2339 devResult = device->add_rng_entropy(device, data, dataLength);
2340 }
2341 if (fallback->add_rng_entropy) {
2342 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2343 }
2344 if (devResult) {
2345 return devResult;
2346 }
2347 if (fallbackResult) {
2348 return fallbackResult;
2349 }
2350 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002351 }
2352
Chad Brubaker17d68b92015-02-05 22:04:16 -08002353 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002354 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2355 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002356 uid = getEffectiveUid(uid);
2357 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2358 flags & KEYSTORE_FLAG_ENCRYPTED);
2359 if (rc != ::NO_ERROR) {
2360 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002361 }
2362
Chad Brubaker9489b792015-04-14 11:01:45 -07002363 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002364 bool isFallback = false;
2365 keymaster_key_blob_t blob;
2366 keymaster_key_characteristics_t *out = NULL;
2367
2368 const keymaster1_device_t* device = mKeyStore->getDevice();
2369 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002370 std::vector<keymaster_key_param_t> opParams(params.params);
2371 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002372 if (device == NULL) {
2373 return ::SYSTEM_ERROR;
2374 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002375 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002376 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2377 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002378 if (!entropy) {
2379 rc = KM_ERROR_OK;
2380 } else if (device->add_rng_entropy) {
2381 rc = device->add_rng_entropy(device, entropy, entropyLength);
2382 } else {
2383 rc = KM_ERROR_UNIMPLEMENTED;
2384 }
2385 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002386 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002387 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002388 }
2389 // If the HW device didn't support generate_key or generate_key failed
2390 // fall back to the software implementation.
2391 if (rc && fallback->generate_key != NULL) {
2392 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002393 if (!entropy) {
2394 rc = KM_ERROR_OK;
2395 } else if (fallback->add_rng_entropy) {
2396 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2397 } else {
2398 rc = KM_ERROR_UNIMPLEMENTED;
2399 }
2400 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002401 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002402 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002403 }
2404
2405 if (out) {
2406 if (outCharacteristics) {
2407 outCharacteristics->characteristics = *out;
2408 } else {
2409 keymaster_free_characteristics(out);
2410 }
2411 free(out);
2412 }
2413
2414 if (rc) {
2415 return rc;
2416 }
2417
2418 String8 name8(name);
2419 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2420
2421 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2422 keyBlob.setFallback(isFallback);
2423 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2424
2425 free(const_cast<uint8_t*>(blob.key_material));
2426
Chad Brubaker72593ee2015-05-12 10:42:00 -07002427 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002428 }
2429
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002430 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002431 const keymaster_blob_t* clientId,
2432 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002433 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002434 if (!outCharacteristics) {
2435 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2436 }
2437
2438 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2439
2440 Blob keyBlob;
2441 String8 name8(name);
2442 int rc;
2443
2444 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2445 TYPE_KEYMASTER_10);
2446 if (responseCode != ::NO_ERROR) {
2447 return responseCode;
2448 }
2449 keymaster_key_blob_t key;
2450 key.key_material_size = keyBlob.getLength();
2451 key.key_material = keyBlob.getValue();
2452 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2453 keymaster_key_characteristics_t *out = NULL;
2454 if (!dev->get_key_characteristics) {
2455 ALOGW("device does not implement get_key_characteristics");
2456 return KM_ERROR_UNIMPLEMENTED;
2457 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002458 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002459 if (out) {
2460 outCharacteristics->characteristics = *out;
2461 free(out);
2462 }
2463 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002464 }
2465
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002466 int32_t importKey(const String16& name, const KeymasterArguments& params,
2467 keymaster_key_format_t format, const uint8_t *keyData,
2468 size_t keyLength, int uid, int flags,
2469 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002470 uid = getEffectiveUid(uid);
2471 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2472 flags & KEYSTORE_FLAG_ENCRYPTED);
2473 if (rc != ::NO_ERROR) {
2474 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002475 }
2476
Chad Brubaker9489b792015-04-14 11:01:45 -07002477 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002478 bool isFallback = false;
2479 keymaster_key_blob_t blob;
2480 keymaster_key_characteristics_t *out = NULL;
2481
2482 const keymaster1_device_t* device = mKeyStore->getDevice();
2483 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002484 std::vector<keymaster_key_param_t> opParams(params.params);
2485 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2486 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002487 if (device == NULL) {
2488 return ::SYSTEM_ERROR;
2489 }
2490 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2491 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002492 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002493 }
2494 if (rc && fallback->import_key != NULL) {
2495 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002496 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002497 }
2498 if (out) {
2499 if (outCharacteristics) {
2500 outCharacteristics->characteristics = *out;
2501 } else {
2502 keymaster_free_characteristics(out);
2503 }
2504 free(out);
2505 }
2506 if (rc) {
2507 return rc;
2508 }
2509
2510 String8 name8(name);
2511 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2512
2513 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2514 keyBlob.setFallback(isFallback);
2515 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2516
2517 free((void*) blob.key_material);
2518
Chad Brubaker72593ee2015-05-12 10:42:00 -07002519 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002520 }
2521
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002522 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002523 const keymaster_blob_t* clientId,
2524 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002525
2526 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2527
2528 Blob keyBlob;
2529 String8 name8(name);
2530 int rc;
2531
2532 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2533 TYPE_KEYMASTER_10);
2534 if (responseCode != ::NO_ERROR) {
2535 result->resultCode = responseCode;
2536 return;
2537 }
2538 keymaster_key_blob_t key;
2539 key.key_material_size = keyBlob.getLength();
2540 key.key_material = keyBlob.getValue();
2541 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2542 if (!dev->export_key) {
2543 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2544 return;
2545 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002546 keymaster_blob_t output = {NULL, 0};
2547 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2548 result->exportData.reset(const_cast<uint8_t*>(output.data));
2549 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002550 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002551 }
2552
Chad Brubakerad6514a2015-04-09 14:00:26 -07002553
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002554 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002555 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002556 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002557 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2558 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2559 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2560 result->resultCode = ::PERMISSION_DENIED;
2561 return;
2562 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002563 if (!checkAllowedOperationParams(params.params)) {
2564 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2565 return;
2566 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002567 Blob keyBlob;
2568 String8 name8(name);
2569 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2570 TYPE_KEYMASTER_10);
2571 if (responseCode != ::NO_ERROR) {
2572 result->resultCode = responseCode;
2573 return;
2574 }
2575 keymaster_key_blob_t key;
2576 key.key_material_size = keyBlob.getLength();
2577 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002578 keymaster_operation_handle_t handle;
2579 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002580 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002581 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002582 Unique_keymaster_key_characteristics characteristics;
2583 characteristics.reset(new keymaster_key_characteristics_t);
2584 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2585 if (err) {
2586 result->resultCode = err;
2587 return;
2588 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002589 const hw_auth_token_t* authToken = NULL;
2590 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002591 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002592 // If per-operation auth is needed we need to begin the operation and
2593 // the client will need to authorize that operation before calling
2594 // update. Any other auth issues stop here.
2595 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2596 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002597 return;
2598 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002599 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002600 // Add entropy to the device first.
2601 if (entropy) {
2602 if (dev->add_rng_entropy) {
2603 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2604 } else {
2605 err = KM_ERROR_UNIMPLEMENTED;
2606 }
2607 if (err) {
2608 result->resultCode = err;
2609 return;
2610 }
2611 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002612 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2613 keymaster_key_param_set_t outParams = {NULL, 0};
2614 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002615
2616 // If there are too many operations abort the oldest operation that was
2617 // started as pruneable and try again.
2618 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2619 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2620 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2621 if (abort(oldest) != ::NO_ERROR) {
2622 break;
2623 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002624 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002625 }
2626 if (err) {
2627 result->resultCode = err;
2628 return;
2629 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002630
Chad Brubakerad6514a2015-04-09 14:00:26 -07002631 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2632 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002633 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002634 if (authToken) {
2635 mOperationMap.setOperationAuthToken(operationToken, authToken);
2636 }
2637 // Return the authentication lookup result. If this is a per operation
2638 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2639 // application should get an auth token using the handle before the
2640 // first call to update, which will fail if keystore hasn't received the
2641 // auth token.
2642 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002643 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002644 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002645 if (outParams.params) {
2646 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2647 free(outParams.params);
2648 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002649 }
2650
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002651 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2652 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002653 if (!checkAllowedOperationParams(params.params)) {
2654 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2655 return;
2656 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002657 const keymaster1_device_t* dev;
2658 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002659 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002660 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2661 return;
2662 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002663 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002664 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2665 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002666 result->resultCode = authResult;
2667 return;
2668 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002669 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2670 keymaster_blob_t input = {data, dataLength};
2671 size_t consumed = 0;
2672 keymaster_blob_t output = {NULL, 0};
2673 keymaster_key_param_set_t outParams = {NULL, 0};
2674
2675 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2676 &output);
2677 result->data.reset(const_cast<uint8_t*>(output.data));
2678 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002679 result->inputConsumed = consumed;
2680 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002681 if (outParams.params) {
2682 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2683 free(outParams.params);
2684 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002685 }
2686
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002687 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002688 const uint8_t* signature, size_t signatureLength,
2689 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002690 if (!checkAllowedOperationParams(params.params)) {
2691 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2692 return;
2693 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002694 const keymaster1_device_t* dev;
2695 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002696 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002697 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2698 return;
2699 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002700 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002701 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2702 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002703 result->resultCode = authResult;
2704 return;
2705 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002706 keymaster_error_t err;
2707 if (entropy) {
2708 if (dev->add_rng_entropy) {
2709 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2710 } else {
2711 err = KM_ERROR_UNIMPLEMENTED;
2712 }
2713 if (err) {
2714 result->resultCode = err;
2715 return;
2716 }
2717 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002718
Chad Brubaker57e106d2015-06-01 12:59:00 -07002719 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2720 keymaster_blob_t input = {signature, signatureLength};
2721 keymaster_blob_t output = {NULL, 0};
2722 keymaster_key_param_set_t outParams = {NULL, 0};
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002723 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002724 // Remove the operation regardless of the result
2725 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002726 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002727
2728 result->data.reset(const_cast<uint8_t*>(output.data));
2729 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002730 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002731 if (outParams.params) {
2732 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2733 free(outParams.params);
2734 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002735 }
2736
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002737 int32_t abort(const sp<IBinder>& token) {
2738 const keymaster1_device_t* dev;
2739 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002740 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002741 return KM_ERROR_INVALID_OPERATION_HANDLE;
2742 }
2743 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002744 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002745 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002746 rc = KM_ERROR_UNIMPLEMENTED;
2747 } else {
2748 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002749 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002750 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002751 if (rc) {
2752 return rc;
2753 }
2754 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002755 }
2756
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002757 bool isOperationAuthorized(const sp<IBinder>& token) {
2758 const keymaster1_device_t* dev;
2759 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002760 const keymaster_key_characteristics_t* characteristics;
2761 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002762 return false;
2763 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002764 const hw_auth_token_t* authToken = NULL;
2765 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002766 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002767 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2768 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002769 }
2770
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002771 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002772 if (!checkBinderPermission(P_ADD_AUTH)) {
2773 ALOGW("addAuthToken: permission denied for %d",
2774 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002775 return ::PERMISSION_DENIED;
2776 }
2777 if (length != sizeof(hw_auth_token_t)) {
2778 return KM_ERROR_INVALID_ARGUMENT;
2779 }
2780 hw_auth_token_t* authToken = new hw_auth_token_t;
2781 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2782 // The table takes ownership of authToken.
2783 mAuthTokenTable.AddAuthenticationToken(authToken);
2784 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002785 }
2786
Kenny Root07438c82012-11-02 15:41:02 -07002787private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002788 static const int32_t UID_SELF = -1;
2789
2790 /**
2791 * Get the effective target uid for a binder operation that takes an
2792 * optional uid as the target.
2793 */
2794 inline uid_t getEffectiveUid(int32_t targetUid) {
2795 if (targetUid == UID_SELF) {
2796 return IPCThreadState::self()->getCallingUid();
2797 }
2798 return static_cast<uid_t>(targetUid);
2799 }
2800
2801 /**
2802 * Check if the caller of the current binder method has the required
2803 * permission and if acting on other uids the grants to do so.
2804 */
2805 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2806 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2807 pid_t spid = IPCThreadState::self()->getCallingPid();
2808 if (!has_permission(callingUid, permission, spid)) {
2809 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2810 return false;
2811 }
2812 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2813 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2814 return false;
2815 }
2816 return true;
2817 }
2818
2819 /**
2820 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002821 * permission and the target uid is the caller or the caller is system.
2822 */
2823 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2824 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2825 pid_t spid = IPCThreadState::self()->getCallingPid();
2826 if (!has_permission(callingUid, permission, spid)) {
2827 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2828 return false;
2829 }
2830 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2831 }
2832
2833 /**
2834 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002835 * permission or the target of the operation is the caller's uid. This is
2836 * for operation where the permission is only for cross-uid activity and all
2837 * uids are allowed to act on their own (ie: clearing all entries for a
2838 * given uid).
2839 */
2840 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2841 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2842 if (getEffectiveUid(targetUid) == callingUid) {
2843 return true;
2844 } else {
2845 return checkBinderPermission(permission, targetUid);
2846 }
2847 }
2848
2849 /**
2850 * Helper method to check that the caller has the required permission as
2851 * well as the keystore is in the unlocked state if checkUnlocked is true.
2852 *
2853 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2854 * otherwise the state of keystore when not unlocked and checkUnlocked is
2855 * true.
2856 */
2857 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2858 bool checkUnlocked = true) {
2859 if (!checkBinderPermission(permission, targetUid)) {
2860 return ::PERMISSION_DENIED;
2861 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002862 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002863 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2864 return state;
2865 }
2866
2867 return ::NO_ERROR;
2868
2869 }
2870
Kenny Root9d45d1c2013-02-14 10:32:30 -08002871 inline bool isKeystoreUnlocked(State state) {
2872 switch (state) {
2873 case ::STATE_NO_ERROR:
2874 return true;
2875 case ::STATE_UNINITIALIZED:
2876 case ::STATE_LOCKED:
2877 return false;
2878 }
2879 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002880 }
2881
Chad Brubaker67d2a502015-03-11 17:21:18 +00002882 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002883 const int32_t device_api = device->common.module->module_api_version;
2884 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2885 switch (keyType) {
2886 case TYPE_RSA:
2887 case TYPE_DSA:
2888 case TYPE_EC:
2889 return true;
2890 default:
2891 return false;
2892 }
2893 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2894 switch (keyType) {
2895 case TYPE_RSA:
2896 return true;
2897 case TYPE_DSA:
2898 return device->flags & KEYMASTER_SUPPORTS_DSA;
2899 case TYPE_EC:
2900 return device->flags & KEYMASTER_SUPPORTS_EC;
2901 default:
2902 return false;
2903 }
2904 } else {
2905 return keyType == TYPE_RSA;
2906 }
2907 }
2908
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002909 /**
2910 * Check that all keymaster_key_param_t's provided by the application are
2911 * allowed. Any parameter that keystore adds itself should be disallowed here.
2912 */
2913 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2914 for (auto param: params) {
2915 switch (param.tag) {
2916 case KM_TAG_AUTH_TOKEN:
2917 return false;
2918 default:
2919 break;
2920 }
2921 }
2922 return true;
2923 }
2924
2925 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2926 const keymaster1_device_t* dev,
2927 const std::vector<keymaster_key_param_t>& params,
2928 keymaster_key_characteristics_t* out) {
2929 UniquePtr<keymaster_blob_t> appId;
2930 UniquePtr<keymaster_blob_t> appData;
2931 for (auto param : params) {
2932 if (param.tag == KM_TAG_APPLICATION_ID) {
2933 appId.reset(new keymaster_blob_t);
2934 appId->data = param.blob.data;
2935 appId->data_length = param.blob.data_length;
2936 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2937 appData.reset(new keymaster_blob_t);
2938 appData->data = param.blob.data;
2939 appData->data_length = param.blob.data_length;
2940 }
2941 }
2942 keymaster_key_characteristics_t* result = NULL;
2943 if (!dev->get_key_characteristics) {
2944 return KM_ERROR_UNIMPLEMENTED;
2945 }
2946 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2947 appData.get(), &result);
2948 if (result) {
2949 *out = *result;
2950 free(result);
2951 }
2952 return error;
2953 }
2954
2955 /**
2956 * Get the auth token for this operation from the auth token table.
2957 *
2958 * Returns ::NO_ERROR if the auth token was set or none was required.
2959 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2960 * authorization token exists for that operation and
2961 * failOnTokenMissing is false.
2962 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2963 * token for the operation
2964 */
2965 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2966 keymaster_operation_handle_t handle,
2967 const hw_auth_token_t** authToken,
2968 bool failOnTokenMissing = true) {
2969
2970 std::vector<keymaster_key_param_t> allCharacteristics;
2971 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2972 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2973 }
2974 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2975 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2976 }
2977 keymaster::AuthTokenTable::Error err =
2978 mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
2979 allCharacteristics.size(), handle, authToken);
2980 switch (err) {
2981 case keymaster::AuthTokenTable::OK:
2982 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2983 return ::NO_ERROR;
2984 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2985 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2986 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2987 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2988 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2989 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2990 (int32_t) ::OP_AUTH_NEEDED;
2991 default:
2992 ALOGE("Unexpected FindAuthorization return value %d", err);
2993 return KM_ERROR_INVALID_ARGUMENT;
2994 }
2995 }
2996
2997 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2998 const hw_auth_token_t* token) {
2999 if (token) {
3000 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
3001 reinterpret_cast<const uint8_t*>(token),
3002 sizeof(hw_auth_token_t)));
3003 }
3004 }
3005
3006 /**
3007 * Add the auth token for the operation to the param list if the operation
3008 * requires authorization. Uses the cached result in the OperationMap if available
3009 * otherwise gets the token from the AuthTokenTable and caches the result.
3010 *
3011 * Returns ::NO_ERROR if the auth token was added or not needed.
3012 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
3013 * authenticated.
3014 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
3015 * operation token.
3016 */
3017 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3018 std::vector<keymaster_key_param_t>* params) {
3019 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07003020 mOperationMap.getOperationAuthToken(token, &authToken);
3021 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003022 const keymaster1_device_t* dev;
3023 keymaster_operation_handle_t handle;
3024 const keymaster_key_characteristics_t* characteristics = NULL;
3025 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
3026 return KM_ERROR_INVALID_OPERATION_HANDLE;
3027 }
3028 int32_t result = getAuthToken(characteristics, handle, &authToken);
3029 if (result != ::NO_ERROR) {
3030 return result;
3031 }
3032 if (authToken) {
3033 mOperationMap.setOperationAuthToken(token, authToken);
3034 }
3035 }
3036 addAuthToParams(params, authToken);
3037 return ::NO_ERROR;
3038 }
3039
Kenny Root07438c82012-11-02 15:41:02 -07003040 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003041 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003042 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07003043};
3044
3045}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003046
3047int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003048 if (argc < 2) {
3049 ALOGE("A directory must be specified!");
3050 return 1;
3051 }
3052 if (chdir(argv[1]) == -1) {
3053 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3054 return 1;
3055 }
3056
3057 Entropy entropy;
3058 if (!entropy.open()) {
3059 return 1;
3060 }
Kenny Root70e3a862012-02-15 17:20:23 -08003061
Chad Brubakerbd07a232015-06-01 10:44:27 -07003062 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003063 if (keymaster_device_initialize(&dev)) {
3064 ALOGE("keystore keymaster could not be initialized; exiting");
3065 return 1;
3066 }
3067
Chad Brubaker67d2a502015-03-11 17:21:18 +00003068 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003069 if (fallback_keymaster_device_initialize(&fallback)) {
3070 ALOGE("software keymaster could not be initialized; exiting");
3071 return 1;
3072 }
3073
Riley Spahneaabae92014-06-30 12:39:52 -07003074 ks_is_selinux_enabled = is_selinux_enabled();
3075 if (ks_is_selinux_enabled) {
3076 union selinux_callback cb;
3077 cb.func_log = selinux_log_callback;
3078 selinux_set_callback(SELINUX_CB_LOG, cb);
3079 if (getcon(&tctx) != 0) {
3080 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3081 return -1;
3082 }
3083 } else {
3084 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3085 }
3086
Chad Brubakerbd07a232015-06-01 10:44:27 -07003087 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003088 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003089 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3090 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3091 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3092 if (ret != android::OK) {
3093 ALOGE("Couldn't register binder service!");
3094 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003095 }
Kenny Root07438c82012-11-02 15:41:02 -07003096
3097 /*
3098 * We're the only thread in existence, so we're just going to process
3099 * Binder transaction as a single-threaded program.
3100 */
3101 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003102
3103 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003104 return 1;
3105}