blob: 3068756b01937b03c2ebee0c66effadef96d7307 [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
Shawn Willden80843db2015-02-24 09:31:25 -0700109static int keymaster_device_initialize(keymaster0_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800110 int rc;
111
112 const hw_module_t* mod;
113 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
114 if (rc) {
115 ALOGE("could not find any keystore module");
116 goto out;
117 }
118
Shawn Willden80843db2015-02-24 09:31:25 -0700119 rc = keymaster0_open(mod, dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800120 if (rc) {
121 ALOGE("could not open keymaster device in %s (%s)",
122 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
123 goto out;
124 }
125
126 return 0;
127
128out:
129 *dev = NULL;
130 return rc;
131}
132
Shawn Willden04006752015-04-30 11:12:33 -0600133// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
134// logger used by SoftKeymasterDevice.
135static keymaster::SoftKeymasterLogger softkeymaster_logger;
136
Chad Brubaker67d2a502015-03-11 17:21:18 +0000137static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
138 keymaster::SoftKeymasterDevice* softkeymaster =
139 new keymaster::SoftKeymasterDevice();
Shawn Willden9fd05a92015-04-30 11:01:19 -0600140 *dev = softkeymaster->keymaster_device();
141 // softkeymaster will be freed by *dev->close_device; don't delete here.
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800142 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800143}
144
Shawn Willden80843db2015-02-24 09:31:25 -0700145static void keymaster_device_release(keymaster0_device_t* dev) {
146 keymaster0_close(dev);
Kenny Root70e3a862012-02-15 17:20:23 -0800147}
148
Kenny Root07438c82012-11-02 15:41:02 -0700149/***************
150 * PERMISSIONS *
151 ***************/
152
153/* Here are the permissions, actions, users, and the main function. */
154typedef enum {
Robin Lee4e865752014-08-19 17:37:55 +0100155 P_TEST = 1 << 0,
156 P_GET = 1 << 1,
157 P_INSERT = 1 << 2,
158 P_DELETE = 1 << 3,
159 P_EXIST = 1 << 4,
160 P_SAW = 1 << 5,
161 P_RESET = 1 << 6,
162 P_PASSWORD = 1 << 7,
163 P_LOCK = 1 << 8,
164 P_UNLOCK = 1 << 9,
165 P_ZERO = 1 << 10,
166 P_SIGN = 1 << 11,
167 P_VERIFY = 1 << 12,
168 P_GRANT = 1 << 13,
169 P_DUPLICATE = 1 << 14,
170 P_CLEAR_UID = 1 << 15,
171 P_RESET_UID = 1 << 16,
172 P_SYNC_UID = 1 << 17,
173 P_PASSWORD_UID = 1 << 18,
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700174 P_ADD_AUTH = 1 << 19,
Chad Brubakerc0f031a2015-05-12 10:43:10 -0700175 P_USER_CHANGED = 1 << 20,
Kenny Root07438c82012-11-02 15:41:02 -0700176} perm_t;
177
178static struct user_euid {
179 uid_t uid;
180 uid_t euid;
181} user_euids[] = {
182 {AID_VPN, AID_SYSTEM},
183 {AID_WIFI, AID_SYSTEM},
184 {AID_ROOT, AID_SYSTEM},
185};
186
Riley Spahneaabae92014-06-30 12:39:52 -0700187/* perm_labels associcated with keystore_key SELinux class verbs. */
188const char *perm_labels[] = {
189 "test",
190 "get",
191 "insert",
192 "delete",
193 "exist",
194 "saw",
195 "reset",
196 "password",
197 "lock",
198 "unlock",
199 "zero",
200 "sign",
201 "verify",
202 "grant",
203 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100204 "clear_uid",
205 "reset_uid",
206 "sync_uid",
207 "password_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700208 "add_auth",
Chad Brubakerc0f031a2015-05-12 10:43:10 -0700209 "user_changed",
Riley Spahneaabae92014-06-30 12:39:52 -0700210};
211
Kenny Root07438c82012-11-02 15:41:02 -0700212static struct user_perm {
213 uid_t uid;
214 perm_t perms;
215} user_perms[] = {
216 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
217 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
218 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
219 {AID_ROOT, static_cast<perm_t>(P_GET) },
220};
221
222static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_TEST | P_GET | P_INSERT | P_DELETE | P_EXIST | P_SAW | P_SIGN
223 | P_VERIFY);
224
Riley Spahneaabae92014-06-30 12:39:52 -0700225static char *tctx;
226static int ks_is_selinux_enabled;
227
228static const char *get_perm_label(perm_t perm) {
229 unsigned int index = ffs(perm);
230 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
231 return perm_labels[index - 1];
232 } else {
233 ALOGE("Keystore: Failed to retrieve permission label.\n");
234 abort();
235 }
236}
237
Kenny Root655b9582013-04-04 08:37:42 -0700238/**
239 * Returns the app ID (in the Android multi-user sense) for the current
240 * UNIX UID.
241 */
242static uid_t get_app_id(uid_t uid) {
243 return uid % AID_USER;
244}
245
246/**
247 * Returns the user ID (in the Android multi-user sense) for the current
248 * UNIX UID.
249 */
250static uid_t get_user_id(uid_t uid) {
251 return uid / AID_USER;
252}
253
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700254static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700255 if (!ks_is_selinux_enabled) {
256 return true;
257 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000258
Riley Spahneaabae92014-06-30 12:39:52 -0700259 char *sctx = NULL;
260 const char *selinux_class = "keystore_key";
261 const char *str_perm = get_perm_label(perm);
262
263 if (!str_perm) {
264 return false;
265 }
266
267 if (getpidcon(spid, &sctx) != 0) {
268 ALOGE("SELinux: Failed to get source pid context.\n");
269 return false;
270 }
271
272 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
273 NULL) == 0;
274 freecon(sctx);
275 return allowed;
276}
277
278static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700279 // All system users are equivalent for multi-user support.
280 if (get_app_id(uid) == AID_SYSTEM) {
281 uid = AID_SYSTEM;
282 }
283
Kenny Root07438c82012-11-02 15:41:02 -0700284 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
285 struct user_perm user = user_perms[i];
286 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700287 return (user.perms & perm) &&
288 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700289 }
290 }
291
Riley Spahneaabae92014-06-30 12:39:52 -0700292 return (DEFAULT_PERMS & perm) &&
293 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700294}
295
Kenny Root49468902013-03-19 13:41:33 -0700296/**
297 * Returns the UID that the callingUid should act as. This is here for
298 * legacy support of the WiFi and VPN systems and should be removed
299 * when WiFi can operate in its own namespace.
300 */
Kenny Root07438c82012-11-02 15:41:02 -0700301static uid_t get_keystore_euid(uid_t uid) {
302 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
303 struct user_euid user = user_euids[i];
304 if (user.uid == uid) {
305 return user.euid;
306 }
307 }
308
309 return uid;
310}
311
Kenny Root49468902013-03-19 13:41:33 -0700312/**
313 * Returns true if the callingUid is allowed to interact in the targetUid's
314 * namespace.
315 */
316static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700317 if (callingUid == targetUid) {
318 return true;
319 }
Kenny Root49468902013-03-19 13:41:33 -0700320 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
321 struct user_euid user = user_euids[i];
322 if (user.euid == callingUid && user.uid == targetUid) {
323 return true;
324 }
325 }
326
327 return false;
328}
329
Kenny Roota91203b2012-02-15 15:00:46 -0800330/* Here is the encoding of keys. This is necessary in order to allow arbitrary
331 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
332 * into two bytes. The first byte is one of [+-.] which represents the first
333 * two bits of the character. The second byte encodes the rest of the bits into
334 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
335 * that Base64 cannot be used here due to the need of prefix match on keys. */
336
Kenny Root655b9582013-04-04 08:37:42 -0700337static size_t encode_key_length(const android::String8& keyName) {
338 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
339 size_t length = keyName.length();
340 for (int i = length; i > 0; --i, ++in) {
341 if (*in < '0' || *in > '~') {
342 ++length;
343 }
344 }
345 return length;
346}
347
Kenny Root07438c82012-11-02 15:41:02 -0700348static int encode_key(char* out, const android::String8& keyName) {
349 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
350 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800351 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700352 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800353 *out = '+' + (*in >> 6);
354 *++out = '0' + (*in & 0x3F);
355 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700356 } else {
357 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800358 }
359 }
360 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800361 return length;
362}
363
Kenny Root07438c82012-11-02 15:41:02 -0700364/*
365 * Converts from the "escaped" format on disk to actual name.
366 * This will be smaller than the input string.
367 *
368 * Characters that should combine with the next at the end will be truncated.
369 */
370static size_t decode_key_length(const char* in, size_t length) {
371 size_t outLength = 0;
372
373 for (const char* end = in + length; in < end; in++) {
374 /* This combines with the next character. */
375 if (*in < '0' || *in > '~') {
376 continue;
377 }
378
379 outLength++;
380 }
381 return outLength;
382}
383
384static void decode_key(char* out, const char* in, size_t length) {
385 for (const char* end = in + length; in < end; in++) {
386 if (*in < '0' || *in > '~') {
387 /* Truncate combining characters at the end. */
388 if (in + 1 >= end) {
389 break;
390 }
391
392 *out = (*in++ - '+') << 6;
393 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800394 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700395 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800396 }
397 }
398 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800399}
400
401static size_t readFully(int fd, uint8_t* data, size_t size) {
402 size_t remaining = size;
403 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800404 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800405 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800406 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800407 }
408 data += n;
409 remaining -= n;
410 }
411 return size;
412}
413
414static size_t writeFully(int fd, uint8_t* data, size_t size) {
415 size_t remaining = size;
416 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800417 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
418 if (n < 0) {
419 ALOGW("write failed: %s", strerror(errno));
420 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800421 }
422 data += n;
423 remaining -= n;
424 }
425 return size;
426}
427
428class Entropy {
429public:
430 Entropy() : mRandom(-1) {}
431 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800432 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800433 close(mRandom);
434 }
435 }
436
437 bool open() {
438 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800439 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
440 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800441 ALOGE("open: %s: %s", randomDevice, strerror(errno));
442 return false;
443 }
444 return true;
445 }
446
Kenny Root51878182012-03-13 12:53:19 -0700447 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800448 return (readFully(mRandom, data, size) == size);
449 }
450
451private:
452 int mRandom;
453};
454
455/* Here is the file format. There are two parts in blob.value, the secret and
456 * the description. The secret is stored in ciphertext, and its original size
457 * can be found in blob.length. The description is stored after the secret in
458 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700459 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700460 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800461 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
462 * and decryptBlob(). Thus they should not be accessed from outside. */
463
Kenny Root822c3a92012-03-23 16:34:39 -0700464/* ** Note to future implementors of encryption: **
465 * Currently this is the construction:
466 * metadata || Enc(MD5(data) || data)
467 *
468 * This should be the construction used for encrypting if re-implementing:
469 *
470 * Derive independent keys for encryption and MAC:
471 * Kenc = AES_encrypt(masterKey, "Encrypt")
472 * Kmac = AES_encrypt(masterKey, "MAC")
473 *
474 * Store this:
475 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
476 * HMAC(Kmac, metadata || Enc(data))
477 */
Kenny Roota91203b2012-02-15 15:00:46 -0800478struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700479 uint8_t version;
480 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700481 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800482 uint8_t info;
483 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700484 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800485 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700486 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800487 int32_t length; // in network byte order when encrypted
488 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
489};
490
Kenny Root822c3a92012-03-23 16:34:39 -0700491typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700492 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700493 TYPE_GENERIC = 1,
494 TYPE_MASTER_KEY = 2,
495 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800496 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700497} BlobType;
498
Kenny Rootf9119d62013-04-03 09:22:15 -0700499static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700500
Kenny Roota91203b2012-02-15 15:00:46 -0800501class Blob {
502public:
Kenny Root07438c82012-11-02 15:41:02 -0700503 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
504 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800505 memset(&mBlob, 0, sizeof(mBlob));
Kenny Roota91203b2012-02-15 15:00:46 -0800506 mBlob.length = valueLength;
507 memcpy(mBlob.value, value, valueLength);
508
509 mBlob.info = infoLength;
510 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700511
Kenny Root07438c82012-11-02 15:41:02 -0700512 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700513 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700514
Kenny Rootee8068b2013-10-07 09:49:15 -0700515 if (type == TYPE_MASTER_KEY) {
516 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
517 } else {
518 mBlob.flags = KEYSTORE_FLAG_NONE;
519 }
Kenny Roota91203b2012-02-15 15:00:46 -0800520 }
521
522 Blob(blob b) {
523 mBlob = b;
524 }
525
Alex Klyubin1773b442015-02-20 12:33:33 -0800526 Blob() {
527 memset(&mBlob, 0, sizeof(mBlob));
528 }
Kenny Roota91203b2012-02-15 15:00:46 -0800529
Kenny Root51878182012-03-13 12:53:19 -0700530 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800531 return mBlob.value;
532 }
533
Kenny Root51878182012-03-13 12:53:19 -0700534 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800535 return mBlob.length;
536 }
537
Kenny Root51878182012-03-13 12:53:19 -0700538 const uint8_t* getInfo() const {
539 return mBlob.value + mBlob.length;
540 }
541
542 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800543 return mBlob.info;
544 }
545
Kenny Root822c3a92012-03-23 16:34:39 -0700546 uint8_t getVersion() const {
547 return mBlob.version;
548 }
549
Kenny Rootf9119d62013-04-03 09:22:15 -0700550 bool isEncrypted() const {
551 if (mBlob.version < 2) {
552 return true;
553 }
554
555 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
556 }
557
558 void setEncrypted(bool encrypted) {
559 if (encrypted) {
560 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
561 } else {
562 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
563 }
564 }
565
Kenny Root17208e02013-09-04 13:56:03 -0700566 bool isFallback() const {
567 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
568 }
569
570 void setFallback(bool fallback) {
571 if (fallback) {
572 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
573 } else {
574 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
575 }
576 }
577
Kenny Root822c3a92012-03-23 16:34:39 -0700578 void setVersion(uint8_t version) {
579 mBlob.version = version;
580 }
581
582 BlobType getType() const {
583 return BlobType(mBlob.type);
584 }
585
586 void setType(BlobType type) {
587 mBlob.type = uint8_t(type);
588 }
589
Kenny Rootf9119d62013-04-03 09:22:15 -0700590 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
591 ALOGV("writing blob %s", filename);
592 if (isEncrypted()) {
593 if (state != STATE_NO_ERROR) {
594 ALOGD("couldn't insert encrypted blob while not unlocked");
595 return LOCKED;
596 }
597
598 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
599 ALOGW("Could not read random data for: %s", filename);
600 return SYSTEM_ERROR;
601 }
Kenny Roota91203b2012-02-15 15:00:46 -0800602 }
603
604 // data includes the value and the value's length
605 size_t dataLength = mBlob.length + sizeof(mBlob.length);
606 // pad data to the AES_BLOCK_SIZE
607 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
608 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
609 // encrypted data includes the digest value
610 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
611 // move info after space for padding
612 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
613 // zero padding area
614 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
615
616 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800617
Kenny Rootf9119d62013-04-03 09:22:15 -0700618 if (isEncrypted()) {
619 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800620
Kenny Rootf9119d62013-04-03 09:22:15 -0700621 uint8_t vector[AES_BLOCK_SIZE];
622 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
623 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
624 aes_key, vector, AES_ENCRYPT);
625 }
626
Kenny Roota91203b2012-02-15 15:00:46 -0800627 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
628 size_t fileLength = encryptedLength + headerLength + mBlob.info;
629
630 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800631 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
632 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
633 if (out < 0) {
634 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800635 return SYSTEM_ERROR;
636 }
637 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
638 if (close(out) != 0) {
639 return SYSTEM_ERROR;
640 }
641 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800642 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800643 unlink(tmpFileName);
644 return SYSTEM_ERROR;
645 }
Kenny Root150ca932012-11-14 14:29:02 -0800646 if (rename(tmpFileName, filename) == -1) {
647 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
648 return SYSTEM_ERROR;
649 }
650 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800651 }
652
Kenny Rootf9119d62013-04-03 09:22:15 -0700653 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
654 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800655 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
656 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800657 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
658 }
659 // fileLength may be less than sizeof(mBlob) since the in
660 // memory version has extra padding to tolerate rounding up to
661 // the AES_BLOCK_SIZE
662 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
663 if (close(in) != 0) {
664 return SYSTEM_ERROR;
665 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700666
667 if (isEncrypted() && (state != STATE_NO_ERROR)) {
668 return LOCKED;
669 }
670
Kenny Roota91203b2012-02-15 15:00:46 -0800671 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
672 if (fileLength < headerLength) {
673 return VALUE_CORRUPTED;
674 }
675
676 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700677 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800678 return VALUE_CORRUPTED;
679 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700680
681 ssize_t digestedLength;
682 if (isEncrypted()) {
683 if (encryptedLength % AES_BLOCK_SIZE != 0) {
684 return VALUE_CORRUPTED;
685 }
686
687 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
688 mBlob.vector, AES_DECRYPT);
689 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
690 uint8_t computedDigest[MD5_DIGEST_LENGTH];
691 MD5(mBlob.digested, digestedLength, computedDigest);
692 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
693 return VALUE_CORRUPTED;
694 }
695 } else {
696 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800697 }
698
699 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
700 mBlob.length = ntohl(mBlob.length);
701 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
702 return VALUE_CORRUPTED;
703 }
704 if (mBlob.info != 0) {
705 // move info from after padding to after data
706 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
707 }
Kenny Root07438c82012-11-02 15:41:02 -0700708 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800709 }
710
711private:
712 struct blob mBlob;
713};
714
Kenny Root655b9582013-04-04 08:37:42 -0700715class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800716public:
Kenny Root655b9582013-04-04 08:37:42 -0700717 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
718 asprintf(&mUserDir, "user_%u", mUserId);
719 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
720 }
721
722 ~UserState() {
723 free(mUserDir);
724 free(mMasterKeyFile);
725 }
726
727 bool initialize() {
728 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
729 ALOGE("Could not create directory '%s'", mUserDir);
730 return false;
731 }
732
733 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800734 setState(STATE_LOCKED);
735 } else {
736 setState(STATE_UNINITIALIZED);
737 }
Kenny Root70e3a862012-02-15 17:20:23 -0800738
Kenny Root655b9582013-04-04 08:37:42 -0700739 return true;
740 }
741
742 uid_t getUserId() const {
743 return mUserId;
744 }
745
746 const char* getUserDirName() const {
747 return mUserDir;
748 }
749
750 const char* getMasterKeyFileName() const {
751 return mMasterKeyFile;
752 }
753
754 void setState(State state) {
755 mState = state;
756 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
757 mRetry = MAX_RETRY;
758 }
Kenny Roota91203b2012-02-15 15:00:46 -0800759 }
760
Kenny Root51878182012-03-13 12:53:19 -0700761 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800762 return mState;
763 }
764
Kenny Root51878182012-03-13 12:53:19 -0700765 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800766 return mRetry;
767 }
768
Kenny Root655b9582013-04-04 08:37:42 -0700769 void zeroizeMasterKeysInMemory() {
770 memset(mMasterKey, 0, sizeof(mMasterKey));
771 memset(mSalt, 0, sizeof(mSalt));
772 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
773 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800774 }
775
Chad Brubaker96d6d782015-05-07 10:19:40 -0700776 bool deleteMasterKey() {
777 setState(STATE_UNINITIALIZED);
778 zeroizeMasterKeysInMemory();
779 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
780 }
781
Kenny Root655b9582013-04-04 08:37:42 -0700782 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
783 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800784 return SYSTEM_ERROR;
785 }
Kenny Root655b9582013-04-04 08:37:42 -0700786 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800787 if (response != NO_ERROR) {
788 return response;
789 }
790 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700791 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800792 }
793
Robin Lee4e865752014-08-19 17:37:55 +0100794 ResponseCode copyMasterKey(UserState* src) {
795 if (mState != STATE_UNINITIALIZED) {
796 return ::SYSTEM_ERROR;
797 }
798 if (src->getState() != STATE_NO_ERROR) {
799 return ::SYSTEM_ERROR;
800 }
801 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
802 setupMasterKeys();
803 return ::NO_ERROR;
804 }
805
Kenny Root655b9582013-04-04 08:37:42 -0700806 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800807 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
808 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
809 AES_KEY passwordAesKey;
810 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700811 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700812 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800813 }
814
Kenny Root655b9582013-04-04 08:37:42 -0700815 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
816 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800817 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800818 return SYSTEM_ERROR;
819 }
820
821 // we read the raw blob to just to get the salt to generate
822 // the AES key, then we create the Blob to use with decryptBlob
823 blob rawBlob;
824 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
825 if (close(in) != 0) {
826 return SYSTEM_ERROR;
827 }
828 // find salt at EOF if present, otherwise we have an old file
829 uint8_t* salt;
830 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
831 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
832 } else {
833 salt = NULL;
834 }
835 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
836 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
837 AES_KEY passwordAesKey;
838 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
839 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700840 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
841 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800842 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700843 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800844 }
845 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
846 // if salt was missing, generate one and write a new master key file with the salt.
847 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700848 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800849 return SYSTEM_ERROR;
850 }
Kenny Root655b9582013-04-04 08:37:42 -0700851 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800852 }
853 if (response == NO_ERROR) {
854 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
855 setupMasterKeys();
856 }
857 return response;
858 }
859 if (mRetry <= 0) {
860 reset();
861 return UNINITIALIZED;
862 }
863 --mRetry;
864 switch (mRetry) {
865 case 0: return WRONG_PASSWORD_0;
866 case 1: return WRONG_PASSWORD_1;
867 case 2: return WRONG_PASSWORD_2;
868 case 3: return WRONG_PASSWORD_3;
869 default: return WRONG_PASSWORD_3;
870 }
871 }
872
Kenny Root655b9582013-04-04 08:37:42 -0700873 AES_KEY* getEncryptionKey() {
874 return &mMasterKeyEncryption;
875 }
876
877 AES_KEY* getDecryptionKey() {
878 return &mMasterKeyDecryption;
879 }
880
Kenny Roota91203b2012-02-15 15:00:46 -0800881 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700882 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800883 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700884 // If the directory doesn't exist then nothing to do.
885 if (errno == ENOENT) {
886 return true;
887 }
Kenny Root655b9582013-04-04 08:37:42 -0700888 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800889 return false;
890 }
Kenny Root655b9582013-04-04 08:37:42 -0700891
892 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800893 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700894 // skip . and ..
895 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700896 continue;
897 }
898
899 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800900 }
901 closedir(dir);
902 return true;
903 }
904
Kenny Root655b9582013-04-04 08:37:42 -0700905private:
906 static const int MASTER_KEY_SIZE_BYTES = 16;
907 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
908
909 static const int MAX_RETRY = 4;
910 static const size_t SALT_SIZE = 16;
911
912 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
913 uint8_t* salt) {
914 size_t saltSize;
915 if (salt != NULL) {
916 saltSize = SALT_SIZE;
917 } else {
918 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
919 salt = (uint8_t*) "keystore";
920 // sizeof = 9, not strlen = 8
921 saltSize = sizeof("keystore");
922 }
923
924 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
925 saltSize, 8192, keySize, key);
926 }
927
928 bool generateSalt(Entropy* entropy) {
929 return entropy->generate_random_data(mSalt, sizeof(mSalt));
930 }
931
932 bool generateMasterKey(Entropy* entropy) {
933 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
934 return false;
935 }
936 if (!generateSalt(entropy)) {
937 return false;
938 }
939 return true;
940 }
941
942 void setupMasterKeys() {
943 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
944 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
945 setState(STATE_NO_ERROR);
946 }
947
948 uid_t mUserId;
949
950 char* mUserDir;
951 char* mMasterKeyFile;
952
953 State mState;
954 int8_t mRetry;
955
956 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
957 uint8_t mSalt[SALT_SIZE];
958
959 AES_KEY mMasterKeyEncryption;
960 AES_KEY mMasterKeyDecryption;
961};
962
963typedef struct {
964 uint32_t uid;
965 const uint8_t* filename;
966} grant_t;
967
968class KeyStore {
969public:
Chad Brubaker67d2a502015-03-11 17:21:18 +0000970 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700971 : mEntropy(entropy)
972 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800973 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700974 {
975 memset(&mMetaData, '\0', sizeof(mMetaData));
976 }
977
978 ~KeyStore() {
979 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
980 it != mGrants.end(); it++) {
981 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700982 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800983 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700984
985 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
986 it != mMasterKeys.end(); it++) {
987 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700988 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800989 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700990 }
991
Chad Brubaker67d2a502015-03-11 17:21:18 +0000992 /**
993 * Depending on the hardware keymaster version is this may return a
994 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
995 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
996 * be guarded by a check on the device's version.
997 */
998 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700999 return mDevice;
1000 }
1001
Chad Brubaker67d2a502015-03-11 17:21:18 +00001002 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001003 return mFallbackDevice;
1004 }
1005
Chad Brubaker67d2a502015-03-11 17:21:18 +00001006 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001007 return blob.isFallback() ? mFallbackDevice: mDevice;
1008 }
1009
Kenny Root655b9582013-04-04 08:37:42 -07001010 ResponseCode initialize() {
1011 readMetaData();
1012 if (upgradeKeystore()) {
1013 writeMetaData();
1014 }
1015
1016 return ::NO_ERROR;
1017 }
1018
Chad Brubaker72593ee2015-05-12 10:42:00 -07001019 State getState(uid_t userId) {
1020 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001021 }
1022
Chad Brubaker72593ee2015-05-12 10:42:00 -07001023 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1024 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001025 return userState->initialize(pw, mEntropy);
1026 }
1027
Chad Brubaker72593ee2015-05-12 10:42:00 -07001028 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1029 UserState *userState = getUserState(dstUser);
1030 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001031 return userState->copyMasterKey(initState);
1032 }
1033
Chad Brubaker72593ee2015-05-12 10:42:00 -07001034 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1035 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001036 return userState->writeMasterKey(pw, mEntropy);
1037 }
1038
Chad Brubaker72593ee2015-05-12 10:42:00 -07001039 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1040 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001041 return userState->readMasterKey(pw, mEntropy);
1042 }
1043
1044 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001045 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001046 encode_key(encoded, keyName);
1047 return android::String8(encoded);
1048 }
1049
1050 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001051 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001052 encode_key(encoded, keyName);
1053 return android::String8::format("%u_%s", uid, encoded);
1054 }
1055
1056 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001057 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001058 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001059 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001060 encoded);
1061 }
1062
Chad Brubaker96d6d782015-05-07 10:19:40 -07001063 /*
1064 * Delete entries owned by userId. If keepUnencryptedEntries is true
1065 * then only encrypted entries will be removed, otherwise all entries will
1066 * be removed.
1067 */
1068 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001069 android::String8 prefix("");
1070 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001071 UserState* userState = getUserState(userId);
1072 if (saw(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001073 return;
1074 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001075 for (uint32_t i = 0; i < aliases.size(); i++) {
1076 android::String8 filename(aliases[i]);
1077 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001078 getKeyName(filename).string());
1079 bool shouldDelete = true;
1080 if (keepUnenryptedEntries) {
1081 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001082 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001083
Chad Brubaker96d6d782015-05-07 10:19:40 -07001084 /* get can fail if the blob is encrypted and the state is
1085 * not unlocked, only skip deleting blobs that were loaded and
1086 * who are not encrypted. If there are blobs we fail to read for
1087 * other reasons err on the safe side and delete them since we
1088 * can't tell if they're encrypted.
1089 */
1090 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1091 }
1092 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001093 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001094 }
1095 }
1096 if (!userState->deleteMasterKey()) {
1097 ALOGE("Failed to delete user %d's master key", userId);
1098 }
1099 if (!keepUnenryptedEntries) {
1100 if(!userState->reset()) {
1101 ALOGE("Failed to remove user %d's directory", userId);
1102 }
1103 }
Kenny Root655b9582013-04-04 08:37:42 -07001104 }
1105
Chad Brubaker72593ee2015-05-12 10:42:00 -07001106 bool isEmpty(uid_t userId) const {
1107 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001108 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001109 return true;
1110 }
1111
1112 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001113 if (!dir) {
1114 return true;
1115 }
Kenny Root31e27462014-09-10 11:28:03 -07001116
Kenny Roota91203b2012-02-15 15:00:46 -08001117 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001118 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001119 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001120 // We only care about files.
1121 if (file->d_type != DT_REG) {
1122 continue;
1123 }
1124
1125 // Skip anything that starts with a "."
1126 if (file->d_name[0] == '.') {
1127 continue;
1128 }
1129
Kenny Root31e27462014-09-10 11:28:03 -07001130 result = false;
1131 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001132 }
1133 closedir(dir);
1134 return result;
1135 }
1136
Chad Brubaker72593ee2015-05-12 10:42:00 -07001137 void lock(uid_t userId) {
1138 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001139 userState->zeroizeMasterKeysInMemory();
1140 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001141 }
1142
Chad Brubaker72593ee2015-05-12 10:42:00 -07001143 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1144 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001145 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1146 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001147 if (rc != NO_ERROR) {
1148 return rc;
1149 }
1150
1151 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001152 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001153 /* If we upgrade the key, we need to write it to disk again. Then
1154 * it must be read it again since the blob is encrypted each time
1155 * it's written.
1156 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001157 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1158 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001159 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1160 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001161 return rc;
1162 }
1163 }
Kenny Root822c3a92012-03-23 16:34:39 -07001164 }
1165
Kenny Root17208e02013-09-04 13:56:03 -07001166 /*
1167 * This will upgrade software-backed keys to hardware-backed keys when
1168 * the HAL for the device supports the newer key types.
1169 */
1170 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1171 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1172 && keyBlob->isFallback()) {
1173 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001174 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001175
1176 // The HAL allowed the import, reget the key to have the "fresh"
1177 // version.
1178 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001179 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001180 }
1181 }
1182
Kenny Rootd53bc922013-03-21 14:10:15 -07001183 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001184 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1185 return KEY_NOT_FOUND;
1186 }
1187
1188 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001189 }
1190
Chad Brubaker72593ee2015-05-12 10:42:00 -07001191 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1192 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001193 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1194 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001195 }
1196
Chad Brubaker72593ee2015-05-12 10:42:00 -07001197 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001198 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001199 ResponseCode rc = get(filename, &keyBlob, type, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001200 if (rc != ::NO_ERROR) {
1201 return rc;
1202 }
1203
1204 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1205 // A device doesn't have to implement delete_keypair.
1206 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1207 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1208 rc = ::SYSTEM_ERROR;
1209 }
1210 }
1211 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001212 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1213 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1214 if (dev->delete_key) {
1215 keymaster_key_blob_t blob;
1216 blob.key_material = keyBlob.getValue();
1217 blob.key_material_size = keyBlob.getLength();
1218 dev->delete_key(dev, &blob);
1219 }
1220 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001221 if (rc != ::NO_ERROR) {
1222 return rc;
1223 }
1224
1225 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1226 }
1227
1228 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001229 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001230
Chad Brubaker72593ee2015-05-12 10:42:00 -07001231 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001232 size_t n = prefix.length();
1233
1234 DIR* dir = opendir(userState->getUserDirName());
1235 if (!dir) {
1236 ALOGW("can't open directory for user: %s", strerror(errno));
1237 return ::SYSTEM_ERROR;
1238 }
1239
1240 struct dirent* file;
1241 while ((file = readdir(dir)) != NULL) {
1242 // We only care about files.
1243 if (file->d_type != DT_REG) {
1244 continue;
1245 }
1246
1247 // Skip anything that starts with a "."
1248 if (file->d_name[0] == '.') {
1249 continue;
1250 }
1251
1252 if (!strncmp(prefix.string(), file->d_name, n)) {
1253 const char* p = &file->d_name[n];
1254 size_t plen = strlen(p);
1255
1256 size_t extra = decode_key_length(p, plen);
1257 char *match = (char*) malloc(extra + 1);
1258 if (match != NULL) {
1259 decode_key(match, p, plen);
1260 matches->push(android::String16(match, extra));
1261 free(match);
1262 } else {
1263 ALOGW("could not allocate match of size %zd", extra);
1264 }
1265 }
1266 }
1267 closedir(dir);
1268 return ::NO_ERROR;
1269 }
1270
Kenny Root07438c82012-11-02 15:41:02 -07001271 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001272 const grant_t* existing = getGrant(filename, granteeUid);
1273 if (existing == NULL) {
1274 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001275 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001276 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001277 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001278 }
1279 }
1280
Kenny Root07438c82012-11-02 15:41:02 -07001281 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001282 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1283 it != mGrants.end(); it++) {
1284 grant_t* grant = *it;
1285 if (grant->uid == granteeUid
1286 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1287 mGrants.erase(it);
1288 return true;
1289 }
Kenny Root70e3a862012-02-15 17:20:23 -08001290 }
Kenny Root70e3a862012-02-15 17:20:23 -08001291 return false;
1292 }
1293
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001294 bool hasGrant(const char* filename, const uid_t uid) const {
1295 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001296 }
1297
Chad Brubaker72593ee2015-05-12 10:42:00 -07001298 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001299 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001300 uint8_t* data;
1301 size_t dataLength;
1302 int rc;
1303
1304 if (mDevice->import_keypair == NULL) {
1305 ALOGE("Keymaster doesn't support import!");
1306 return SYSTEM_ERROR;
1307 }
1308
Kenny Root17208e02013-09-04 13:56:03 -07001309 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001310 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001311 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001312 /*
1313 * Maybe the device doesn't support this type of key. Try to use the
1314 * software fallback keymaster implementation. This is a little bit
1315 * lazier than checking the PKCS#8 key type, but the software
1316 * implementation will do that anyway.
1317 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001318 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001319 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001320
1321 if (rc) {
1322 ALOGE("Error while importing keypair: %d", rc);
1323 return SYSTEM_ERROR;
1324 }
Kenny Root822c3a92012-03-23 16:34:39 -07001325 }
1326
1327 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1328 free(data);
1329
Kenny Rootf9119d62013-04-03 09:22:15 -07001330 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001331 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001332
Chad Brubaker72593ee2015-05-12 10:42:00 -07001333 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001334 }
1335
Kenny Root1b0e3932013-09-05 13:06:32 -07001336 bool isHardwareBacked(const android::String16& keyType) const {
1337 if (mDevice == NULL) {
1338 ALOGW("can't get keymaster device");
1339 return false;
1340 }
1341
1342 if (sRSAKeyType == keyType) {
1343 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1344 } else {
1345 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1346 && (mDevice->common.module->module_api_version
1347 >= KEYMASTER_MODULE_API_VERSION_0_2);
1348 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001349 }
1350
Kenny Root655b9582013-04-04 08:37:42 -07001351 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1352 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001353 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001354 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001355
Chad Brubaker72593ee2015-05-12 10:42:00 -07001356 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001357 if (responseCode == NO_ERROR) {
1358 return responseCode;
1359 }
1360
1361 // If this is one of the legacy UID->UID mappings, use it.
1362 uid_t euid = get_keystore_euid(uid);
1363 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001364 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001365 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001366 if (responseCode == NO_ERROR) {
1367 return responseCode;
1368 }
1369 }
1370
1371 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001372 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001373 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001374 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001375 if (end[0] != '_' || end[1] == 0) {
1376 return KEY_NOT_FOUND;
1377 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001378 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001379 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001380 if (!hasGrant(filepath8.string(), uid)) {
1381 return responseCode;
1382 }
1383
1384 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001385 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001386 }
1387
1388 /**
1389 * Returns any existing UserState or creates it if it doesn't exist.
1390 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001391 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001392 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1393 it != mMasterKeys.end(); it++) {
1394 UserState* state = *it;
1395 if (state->getUserId() == userId) {
1396 return state;
1397 }
1398 }
1399
1400 UserState* userState = new UserState(userId);
1401 if (!userState->initialize()) {
1402 /* There's not much we can do if initialization fails. Trying to
1403 * unlock the keystore for that user will fail as well, so any
1404 * subsequent request for this user will just return SYSTEM_ERROR.
1405 */
1406 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1407 }
1408 mMasterKeys.add(userState);
1409 return userState;
1410 }
1411
1412 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001413 * Returns any existing UserState or creates it if it doesn't exist.
1414 */
1415 UserState* getUserStateByUid(uid_t uid) {
1416 uid_t userId = get_user_id(uid);
1417 return getUserState(userId);
1418 }
1419
1420 /**
Kenny Root655b9582013-04-04 08:37:42 -07001421 * Returns NULL if the UserState doesn't already exist.
1422 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001423 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001424 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1425 it != mMasterKeys.end(); it++) {
1426 UserState* state = *it;
1427 if (state->getUserId() == userId) {
1428 return state;
1429 }
1430 }
1431
1432 return NULL;
1433 }
1434
Chad Brubaker72593ee2015-05-12 10:42:00 -07001435 /**
1436 * Returns NULL if the UserState doesn't already exist.
1437 */
1438 const UserState* getUserStateByUid(uid_t uid) const {
1439 uid_t userId = get_user_id(uid);
1440 return getUserState(userId);
1441 }
1442
Kenny Roota91203b2012-02-15 15:00:46 -08001443private:
Kenny Root655b9582013-04-04 08:37:42 -07001444 static const char* sOldMasterKey;
1445 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001446 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001447 Entropy* mEntropy;
1448
Chad Brubaker67d2a502015-03-11 17:21:18 +00001449 keymaster1_device_t* mDevice;
1450 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001451
Kenny Root655b9582013-04-04 08:37:42 -07001452 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001453
Kenny Root655b9582013-04-04 08:37:42 -07001454 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001455
Kenny Root655b9582013-04-04 08:37:42 -07001456 typedef struct {
1457 uint32_t version;
1458 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001459
Kenny Root655b9582013-04-04 08:37:42 -07001460 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001461
Kenny Root655b9582013-04-04 08:37:42 -07001462 const grant_t* getGrant(const char* filename, uid_t uid) const {
1463 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1464 it != mGrants.end(); it++) {
1465 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001466 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001467 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001468 return grant;
1469 }
1470 }
Kenny Root70e3a862012-02-15 17:20:23 -08001471 return NULL;
1472 }
1473
Kenny Root822c3a92012-03-23 16:34:39 -07001474 /**
1475 * Upgrade code. This will upgrade the key from the current version
1476 * to whatever is newest.
1477 */
Kenny Root655b9582013-04-04 08:37:42 -07001478 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1479 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001480 bool updated = false;
1481 uint8_t version = oldVersion;
1482
1483 /* From V0 -> V1: All old types were unknown */
1484 if (version == 0) {
1485 ALOGV("upgrading to version 1 and setting type %d", type);
1486
1487 blob->setType(type);
1488 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001489 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001490 }
1491 version = 1;
1492 updated = true;
1493 }
1494
Kenny Rootf9119d62013-04-03 09:22:15 -07001495 /* From V1 -> V2: All old keys were encrypted */
1496 if (version == 1) {
1497 ALOGV("upgrading to version 2");
1498
1499 blob->setEncrypted(true);
1500 version = 2;
1501 updated = true;
1502 }
1503
Kenny Root822c3a92012-03-23 16:34:39 -07001504 /*
1505 * If we've updated, set the key blob to the right version
1506 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001507 */
Kenny Root822c3a92012-03-23 16:34:39 -07001508 if (updated) {
1509 ALOGV("updated and writing file %s", filename);
1510 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001511 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001512
1513 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001514 }
1515
1516 /**
1517 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1518 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1519 * Then it overwrites the original blob with the new blob
1520 * format that is returned from the keymaster.
1521 */
Kenny Root655b9582013-04-04 08:37:42 -07001522 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001523 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1524 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1525 if (b.get() == NULL) {
1526 ALOGE("Problem instantiating BIO");
1527 return SYSTEM_ERROR;
1528 }
1529
1530 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1531 if (pkey.get() == NULL) {
1532 ALOGE("Couldn't read old PEM file");
1533 return SYSTEM_ERROR;
1534 }
1535
1536 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1537 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1538 if (len < 0) {
1539 ALOGE("Couldn't measure PKCS#8 length");
1540 return SYSTEM_ERROR;
1541 }
1542
Kenny Root70c98892013-02-07 09:10:36 -08001543 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1544 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001545 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1546 ALOGE("Couldn't convert to PKCS#8");
1547 return SYSTEM_ERROR;
1548 }
1549
Chad Brubaker72593ee2015-05-12 10:42:00 -07001550 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001551 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001552 if (rc != NO_ERROR) {
1553 return rc;
1554 }
1555
Kenny Root655b9582013-04-04 08:37:42 -07001556 return get(filename, blob, TYPE_KEY_PAIR, uid);
1557 }
1558
1559 void readMetaData() {
1560 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1561 if (in < 0) {
1562 return;
1563 }
1564 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1565 if (fileLength != sizeof(mMetaData)) {
1566 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1567 sizeof(mMetaData));
1568 }
1569 close(in);
1570 }
1571
1572 void writeMetaData() {
1573 const char* tmpFileName = ".metadata.tmp";
1574 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1575 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1576 if (out < 0) {
1577 ALOGE("couldn't write metadata file: %s", strerror(errno));
1578 return;
1579 }
1580 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1581 if (fileLength != sizeof(mMetaData)) {
1582 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1583 sizeof(mMetaData));
1584 }
1585 close(out);
1586 rename(tmpFileName, sMetaDataFile);
1587 }
1588
1589 bool upgradeKeystore() {
1590 bool upgraded = false;
1591
1592 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001593 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001594
1595 // Initialize first so the directory is made.
1596 userState->initialize();
1597
1598 // Migrate the old .masterkey file to user 0.
1599 if (access(sOldMasterKey, R_OK) == 0) {
1600 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1601 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1602 return false;
1603 }
1604 }
1605
1606 // Initialize again in case we had a key.
1607 userState->initialize();
1608
1609 // Try to migrate existing keys.
1610 DIR* dir = opendir(".");
1611 if (!dir) {
1612 // Give up now; maybe we can upgrade later.
1613 ALOGE("couldn't open keystore's directory; something is wrong");
1614 return false;
1615 }
1616
1617 struct dirent* file;
1618 while ((file = readdir(dir)) != NULL) {
1619 // We only care about files.
1620 if (file->d_type != DT_REG) {
1621 continue;
1622 }
1623
1624 // Skip anything that starts with a "."
1625 if (file->d_name[0] == '.') {
1626 continue;
1627 }
1628
1629 // Find the current file's user.
1630 char* end;
1631 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1632 if (end[0] != '_' || end[1] == 0) {
1633 continue;
1634 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001635 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001636 if (otherUser->getUserId() != 0) {
1637 unlinkat(dirfd(dir), file->d_name, 0);
1638 }
1639
1640 // Rename the file into user directory.
1641 DIR* otherdir = opendir(otherUser->getUserDirName());
1642 if (otherdir == NULL) {
1643 ALOGW("couldn't open user directory for rename");
1644 continue;
1645 }
1646 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1647 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1648 }
1649 closedir(otherdir);
1650 }
1651 closedir(dir);
1652
1653 mMetaData.version = 1;
1654 upgraded = true;
1655 }
1656
1657 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001658 }
Kenny Roota91203b2012-02-15 15:00:46 -08001659};
1660
Kenny Root655b9582013-04-04 08:37:42 -07001661const char* KeyStore::sOldMasterKey = ".masterkey";
1662const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001663
Kenny Root1b0e3932013-09-05 13:06:32 -07001664const android::String16 KeyStore::sRSAKeyType("RSA");
1665
Kenny Root07438c82012-11-02 15:41:02 -07001666namespace android {
1667class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1668public:
1669 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001670 : mKeyStore(keyStore),
1671 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001672 {
Kenny Roota91203b2012-02-15 15:00:46 -08001673 }
Kenny Roota91203b2012-02-15 15:00:46 -08001674
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001675 void binderDied(const wp<IBinder>& who) {
1676 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1677 for (auto token: operations) {
1678 abort(token);
1679 }
Kenny Root822c3a92012-03-23 16:34:39 -07001680 }
Kenny Roota91203b2012-02-15 15:00:46 -08001681
Kenny Root07438c82012-11-02 15:41:02 -07001682 int32_t test() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001683 if (!checkBinderPermission(P_TEST)) {
Kenny Root07438c82012-11-02 15:41:02 -07001684 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001685 }
Kenny Roota91203b2012-02-15 15:00:46 -08001686
Chad Brubaker72593ee2015-05-12 10:42:00 -07001687 return mKeyStore->getState(get_user_id(IPCThreadState::self()->getCallingUid()));
Kenny Root298e7b12012-03-26 13:54:44 -07001688 }
1689
Kenny Root07438c82012-11-02 15:41:02 -07001690 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001691 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001692 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001693 }
Kenny Root07438c82012-11-02 15:41:02 -07001694
Chad Brubaker9489b792015-04-14 11:01:45 -07001695 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001696 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001697 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001698
Kenny Root655b9582013-04-04 08:37:42 -07001699 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001700 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001701 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001702 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001703 *item = NULL;
1704 *itemLength = 0;
1705 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001706 }
Kenny Roota91203b2012-02-15 15:00:46 -08001707
Kenny Root07438c82012-11-02 15:41:02 -07001708 *item = (uint8_t*) malloc(keyBlob.getLength());
1709 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1710 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001711
Kenny Root07438c82012-11-02 15:41:02 -07001712 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001713 }
1714
Kenny Rootf9119d62013-04-03 09:22:15 -07001715 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1716 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001717 targetUid = getEffectiveUid(targetUid);
1718 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1719 flags & KEYSTORE_FLAG_ENCRYPTED);
1720 if (result != ::NO_ERROR) {
1721 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001722 }
1723
Kenny Root07438c82012-11-02 15:41:02 -07001724 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001725 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001726
1727 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001728 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1729
Chad Brubaker72593ee2015-05-12 10:42:00 -07001730 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001731 }
1732
Kenny Root49468902013-03-19 13:41:33 -07001733 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001734 targetUid = getEffectiveUid(targetUid);
1735 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001736 return ::PERMISSION_DENIED;
1737 }
Kenny Root07438c82012-11-02 15:41:02 -07001738 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001739 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001740 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001741 }
1742
Kenny Root49468902013-03-19 13:41:33 -07001743 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001744 targetUid = getEffectiveUid(targetUid);
1745 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001746 return ::PERMISSION_DENIED;
1747 }
1748
Kenny Root07438c82012-11-02 15:41:02 -07001749 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001750 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001751
Kenny Root655b9582013-04-04 08:37:42 -07001752 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001753 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1754 }
1755 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001756 }
1757
Kenny Root49468902013-03-19 13:41:33 -07001758 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001759 targetUid = getEffectiveUid(targetUid);
1760 if (!checkBinderPermission(P_SAW, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001761 return ::PERMISSION_DENIED;
1762 }
Kenny Root07438c82012-11-02 15:41:02 -07001763 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001764 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001765
Chad Brubaker72593ee2015-05-12 10:42:00 -07001766 if (mKeyStore->saw(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001767 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001768 }
Kenny Root07438c82012-11-02 15:41:02 -07001769 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001770 }
1771
Kenny Root07438c82012-11-02 15:41:02 -07001772 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001773 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001774 return ::PERMISSION_DENIED;
1775 }
1776
Chad Brubaker9489b792015-04-14 11:01:45 -07001777 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001778 mKeyStore->resetUser(get_user_id(callingUid), false);
1779 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001780 }
1781
Chad Brubaker96d6d782015-05-07 10:19:40 -07001782 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001783 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001784 return ::PERMISSION_DENIED;
1785 }
Kenny Root70e3a862012-02-15 17:20:23 -08001786
Kenny Root07438c82012-11-02 15:41:02 -07001787 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001788 // Flush the auth token table to prevent stale tokens from sticking
1789 // around.
1790 mAuthTokenTable.Clear();
1791
1792 if (password.size() == 0) {
1793 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001794 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001795 return ::NO_ERROR;
1796 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001797 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001798 case ::STATE_UNINITIALIZED: {
1799 // generate master key, encrypt with password, write to file,
1800 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001801 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001802 }
1803 case ::STATE_NO_ERROR: {
1804 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001805 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001806 }
1807 case ::STATE_LOCKED: {
1808 ALOGE("Changing user %d's password while locked, clearing old encryption",
1809 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001810 mKeyStore->resetUser(userId, true);
1811 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001812 }
Kenny Root07438c82012-11-02 15:41:02 -07001813 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001814 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001815 }
Kenny Root70e3a862012-02-15 17:20:23 -08001816 }
1817
Chad Brubakerc0f031a2015-05-12 10:43:10 -07001818 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1819 if (!checkBinderPermission(P_USER_CHANGED)) {
1820 return ::PERMISSION_DENIED;
1821 }
1822
1823 // Sanity check that the new user has an empty keystore.
1824 if (!mKeyStore->isEmpty(userId)) {
1825 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
1826 }
1827 // Unconditionally clear the keystore, just to be safe.
1828 mKeyStore->resetUser(userId, false);
1829
1830 // If the user has a parent user then use the parent's
1831 // masterkey/password, otherwise there's nothing to do.
1832 if (parentId != -1) {
1833 return mKeyStore->copyMasterKey(parentId, userId);
1834 } else {
1835 return ::NO_ERROR;
1836 }
1837 }
1838
1839 int32_t onUserRemoved(int32_t userId) {
1840 if (!checkBinderPermission(P_USER_CHANGED)) {
1841 return ::PERMISSION_DENIED;
1842 }
1843
1844 mKeyStore->resetUser(userId, false);
1845 return ::NO_ERROR;
1846 }
1847
Kenny Root07438c82012-11-02 15:41:02 -07001848 int32_t lock() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001849 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001850 return ::PERMISSION_DENIED;
1851 }
Kenny Root70e3a862012-02-15 17:20:23 -08001852
Chad Brubaker72593ee2015-05-12 10:42:00 -07001853 uid_t userId = get_user_id(IPCThreadState::self()->getCallingUid());
1854 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001855 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001856 ALOGD("calling lock in state: %d", state);
1857 return state;
1858 }
1859
Chad Brubaker72593ee2015-05-12 10:42:00 -07001860 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07001861 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001862 }
1863
Chad Brubaker96d6d782015-05-07 10:19:40 -07001864 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001865 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001866 return ::PERMISSION_DENIED;
1867 }
1868
Chad Brubaker72593ee2015-05-12 10:42:00 -07001869 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001870 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001871 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001872 return state;
1873 }
1874
1875 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001876 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001877 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001878 }
1879
Kenny Root07438c82012-11-02 15:41:02 -07001880 int32_t zero() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001881 if (!checkBinderPermission(P_ZERO)) {
Kenny Root07438c82012-11-02 15:41:02 -07001882 return -1;
1883 }
Kenny Root70e3a862012-02-15 17:20:23 -08001884
Chad Brubaker9489b792015-04-14 11:01:45 -07001885 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker72593ee2015-05-12 10:42:00 -07001886 return mKeyStore->isEmpty(get_user_id(callingUid)) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001887 }
1888
Kenny Root96427ba2013-08-16 14:02:41 -07001889 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1890 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001891 targetUid = getEffectiveUid(targetUid);
1892 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1893 flags & KEYSTORE_FLAG_ENCRYPTED);
1894 if (result != ::NO_ERROR) {
1895 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001896 }
Kenny Root07438c82012-11-02 15:41:02 -07001897 uint8_t* data;
1898 size_t dataLength;
1899 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001900 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001901
Chad Brubaker67d2a502015-03-11 17:21:18 +00001902 const keymaster1_device_t* device = mKeyStore->getDevice();
1903 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001904 if (device == NULL) {
1905 return ::SYSTEM_ERROR;
1906 }
1907
1908 if (device->generate_keypair == NULL) {
1909 return ::SYSTEM_ERROR;
1910 }
1911
Kenny Root17208e02013-09-04 13:56:03 -07001912 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001913 keymaster_dsa_keygen_params_t dsa_params;
1914 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001915
Kenny Root96427ba2013-08-16 14:02:41 -07001916 if (keySize == -1) {
1917 keySize = DSA_DEFAULT_KEY_SIZE;
1918 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1919 || keySize > DSA_MAX_KEY_SIZE) {
1920 ALOGI("invalid key size %d", keySize);
1921 return ::SYSTEM_ERROR;
1922 }
1923 dsa_params.key_size = keySize;
1924
1925 if (args->size() == 3) {
1926 sp<KeystoreArg> gArg = args->itemAt(0);
1927 sp<KeystoreArg> pArg = args->itemAt(1);
1928 sp<KeystoreArg> qArg = args->itemAt(2);
1929
1930 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1931 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1932 dsa_params.generator_len = gArg->size();
1933
1934 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1935 dsa_params.prime_p_len = pArg->size();
1936
1937 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1938 dsa_params.prime_q_len = qArg->size();
1939 } else {
1940 ALOGI("not all DSA parameters were read");
1941 return ::SYSTEM_ERROR;
1942 }
1943 } else if (args->size() != 0) {
1944 ALOGI("DSA args must be 3");
1945 return ::SYSTEM_ERROR;
1946 }
1947
Kenny Root1d448c02013-11-21 10:36:53 -08001948 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001949 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1950 } else {
1951 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001952 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1953 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001954 }
1955 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001956 keymaster_ec_keygen_params_t ec_params;
1957 memset(&ec_params, '\0', sizeof(ec_params));
1958
1959 if (keySize == -1) {
1960 keySize = EC_DEFAULT_KEY_SIZE;
1961 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1962 ALOGI("invalid key size %d", keySize);
1963 return ::SYSTEM_ERROR;
1964 }
1965 ec_params.field_size = keySize;
1966
Kenny Root1d448c02013-11-21 10:36:53 -08001967 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001968 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1969 } else {
1970 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001971 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001972 }
Kenny Root96427ba2013-08-16 14:02:41 -07001973 } else if (keyType == EVP_PKEY_RSA) {
1974 keymaster_rsa_keygen_params_t rsa_params;
1975 memset(&rsa_params, '\0', sizeof(rsa_params));
1976 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1977
1978 if (keySize == -1) {
1979 keySize = RSA_DEFAULT_KEY_SIZE;
1980 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1981 ALOGI("invalid key size %d", keySize);
1982 return ::SYSTEM_ERROR;
1983 }
1984 rsa_params.modulus_size = keySize;
1985
1986 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001987 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001988 return ::SYSTEM_ERROR;
1989 } else if (args->size() == 1) {
1990 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1991 if (pubExpBlob != NULL) {
1992 Unique_BIGNUM pubExpBn(
1993 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1994 pubExpBlob->size(), NULL));
1995 if (pubExpBn.get() == NULL) {
1996 ALOGI("Could not convert public exponent to BN");
1997 return ::SYSTEM_ERROR;
1998 }
1999 unsigned long pubExp = BN_get_word(pubExpBn.get());
2000 if (pubExp == 0xFFFFFFFFL) {
2001 ALOGI("cannot represent public exponent as a long value");
2002 return ::SYSTEM_ERROR;
2003 }
2004 rsa_params.public_exponent = pubExp;
2005 }
2006 }
2007
2008 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
2009 } else {
2010 ALOGW("Unsupported key type %d", keyType);
2011 rc = -1;
2012 }
2013
Kenny Root07438c82012-11-02 15:41:02 -07002014 if (rc) {
2015 return ::SYSTEM_ERROR;
2016 }
2017
Kenny Root655b9582013-04-04 08:37:42 -07002018 String8 name8(name);
Chad Brubaker9489b792015-04-14 11:01:45 -07002019 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002020
2021 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
2022 free(data);
2023
Kenny Rootee8068b2013-10-07 09:49:15 -07002024 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07002025 keyBlob.setFallback(isFallback);
2026
Chad Brubaker72593ee2015-05-12 10:42:00 -07002027 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08002028 }
2029
Kenny Rootf9119d62013-04-03 09:22:15 -07002030 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2031 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002032 targetUid = getEffectiveUid(targetUid);
2033 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2034 flags & KEYSTORE_FLAG_ENCRYPTED);
2035 if (result != ::NO_ERROR) {
2036 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002037 }
Kenny Root07438c82012-11-02 15:41:02 -07002038 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002039 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002040
Chad Brubaker72593ee2015-05-12 10:42:00 -07002041 return mKeyStore->importKey(data, length, filename.string(), get_user_id(targetUid),
2042 flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002043 }
2044
Kenny Root07438c82012-11-02 15:41:02 -07002045 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2046 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002047 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002048 return ::PERMISSION_DENIED;
2049 }
Kenny Root07438c82012-11-02 15:41:02 -07002050
Chad Brubaker9489b792015-04-14 11:01:45 -07002051 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002052 Blob keyBlob;
2053 String8 name8(name);
2054
Kenny Rootd38a0b02013-02-13 12:59:14 -08002055 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002056
Kenny Root655b9582013-04-04 08:37:42 -07002057 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002058 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002059 if (responseCode != ::NO_ERROR) {
2060 return responseCode;
2061 }
2062
Chad Brubaker67d2a502015-03-11 17:21:18 +00002063 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002064 if (device == NULL) {
2065 ALOGE("no keymaster device; cannot sign");
2066 return ::SYSTEM_ERROR;
2067 }
2068
2069 if (device->sign_data == NULL) {
2070 ALOGE("device doesn't implement signing");
2071 return ::SYSTEM_ERROR;
2072 }
2073
2074 keymaster_rsa_sign_params_t params;
2075 params.digest_type = DIGEST_NONE;
2076 params.padding_type = PADDING_NONE;
Chad Brubaker9489b792015-04-14 11:01:45 -07002077 int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002078 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002079 if (rc) {
2080 ALOGW("device couldn't sign data");
2081 return ::SYSTEM_ERROR;
2082 }
2083
2084 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002085 }
2086
Kenny Root07438c82012-11-02 15:41:02 -07002087 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2088 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002089 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002090 return ::PERMISSION_DENIED;
2091 }
Kenny Root70e3a862012-02-15 17:20:23 -08002092
Chad Brubaker9489b792015-04-14 11:01:45 -07002093 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002094 Blob keyBlob;
2095 String8 name8(name);
2096 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002097
Kenny Root655b9582013-04-04 08:37:42 -07002098 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002099 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002100 if (responseCode != ::NO_ERROR) {
2101 return responseCode;
2102 }
Kenny Root70e3a862012-02-15 17:20:23 -08002103
Chad Brubaker67d2a502015-03-11 17:21:18 +00002104 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002105 if (device == NULL) {
2106 return ::SYSTEM_ERROR;
2107 }
Kenny Root70e3a862012-02-15 17:20:23 -08002108
Kenny Root07438c82012-11-02 15:41:02 -07002109 if (device->verify_data == NULL) {
2110 return ::SYSTEM_ERROR;
2111 }
Kenny Root70e3a862012-02-15 17:20:23 -08002112
Kenny Root07438c82012-11-02 15:41:02 -07002113 keymaster_rsa_sign_params_t params;
2114 params.digest_type = DIGEST_NONE;
2115 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002116
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002117 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2118 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002119 if (rc) {
2120 return ::SYSTEM_ERROR;
2121 } else {
2122 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002123 }
2124 }
Kenny Root07438c82012-11-02 15:41:02 -07002125
2126 /*
2127 * TODO: The abstraction between things stored in hardware and regular blobs
2128 * of data stored on the filesystem should be moved down to keystore itself.
2129 * Unfortunately the Java code that calls this has naming conventions that it
2130 * knows about. Ideally keystore shouldn't be used to store random blobs of
2131 * data.
2132 *
2133 * Until that happens, it's necessary to have a separate "get_pubkey" and
2134 * "del_key" since the Java code doesn't really communicate what it's
2135 * intentions are.
2136 */
2137 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002138 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002139 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002140 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002141 return ::PERMISSION_DENIED;
2142 }
Kenny Root07438c82012-11-02 15:41:02 -07002143
Kenny Root07438c82012-11-02 15:41:02 -07002144 Blob keyBlob;
2145 String8 name8(name);
2146
Kenny Rootd38a0b02013-02-13 12:59:14 -08002147 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002148
Kenny Root655b9582013-04-04 08:37:42 -07002149 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002150 TYPE_KEY_PAIR);
2151 if (responseCode != ::NO_ERROR) {
2152 return responseCode;
2153 }
2154
Chad Brubaker67d2a502015-03-11 17:21:18 +00002155 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002156 if (device == NULL) {
2157 return ::SYSTEM_ERROR;
2158 }
2159
2160 if (device->get_keypair_public == NULL) {
2161 ALOGE("device has no get_keypair_public implementation!");
2162 return ::SYSTEM_ERROR;
2163 }
2164
Kenny Root17208e02013-09-04 13:56:03 -07002165 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002166 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2167 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002168 if (rc) {
2169 return ::SYSTEM_ERROR;
2170 }
2171
2172 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002173 }
Kenny Root07438c82012-11-02 15:41:02 -07002174
Kenny Root49468902013-03-19 13:41:33 -07002175 int32_t del_key(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002176 return del(name, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002177 }
2178
2179 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002180 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002181 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2182 if (result != ::NO_ERROR) {
2183 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002184 }
2185
2186 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002187 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002188
Kenny Root655b9582013-04-04 08:37:42 -07002189 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002190 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2191 }
2192
Kenny Root655b9582013-04-04 08:37:42 -07002193 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002194 return ::NO_ERROR;
2195 }
2196
2197 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002198 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002199 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2200 if (result != ::NO_ERROR) {
2201 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002202 }
2203
2204 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002205 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002206
Kenny Root655b9582013-04-04 08:37:42 -07002207 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002208 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2209 }
2210
Kenny Root655b9582013-04-04 08:37:42 -07002211 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002212 }
2213
2214 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002215 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002216 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002217 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002218 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002219 }
Kenny Root07438c82012-11-02 15:41:02 -07002220
2221 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002222 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002223
Kenny Root655b9582013-04-04 08:37:42 -07002224 if (access(filename.string(), R_OK) == -1) {
2225 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002226 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002227 }
2228
Kenny Root655b9582013-04-04 08:37:42 -07002229 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002230 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002231 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002232 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002233 }
2234
2235 struct stat s;
2236 int ret = fstat(fd, &s);
2237 close(fd);
2238 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002239 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002240 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002241 }
2242
Kenny Root36a9e232013-02-04 14:24:15 -08002243 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002244 }
2245
Kenny Rootd53bc922013-03-21 14:10:15 -07002246 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2247 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002248 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002249 pid_t spid = IPCThreadState::self()->getCallingPid();
2250 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002251 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002252 return -1L;
2253 }
2254
Chad Brubaker72593ee2015-05-12 10:42:00 -07002255 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002256 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002257 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002258 return state;
2259 }
2260
Kenny Rootd53bc922013-03-21 14:10:15 -07002261 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2262 srcUid = callingUid;
2263 } else if (!is_granted_to(callingUid, srcUid)) {
2264 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002265 return ::PERMISSION_DENIED;
2266 }
2267
Kenny Rootd53bc922013-03-21 14:10:15 -07002268 if (destUid == -1) {
2269 destUid = callingUid;
2270 }
2271
2272 if (srcUid != destUid) {
2273 if (static_cast<uid_t>(srcUid) != callingUid) {
2274 ALOGD("can only duplicate from caller to other or to same uid: "
2275 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2276 return ::PERMISSION_DENIED;
2277 }
2278
2279 if (!is_granted_to(callingUid, destUid)) {
2280 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2281 return ::PERMISSION_DENIED;
2282 }
2283 }
2284
2285 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002286 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002287
Kenny Rootd53bc922013-03-21 14:10:15 -07002288 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002289 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002290
Kenny Root655b9582013-04-04 08:37:42 -07002291 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2292 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002293 return ::SYSTEM_ERROR;
2294 }
2295
Kenny Rootd53bc922013-03-21 14:10:15 -07002296 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002297 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002298 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002299 if (responseCode != ::NO_ERROR) {
2300 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002301 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002302
Chad Brubaker72593ee2015-05-12 10:42:00 -07002303 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002304 }
2305
Kenny Root1b0e3932013-09-05 13:06:32 -07002306 int32_t is_hardware_backed(const String16& keyType) {
2307 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002308 }
2309
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002310 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002311 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002312 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002313 return ::PERMISSION_DENIED;
2314 }
2315
Robin Lee4b84fdc2014-09-24 11:56:57 +01002316 String8 prefix = String8::format("%u_", targetUid);
2317 Vector<String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07002318 if (mKeyStore->saw(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002319 return ::SYSTEM_ERROR;
2320 }
2321
Robin Lee4b84fdc2014-09-24 11:56:57 +01002322 for (uint32_t i = 0; i < aliases.size(); i++) {
2323 String8 name8(aliases[i]);
2324 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002325 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002326 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002327 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002328 }
2329
Robin Lee4b84fdc2014-09-24 11:56:57 +01002330 int32_t reset_uid(int32_t targetUid) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07002331 // TODO: Remove this method from the binder interface
Chad Brubaker9489b792015-04-14 11:01:45 -07002332 targetUid = getEffectiveUid(targetUid);
Chad Brubaker96d6d782015-05-07 10:19:40 -07002333 return onUserPasswordChanged(get_user_id(targetUid), String16(""));
Robin Lee4e865752014-08-19 17:37:55 +01002334 }
2335
2336 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002337 if (!checkBinderPermission(P_SYNC_UID, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002338 return ::PERMISSION_DENIED;
2339 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002340 uid_t sourceUser = get_user_id(sourceUid);
2341 uid_t targetUser = get_user_id(targetUid);
Chad Brubaker9489b792015-04-14 11:01:45 -07002342
Chad Brubaker72593ee2015-05-12 10:42:00 -07002343 if (sourceUser == targetUser) {
Robin Lee4e865752014-08-19 17:37:55 +01002344 return ::SYSTEM_ERROR;
2345 }
2346
2347 // Initialise user keystore with existing master key held in-memory
Chad Brubaker72593ee2015-05-12 10:42:00 -07002348 return mKeyStore->copyMasterKey(sourceUser, targetUser);
Robin Lee4e865752014-08-19 17:37:55 +01002349 }
2350
2351 int32_t password_uid(const String16& pw, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002352 targetUid = getEffectiveUid(targetUid);
2353 if (!checkBinderPermission(P_PASSWORD, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002354 return ::PERMISSION_DENIED;
2355 }
Robin Lee4e865752014-08-19 17:37:55 +01002356 const String8 password8(pw);
Chad Brubaker72593ee2015-05-12 10:42:00 -07002357 uid_t userId = get_user_id(targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002358
Chad Brubaker72593ee2015-05-12 10:42:00 -07002359 switch (mKeyStore->getState(userId)) {
Robin Lee4e865752014-08-19 17:37:55 +01002360 case ::STATE_UNINITIALIZED: {
2361 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002362 return mKeyStore->initializeUser(password8, userId);
Robin Lee4e865752014-08-19 17:37:55 +01002363 }
2364 case ::STATE_NO_ERROR: {
2365 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002366 return mKeyStore->writeMasterKey(password8, userId);
Robin Lee4e865752014-08-19 17:37:55 +01002367 }
2368 case ::STATE_LOCKED: {
2369 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07002370 return mKeyStore->readMasterKey(password8, userId);
Robin Lee4e865752014-08-19 17:37:55 +01002371 }
2372 }
2373 return ::SYSTEM_ERROR;
2374 }
2375
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002376 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2377 const keymaster1_device_t* device = mKeyStore->getDevice();
2378 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2379 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2380 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2381 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2382 device->add_rng_entropy != NULL) {
2383 devResult = device->add_rng_entropy(device, data, dataLength);
2384 }
2385 if (fallback->add_rng_entropy) {
2386 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2387 }
2388 if (devResult) {
2389 return devResult;
2390 }
2391 if (fallbackResult) {
2392 return fallbackResult;
2393 }
2394 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002395 }
2396
Chad Brubaker17d68b92015-02-05 22:04:16 -08002397 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002398 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2399 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002400 uid = getEffectiveUid(uid);
2401 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2402 flags & KEYSTORE_FLAG_ENCRYPTED);
2403 if (rc != ::NO_ERROR) {
2404 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002405 }
2406
Chad Brubaker9489b792015-04-14 11:01:45 -07002407 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002408 bool isFallback = false;
2409 keymaster_key_blob_t blob;
2410 keymaster_key_characteristics_t *out = NULL;
2411
2412 const keymaster1_device_t* device = mKeyStore->getDevice();
2413 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2414 if (device == NULL) {
2415 return ::SYSTEM_ERROR;
2416 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002417 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002418 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2419 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002420 if (!entropy) {
2421 rc = KM_ERROR_OK;
2422 } else if (device->add_rng_entropy) {
2423 rc = device->add_rng_entropy(device, entropy, entropyLength);
2424 } else {
2425 rc = KM_ERROR_UNIMPLEMENTED;
2426 }
2427 if (rc == KM_ERROR_OK) {
2428 rc = device->generate_key(device, params.params.data(), params.params.size(),
2429 &blob, &out);
2430 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002431 }
2432 // If the HW device didn't support generate_key or generate_key failed
2433 // fall back to the software implementation.
2434 if (rc && fallback->generate_key != NULL) {
2435 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002436 if (!entropy) {
2437 rc = KM_ERROR_OK;
2438 } else if (fallback->add_rng_entropy) {
2439 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2440 } else {
2441 rc = KM_ERROR_UNIMPLEMENTED;
2442 }
2443 if (rc == KM_ERROR_OK) {
2444 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2445 &blob,
2446 &out);
2447 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002448 }
2449
2450 if (out) {
2451 if (outCharacteristics) {
2452 outCharacteristics->characteristics = *out;
2453 } else {
2454 keymaster_free_characteristics(out);
2455 }
2456 free(out);
2457 }
2458
2459 if (rc) {
2460 return rc;
2461 }
2462
2463 String8 name8(name);
2464 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2465
2466 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2467 keyBlob.setFallback(isFallback);
2468 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2469
2470 free(const_cast<uint8_t*>(blob.key_material));
2471
Chad Brubaker72593ee2015-05-12 10:42:00 -07002472 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002473 }
2474
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002475 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002476 const keymaster_blob_t* clientId,
2477 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002478 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002479 if (!outCharacteristics) {
2480 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2481 }
2482
2483 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2484
2485 Blob keyBlob;
2486 String8 name8(name);
2487 int rc;
2488
2489 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2490 TYPE_KEYMASTER_10);
2491 if (responseCode != ::NO_ERROR) {
2492 return responseCode;
2493 }
2494 keymaster_key_blob_t key;
2495 key.key_material_size = keyBlob.getLength();
2496 key.key_material = keyBlob.getValue();
2497 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2498 keymaster_key_characteristics_t *out = NULL;
2499 if (!dev->get_key_characteristics) {
2500 ALOGW("device does not implement get_key_characteristics");
2501 return KM_ERROR_UNIMPLEMENTED;
2502 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002503 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002504 if (out) {
2505 outCharacteristics->characteristics = *out;
2506 free(out);
2507 }
2508 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002509 }
2510
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002511 int32_t importKey(const String16& name, const KeymasterArguments& params,
2512 keymaster_key_format_t format, const uint8_t *keyData,
2513 size_t keyLength, int uid, int flags,
2514 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002515 uid = getEffectiveUid(uid);
2516 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2517 flags & KEYSTORE_FLAG_ENCRYPTED);
2518 if (rc != ::NO_ERROR) {
2519 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002520 }
2521
Chad Brubaker9489b792015-04-14 11:01:45 -07002522 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002523 bool isFallback = false;
2524 keymaster_key_blob_t blob;
2525 keymaster_key_characteristics_t *out = NULL;
2526
2527 const keymaster1_device_t* device = mKeyStore->getDevice();
2528 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2529 if (device == NULL) {
2530 return ::SYSTEM_ERROR;
2531 }
2532 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2533 device->import_key != NULL) {
2534 rc = device->import_key(device, params.params.data(), params.params.size(),
2535 format, keyData, keyLength, &blob, &out);
2536 }
2537 if (rc && fallback->import_key != NULL) {
2538 isFallback = true;
2539 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2540 format, keyData, keyLength, &blob, &out);
2541 }
2542 if (out) {
2543 if (outCharacteristics) {
2544 outCharacteristics->characteristics = *out;
2545 } else {
2546 keymaster_free_characteristics(out);
2547 }
2548 free(out);
2549 }
2550 if (rc) {
2551 return rc;
2552 }
2553
2554 String8 name8(name);
2555 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2556
2557 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2558 keyBlob.setFallback(isFallback);
2559 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2560
2561 free((void*) blob.key_material);
2562
Chad Brubaker72593ee2015-05-12 10:42:00 -07002563 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002564 }
2565
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002566 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002567 const keymaster_blob_t* clientId,
2568 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002569
2570 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2571
2572 Blob keyBlob;
2573 String8 name8(name);
2574 int rc;
2575
2576 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2577 TYPE_KEYMASTER_10);
2578 if (responseCode != ::NO_ERROR) {
2579 result->resultCode = responseCode;
2580 return;
2581 }
2582 keymaster_key_blob_t key;
2583 key.key_material_size = keyBlob.getLength();
2584 key.key_material = keyBlob.getValue();
2585 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2586 if (!dev->export_key) {
2587 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2588 return;
2589 }
2590 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002591 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002592 &ptr, &result->dataLength);
2593 result->exportData.reset(ptr);
2594 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002595 }
2596
Chad Brubakerad6514a2015-04-09 14:00:26 -07002597
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002598 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002599 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2600 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002601 if (!result || !outParams) {
2602 ALOGE("Unexpected null arguments to begin()");
2603 return;
2604 }
2605 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2606 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2607 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2608 result->resultCode = ::PERMISSION_DENIED;
2609 return;
2610 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002611 if (!checkAllowedOperationParams(params.params)) {
2612 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2613 return;
2614 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002615 Blob keyBlob;
2616 String8 name8(name);
2617 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2618 TYPE_KEYMASTER_10);
2619 if (responseCode != ::NO_ERROR) {
2620 result->resultCode = responseCode;
2621 return;
2622 }
2623 keymaster_key_blob_t key;
2624 key.key_material_size = keyBlob.getLength();
2625 key.key_material = keyBlob.getValue();
2626 keymaster_key_param_t* out;
2627 size_t outSize;
2628 keymaster_operation_handle_t handle;
2629 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002630 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002631 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002632 Unique_keymaster_key_characteristics characteristics;
2633 characteristics.reset(new keymaster_key_characteristics_t);
2634 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2635 if (err) {
2636 result->resultCode = err;
2637 return;
2638 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002639 const hw_auth_token_t* authToken = NULL;
2640 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002641 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002642 // If per-operation auth is needed we need to begin the operation and
2643 // the client will need to authorize that operation before calling
2644 // update. Any other auth issues stop here.
2645 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2646 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002647 return;
2648 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002649 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002650 // Add entropy to the device first.
2651 if (entropy) {
2652 if (dev->add_rng_entropy) {
2653 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2654 } else {
2655 err = KM_ERROR_UNIMPLEMENTED;
2656 }
2657 if (err) {
2658 result->resultCode = err;
2659 return;
2660 }
2661 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002662 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
2663 &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002664
2665 // If there are too many operations abort the oldest operation that was
2666 // started as pruneable and try again.
2667 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2668 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2669 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2670 if (abort(oldest) != ::NO_ERROR) {
2671 break;
2672 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002673 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002674 &handle);
2675 }
2676 if (err) {
2677 result->resultCode = err;
2678 return;
2679 }
2680 if (out) {
2681 outParams->params.assign(out, out + outSize);
2682 free(out);
2683 }
2684
Chad Brubakerad6514a2015-04-09 14:00:26 -07002685 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2686 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002687 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002688 if (authToken) {
2689 mOperationMap.setOperationAuthToken(operationToken, authToken);
2690 }
2691 // Return the authentication lookup result. If this is a per operation
2692 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2693 // application should get an auth token using the handle before the
2694 // first call to update, which will fail if keystore hasn't received the
2695 // auth token.
2696 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002697 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002698 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002699 }
2700
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002701 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2702 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002703 if (!checkAllowedOperationParams(params.params)) {
2704 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2705 return;
2706 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002707 const keymaster1_device_t* dev;
2708 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002709 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002710 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2711 return;
2712 }
2713 uint8_t* output_buf = NULL;
2714 size_t output_length = 0;
2715 size_t consumed = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002716 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002717 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2718 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002719 result->resultCode = authResult;
2720 return;
2721 }
2722 keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
2723 dataLength, &consumed, &output_buf, &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002724 result->data.reset(output_buf);
2725 result->dataLength = output_length;
2726 result->inputConsumed = consumed;
2727 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002728 }
2729
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002730 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2731 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002732 if (!checkAllowedOperationParams(params.params)) {
2733 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2734 return;
2735 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002736 const keymaster1_device_t* dev;
2737 keymaster_operation_handle_t handle;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002738 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002739 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2740 return;
2741 }
2742 uint8_t* output_buf = NULL;
2743 size_t output_length = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002744 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002745 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2746 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002747 result->resultCode = authResult;
2748 return;
2749 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002750
Chad Brubaker06801e02015-03-31 15:13:13 -07002751 keymaster_error_t err = dev->finish(dev, handle, opParams.data(), opParams.size(),
2752 signature, signatureLength, &output_buf,
2753 &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002754 // Remove the operation regardless of the result
2755 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002756 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002757 result->data.reset(output_buf);
2758 result->dataLength = output_length;
2759 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002760 }
2761
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002762 int32_t abort(const sp<IBinder>& token) {
2763 const keymaster1_device_t* dev;
2764 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002765 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002766 return KM_ERROR_INVALID_OPERATION_HANDLE;
2767 }
2768 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002769 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002770 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002771 rc = KM_ERROR_UNIMPLEMENTED;
2772 } else {
2773 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002774 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002775 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002776 if (rc) {
2777 return rc;
2778 }
2779 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002780 }
2781
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002782 bool isOperationAuthorized(const sp<IBinder>& token) {
2783 const keymaster1_device_t* dev;
2784 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002785 const keymaster_key_characteristics_t* characteristics;
2786 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002787 return false;
2788 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002789 const hw_auth_token_t* authToken = NULL;
2790 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002791 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002792 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2793 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002794 }
2795
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002796 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002797 if (!checkBinderPermission(P_ADD_AUTH)) {
2798 ALOGW("addAuthToken: permission denied for %d",
2799 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002800 return ::PERMISSION_DENIED;
2801 }
2802 if (length != sizeof(hw_auth_token_t)) {
2803 return KM_ERROR_INVALID_ARGUMENT;
2804 }
2805 hw_auth_token_t* authToken = new hw_auth_token_t;
2806 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2807 // The table takes ownership of authToken.
2808 mAuthTokenTable.AddAuthenticationToken(authToken);
2809 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002810 }
2811
Kenny Root07438c82012-11-02 15:41:02 -07002812private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002813 static const int32_t UID_SELF = -1;
2814
2815 /**
2816 * Get the effective target uid for a binder operation that takes an
2817 * optional uid as the target.
2818 */
2819 inline uid_t getEffectiveUid(int32_t targetUid) {
2820 if (targetUid == UID_SELF) {
2821 return IPCThreadState::self()->getCallingUid();
2822 }
2823 return static_cast<uid_t>(targetUid);
2824 }
2825
2826 /**
2827 * Check if the caller of the current binder method has the required
2828 * permission and if acting on other uids the grants to do so.
2829 */
2830 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2831 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2832 pid_t spid = IPCThreadState::self()->getCallingPid();
2833 if (!has_permission(callingUid, permission, spid)) {
2834 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2835 return false;
2836 }
2837 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2838 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2839 return false;
2840 }
2841 return true;
2842 }
2843
2844 /**
2845 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002846 * permission and the target uid is the caller or the caller is system.
2847 */
2848 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2849 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2850 pid_t spid = IPCThreadState::self()->getCallingPid();
2851 if (!has_permission(callingUid, permission, spid)) {
2852 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2853 return false;
2854 }
2855 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2856 }
2857
2858 /**
2859 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002860 * permission or the target of the operation is the caller's uid. This is
2861 * for operation where the permission is only for cross-uid activity and all
2862 * uids are allowed to act on their own (ie: clearing all entries for a
2863 * given uid).
2864 */
2865 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2866 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2867 if (getEffectiveUid(targetUid) == callingUid) {
2868 return true;
2869 } else {
2870 return checkBinderPermission(permission, targetUid);
2871 }
2872 }
2873
2874 /**
2875 * Helper method to check that the caller has the required permission as
2876 * well as the keystore is in the unlocked state if checkUnlocked is true.
2877 *
2878 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2879 * otherwise the state of keystore when not unlocked and checkUnlocked is
2880 * true.
2881 */
2882 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2883 bool checkUnlocked = true) {
2884 if (!checkBinderPermission(permission, targetUid)) {
2885 return ::PERMISSION_DENIED;
2886 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002887 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002888 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2889 return state;
2890 }
2891
2892 return ::NO_ERROR;
2893
2894 }
2895
Kenny Root9d45d1c2013-02-14 10:32:30 -08002896 inline bool isKeystoreUnlocked(State state) {
2897 switch (state) {
2898 case ::STATE_NO_ERROR:
2899 return true;
2900 case ::STATE_UNINITIALIZED:
2901 case ::STATE_LOCKED:
2902 return false;
2903 }
2904 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002905 }
2906
Chad Brubaker67d2a502015-03-11 17:21:18 +00002907 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002908 const int32_t device_api = device->common.module->module_api_version;
2909 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2910 switch (keyType) {
2911 case TYPE_RSA:
2912 case TYPE_DSA:
2913 case TYPE_EC:
2914 return true;
2915 default:
2916 return false;
2917 }
2918 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2919 switch (keyType) {
2920 case TYPE_RSA:
2921 return true;
2922 case TYPE_DSA:
2923 return device->flags & KEYMASTER_SUPPORTS_DSA;
2924 case TYPE_EC:
2925 return device->flags & KEYMASTER_SUPPORTS_EC;
2926 default:
2927 return false;
2928 }
2929 } else {
2930 return keyType == TYPE_RSA;
2931 }
2932 }
2933
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002934 /**
2935 * Check that all keymaster_key_param_t's provided by the application are
2936 * allowed. Any parameter that keystore adds itself should be disallowed here.
2937 */
2938 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2939 for (auto param: params) {
2940 switch (param.tag) {
2941 case KM_TAG_AUTH_TOKEN:
2942 return false;
2943 default:
2944 break;
2945 }
2946 }
2947 return true;
2948 }
2949
2950 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2951 const keymaster1_device_t* dev,
2952 const std::vector<keymaster_key_param_t>& params,
2953 keymaster_key_characteristics_t* out) {
2954 UniquePtr<keymaster_blob_t> appId;
2955 UniquePtr<keymaster_blob_t> appData;
2956 for (auto param : params) {
2957 if (param.tag == KM_TAG_APPLICATION_ID) {
2958 appId.reset(new keymaster_blob_t);
2959 appId->data = param.blob.data;
2960 appId->data_length = param.blob.data_length;
2961 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2962 appData.reset(new keymaster_blob_t);
2963 appData->data = param.blob.data;
2964 appData->data_length = param.blob.data_length;
2965 }
2966 }
2967 keymaster_key_characteristics_t* result = NULL;
2968 if (!dev->get_key_characteristics) {
2969 return KM_ERROR_UNIMPLEMENTED;
2970 }
2971 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2972 appData.get(), &result);
2973 if (result) {
2974 *out = *result;
2975 free(result);
2976 }
2977 return error;
2978 }
2979
2980 /**
2981 * Get the auth token for this operation from the auth token table.
2982 *
2983 * Returns ::NO_ERROR if the auth token was set or none was required.
2984 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2985 * authorization token exists for that operation and
2986 * failOnTokenMissing is false.
2987 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2988 * token for the operation
2989 */
2990 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2991 keymaster_operation_handle_t handle,
2992 const hw_auth_token_t** authToken,
2993 bool failOnTokenMissing = true) {
2994
2995 std::vector<keymaster_key_param_t> allCharacteristics;
2996 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2997 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2998 }
2999 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
3000 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
3001 }
3002 keymaster::AuthTokenTable::Error err =
3003 mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
3004 allCharacteristics.size(), handle, authToken);
3005 switch (err) {
3006 case keymaster::AuthTokenTable::OK:
3007 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
3008 return ::NO_ERROR;
3009 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
3010 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
3011 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
3012 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
3013 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
3014 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
3015 (int32_t) ::OP_AUTH_NEEDED;
3016 default:
3017 ALOGE("Unexpected FindAuthorization return value %d", err);
3018 return KM_ERROR_INVALID_ARGUMENT;
3019 }
3020 }
3021
3022 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
3023 const hw_auth_token_t* token) {
3024 if (token) {
3025 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
3026 reinterpret_cast<const uint8_t*>(token),
3027 sizeof(hw_auth_token_t)));
3028 }
3029 }
3030
3031 /**
3032 * Add the auth token for the operation to the param list if the operation
3033 * requires authorization. Uses the cached result in the OperationMap if available
3034 * otherwise gets the token from the AuthTokenTable and caches the result.
3035 *
3036 * Returns ::NO_ERROR if the auth token was added or not needed.
3037 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
3038 * authenticated.
3039 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
3040 * operation token.
3041 */
3042 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3043 std::vector<keymaster_key_param_t>* params) {
3044 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07003045 mOperationMap.getOperationAuthToken(token, &authToken);
3046 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07003047 const keymaster1_device_t* dev;
3048 keymaster_operation_handle_t handle;
3049 const keymaster_key_characteristics_t* characteristics = NULL;
3050 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
3051 return KM_ERROR_INVALID_OPERATION_HANDLE;
3052 }
3053 int32_t result = getAuthToken(characteristics, handle, &authToken);
3054 if (result != ::NO_ERROR) {
3055 return result;
3056 }
3057 if (authToken) {
3058 mOperationMap.setOperationAuthToken(token, authToken);
3059 }
3060 }
3061 addAuthToParams(params, authToken);
3062 return ::NO_ERROR;
3063 }
3064
Kenny Root07438c82012-11-02 15:41:02 -07003065 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003066 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003067 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07003068};
3069
3070}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003071
3072int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003073 if (argc < 2) {
3074 ALOGE("A directory must be specified!");
3075 return 1;
3076 }
3077 if (chdir(argv[1]) == -1) {
3078 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3079 return 1;
3080 }
3081
3082 Entropy entropy;
3083 if (!entropy.open()) {
3084 return 1;
3085 }
Kenny Root70e3a862012-02-15 17:20:23 -08003086
Shawn Willden80843db2015-02-24 09:31:25 -07003087 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003088 if (keymaster_device_initialize(&dev)) {
3089 ALOGE("keystore keymaster could not be initialized; exiting");
3090 return 1;
3091 }
3092
Chad Brubaker67d2a502015-03-11 17:21:18 +00003093 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003094 if (fallback_keymaster_device_initialize(&fallback)) {
3095 ALOGE("software keymaster could not be initialized; exiting");
3096 return 1;
3097 }
3098
Riley Spahneaabae92014-06-30 12:39:52 -07003099 ks_is_selinux_enabled = is_selinux_enabled();
3100 if (ks_is_selinux_enabled) {
3101 union selinux_callback cb;
3102 cb.func_log = selinux_log_callback;
3103 selinux_set_callback(SELINUX_CB_LOG, cb);
3104 if (getcon(&tctx) != 0) {
3105 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3106 return -1;
3107 }
3108 } else {
3109 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3110 }
3111
Chad Brubaker67d2a502015-03-11 17:21:18 +00003112 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003113 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003114 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3115 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3116 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3117 if (ret != android::OK) {
3118 ALOGE("Couldn't register binder service!");
3119 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003120 }
Kenny Root07438c82012-11-02 15:41:02 -07003121
3122 /*
3123 * We're the only thread in existence, so we're just going to process
3124 * Binder transaction as a single-threaded program.
3125 */
3126 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003127
3128 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003129 return 1;
3130}