blob: e3c30b53aa3bba48bdd309734e523e5e7de93d9a [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willdena5bbf2f2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Chad Brubaker919cb2a2015-02-05 21:58:25 -080046#include <keymaster/soft_keymaster_device.h>
Shawn Willden9e5016a2015-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 Willdena5bbf2f2015-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 Willdena5bbf2f2015-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 Willden9e5016a2015-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 Brubaker919cb2a2015-02-05 21:58:25 -0800137static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
138 keymaster::SoftKeymasterDevice* softkeymaster =
139 new keymaster::SoftKeymasterDevice();
Shawn Willdenef572b62015-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 Willdena5bbf2f2015-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 Brubakerfd777e72015-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 Brubakerfd777e72015-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) {
Kenny Roota91203b2012-02-15 15:00:46 -0800505 mBlob.length = valueLength;
506 memcpy(mBlob.value, value, valueLength);
507
508 mBlob.info = infoLength;
509 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700510
Kenny Root07438c82012-11-02 15:41:02 -0700511 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700512 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700513
Kenny Rootee8068b2013-10-07 09:49:15 -0700514 if (type == TYPE_MASTER_KEY) {
515 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
516 } else {
517 mBlob.flags = KEYSTORE_FLAG_NONE;
518 }
Kenny Roota91203b2012-02-15 15:00:46 -0800519 }
520
521 Blob(blob b) {
522 mBlob = b;
523 }
524
525 Blob() {}
526
Kenny Root51878182012-03-13 12:53:19 -0700527 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800528 return mBlob.value;
529 }
530
Kenny Root51878182012-03-13 12:53:19 -0700531 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800532 return mBlob.length;
533 }
534
Kenny Root51878182012-03-13 12:53:19 -0700535 const uint8_t* getInfo() const {
536 return mBlob.value + mBlob.length;
537 }
538
539 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800540 return mBlob.info;
541 }
542
Kenny Root822c3a92012-03-23 16:34:39 -0700543 uint8_t getVersion() const {
544 return mBlob.version;
545 }
546
Kenny Rootf9119d62013-04-03 09:22:15 -0700547 bool isEncrypted() const {
548 if (mBlob.version < 2) {
549 return true;
550 }
551
552 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
553 }
554
555 void setEncrypted(bool encrypted) {
556 if (encrypted) {
557 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
558 } else {
559 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
560 }
561 }
562
Kenny Root17208e02013-09-04 13:56:03 -0700563 bool isFallback() const {
564 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
565 }
566
567 void setFallback(bool fallback) {
568 if (fallback) {
569 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
570 } else {
571 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
572 }
573 }
574
Kenny Root822c3a92012-03-23 16:34:39 -0700575 void setVersion(uint8_t version) {
576 mBlob.version = version;
577 }
578
579 BlobType getType() const {
580 return BlobType(mBlob.type);
581 }
582
583 void setType(BlobType type) {
584 mBlob.type = uint8_t(type);
585 }
586
Kenny Rootf9119d62013-04-03 09:22:15 -0700587 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
588 ALOGV("writing blob %s", filename);
589 if (isEncrypted()) {
590 if (state != STATE_NO_ERROR) {
591 ALOGD("couldn't insert encrypted blob while not unlocked");
592 return LOCKED;
593 }
594
595 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
596 ALOGW("Could not read random data for: %s", filename);
597 return SYSTEM_ERROR;
598 }
Kenny Roota91203b2012-02-15 15:00:46 -0800599 }
600
601 // data includes the value and the value's length
602 size_t dataLength = mBlob.length + sizeof(mBlob.length);
603 // pad data to the AES_BLOCK_SIZE
604 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
605 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
606 // encrypted data includes the digest value
607 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
608 // move info after space for padding
609 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
610 // zero padding area
611 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
612
613 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800614
Kenny Rootf9119d62013-04-03 09:22:15 -0700615 if (isEncrypted()) {
616 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800617
Kenny Rootf9119d62013-04-03 09:22:15 -0700618 uint8_t vector[AES_BLOCK_SIZE];
619 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
620 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
621 aes_key, vector, AES_ENCRYPT);
622 }
623
Kenny Roota91203b2012-02-15 15:00:46 -0800624 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
625 size_t fileLength = encryptedLength + headerLength + mBlob.info;
626
627 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800628 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
629 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
630 if (out < 0) {
631 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800632 return SYSTEM_ERROR;
633 }
634 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
635 if (close(out) != 0) {
636 return SYSTEM_ERROR;
637 }
638 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800639 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800640 unlink(tmpFileName);
641 return SYSTEM_ERROR;
642 }
Kenny Root150ca932012-11-14 14:29:02 -0800643 if (rename(tmpFileName, filename) == -1) {
644 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
645 return SYSTEM_ERROR;
646 }
647 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800648 }
649
Kenny Rootf9119d62013-04-03 09:22:15 -0700650 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
651 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800652 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
653 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800654 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
655 }
656 // fileLength may be less than sizeof(mBlob) since the in
657 // memory version has extra padding to tolerate rounding up to
658 // the AES_BLOCK_SIZE
659 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
660 if (close(in) != 0) {
661 return SYSTEM_ERROR;
662 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700663
664 if (isEncrypted() && (state != STATE_NO_ERROR)) {
665 return LOCKED;
666 }
667
Kenny Roota91203b2012-02-15 15:00:46 -0800668 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
669 if (fileLength < headerLength) {
670 return VALUE_CORRUPTED;
671 }
672
673 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700674 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800675 return VALUE_CORRUPTED;
676 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700677
678 ssize_t digestedLength;
679 if (isEncrypted()) {
680 if (encryptedLength % AES_BLOCK_SIZE != 0) {
681 return VALUE_CORRUPTED;
682 }
683
684 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
685 mBlob.vector, AES_DECRYPT);
686 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
687 uint8_t computedDigest[MD5_DIGEST_LENGTH];
688 MD5(mBlob.digested, digestedLength, computedDigest);
689 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
690 return VALUE_CORRUPTED;
691 }
692 } else {
693 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800694 }
695
696 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
697 mBlob.length = ntohl(mBlob.length);
698 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
699 return VALUE_CORRUPTED;
700 }
701 if (mBlob.info != 0) {
702 // move info from after padding to after data
703 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
704 }
Kenny Root07438c82012-11-02 15:41:02 -0700705 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800706 }
707
708private:
709 struct blob mBlob;
710};
711
Kenny Root655b9582013-04-04 08:37:42 -0700712class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800713public:
Kenny Root655b9582013-04-04 08:37:42 -0700714 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
715 asprintf(&mUserDir, "user_%u", mUserId);
716 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
717 }
718
719 ~UserState() {
720 free(mUserDir);
721 free(mMasterKeyFile);
722 }
723
724 bool initialize() {
725 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
726 ALOGE("Could not create directory '%s'", mUserDir);
727 return false;
728 }
729
730 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800731 setState(STATE_LOCKED);
732 } else {
733 setState(STATE_UNINITIALIZED);
734 }
Kenny Root70e3a862012-02-15 17:20:23 -0800735
Kenny Root655b9582013-04-04 08:37:42 -0700736 return true;
737 }
738
739 uid_t getUserId() const {
740 return mUserId;
741 }
742
743 const char* getUserDirName() const {
744 return mUserDir;
745 }
746
747 const char* getMasterKeyFileName() const {
748 return mMasterKeyFile;
749 }
750
751 void setState(State state) {
752 mState = state;
753 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
754 mRetry = MAX_RETRY;
755 }
Kenny Roota91203b2012-02-15 15:00:46 -0800756 }
757
Kenny Root51878182012-03-13 12:53:19 -0700758 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800759 return mState;
760 }
761
Kenny Root51878182012-03-13 12:53:19 -0700762 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800763 return mRetry;
764 }
765
Kenny Root655b9582013-04-04 08:37:42 -0700766 void zeroizeMasterKeysInMemory() {
767 memset(mMasterKey, 0, sizeof(mMasterKey));
768 memset(mSalt, 0, sizeof(mSalt));
769 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
770 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800771 }
772
Chad Brubakereecdd122015-05-07 10:19:40 -0700773 bool deleteMasterKey() {
774 setState(STATE_UNINITIALIZED);
775 zeroizeMasterKeysInMemory();
776 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
777 }
778
Kenny Root655b9582013-04-04 08:37:42 -0700779 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
780 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800781 return SYSTEM_ERROR;
782 }
Kenny Root655b9582013-04-04 08:37:42 -0700783 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800784 if (response != NO_ERROR) {
785 return response;
786 }
787 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700788 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800789 }
790
Robin Lee4e865752014-08-19 17:37:55 +0100791 ResponseCode copyMasterKey(UserState* src) {
792 if (mState != STATE_UNINITIALIZED) {
793 return ::SYSTEM_ERROR;
794 }
795 if (src->getState() != STATE_NO_ERROR) {
796 return ::SYSTEM_ERROR;
797 }
798 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
799 setupMasterKeys();
800 return ::NO_ERROR;
801 }
802
Kenny Root655b9582013-04-04 08:37:42 -0700803 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800804 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
805 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
806 AES_KEY passwordAesKey;
807 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700808 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700809 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800810 }
811
Kenny Root655b9582013-04-04 08:37:42 -0700812 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
813 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800814 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800815 return SYSTEM_ERROR;
816 }
817
818 // we read the raw blob to just to get the salt to generate
819 // the AES key, then we create the Blob to use with decryptBlob
820 blob rawBlob;
821 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
822 if (close(in) != 0) {
823 return SYSTEM_ERROR;
824 }
825 // find salt at EOF if present, otherwise we have an old file
826 uint8_t* salt;
827 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
828 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
829 } else {
830 salt = NULL;
831 }
832 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
833 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
834 AES_KEY passwordAesKey;
835 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
836 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700837 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
838 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800839 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700840 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800841 }
842 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
843 // if salt was missing, generate one and write a new master key file with the salt.
844 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700845 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800846 return SYSTEM_ERROR;
847 }
Kenny Root655b9582013-04-04 08:37:42 -0700848 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800849 }
850 if (response == NO_ERROR) {
851 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
852 setupMasterKeys();
853 }
854 return response;
855 }
856 if (mRetry <= 0) {
857 reset();
858 return UNINITIALIZED;
859 }
860 --mRetry;
861 switch (mRetry) {
862 case 0: return WRONG_PASSWORD_0;
863 case 1: return WRONG_PASSWORD_1;
864 case 2: return WRONG_PASSWORD_2;
865 case 3: return WRONG_PASSWORD_3;
866 default: return WRONG_PASSWORD_3;
867 }
868 }
869
Kenny Root655b9582013-04-04 08:37:42 -0700870 AES_KEY* getEncryptionKey() {
871 return &mMasterKeyEncryption;
872 }
873
874 AES_KEY* getDecryptionKey() {
875 return &mMasterKeyDecryption;
876 }
877
Kenny Roota91203b2012-02-15 15:00:46 -0800878 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700879 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800880 if (!dir) {
Chad Brubakereecdd122015-05-07 10:19:40 -0700881 // If the directory doesn't exist then nothing to do.
882 if (errno == ENOENT) {
883 return true;
884 }
Kenny Root655b9582013-04-04 08:37:42 -0700885 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800886 return false;
887 }
Kenny Root655b9582013-04-04 08:37:42 -0700888
889 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800890 while ((file = readdir(dir)) != NULL) {
Chad Brubakereecdd122015-05-07 10:19:40 -0700891 // skip . and ..
892 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700893 continue;
894 }
895
896 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800897 }
898 closedir(dir);
899 return true;
900 }
901
Kenny Root655b9582013-04-04 08:37:42 -0700902private:
903 static const int MASTER_KEY_SIZE_BYTES = 16;
904 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
905
906 static const int MAX_RETRY = 4;
907 static const size_t SALT_SIZE = 16;
908
909 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
910 uint8_t* salt) {
911 size_t saltSize;
912 if (salt != NULL) {
913 saltSize = SALT_SIZE;
914 } else {
915 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
916 salt = (uint8_t*) "keystore";
917 // sizeof = 9, not strlen = 8
918 saltSize = sizeof("keystore");
919 }
920
921 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
922 saltSize, 8192, keySize, key);
923 }
924
925 bool generateSalt(Entropy* entropy) {
926 return entropy->generate_random_data(mSalt, sizeof(mSalt));
927 }
928
929 bool generateMasterKey(Entropy* entropy) {
930 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
931 return false;
932 }
933 if (!generateSalt(entropy)) {
934 return false;
935 }
936 return true;
937 }
938
939 void setupMasterKeys() {
940 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
941 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
942 setState(STATE_NO_ERROR);
943 }
944
945 uid_t mUserId;
946
947 char* mUserDir;
948 char* mMasterKeyFile;
949
950 State mState;
951 int8_t mRetry;
952
953 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
954 uint8_t mSalt[SALT_SIZE];
955
956 AES_KEY mMasterKeyEncryption;
957 AES_KEY mMasterKeyDecryption;
958};
959
960typedef struct {
961 uint32_t uid;
962 const uint8_t* filename;
963} grant_t;
964
965class KeyStore {
966public:
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800967 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700968 : mEntropy(entropy)
969 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800970 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700971 {
972 memset(&mMetaData, '\0', sizeof(mMetaData));
973 }
974
975 ~KeyStore() {
976 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
977 it != mGrants.end(); it++) {
978 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700979 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800980 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700981
982 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
983 it != mMasterKeys.end(); it++) {
984 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700985 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800986 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700987 }
988
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800989 /**
990 * Depending on the hardware keymaster version is this may return a
991 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
992 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
993 * be guarded by a check on the device's version.
994 */
995 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -0700996 return mDevice;
997 }
998
Chad Brubaker919cb2a2015-02-05 21:58:25 -0800999 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001000 return mFallbackDevice;
1001 }
1002
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001003 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001004 return blob.isFallback() ? mFallbackDevice: mDevice;
1005 }
1006
Kenny Root655b9582013-04-04 08:37:42 -07001007 ResponseCode initialize() {
1008 readMetaData();
1009 if (upgradeKeystore()) {
1010 writeMetaData();
1011 }
1012
1013 return ::NO_ERROR;
1014 }
1015
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001016 State getState(uid_t userId) {
1017 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001018 }
1019
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001020 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1021 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001022 return userState->initialize(pw, mEntropy);
1023 }
1024
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001025 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1026 UserState *userState = getUserState(dstUser);
1027 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001028 return userState->copyMasterKey(initState);
1029 }
1030
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001031 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1032 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001033 return userState->writeMasterKey(pw, mEntropy);
1034 }
1035
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001036 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1037 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001038 return userState->readMasterKey(pw, mEntropy);
1039 }
1040
1041 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001042 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001043 encode_key(encoded, keyName);
1044 return android::String8(encoded);
1045 }
1046
1047 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001048 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001049 encode_key(encoded, keyName);
1050 return android::String8::format("%u_%s", uid, encoded);
1051 }
1052
1053 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001054 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001055 encode_key(encoded, keyName);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001056 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001057 encoded);
1058 }
1059
Chad Brubakereecdd122015-05-07 10:19:40 -07001060 /*
1061 * Delete entries owned by userId. If keepUnencryptedEntries is true
1062 * then only encrypted entries will be removed, otherwise all entries will
1063 * be removed.
1064 */
1065 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001066 android::String8 prefix("");
1067 android::Vector<android::String16> aliases;
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001068 UserState* userState = getUserState(userId);
1069 if (saw(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubakereecdd122015-05-07 10:19:40 -07001070 return;
1071 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001072 for (uint32_t i = 0; i < aliases.size(); i++) {
1073 android::String8 filename(aliases[i]);
1074 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubakereecdd122015-05-07 10:19:40 -07001075 getKeyName(filename).string());
1076 bool shouldDelete = true;
1077 if (keepUnenryptedEntries) {
1078 Blob blob;
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001079 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001080
Chad Brubakereecdd122015-05-07 10:19:40 -07001081 /* get can fail if the blob is encrypted and the state is
1082 * not unlocked, only skip deleting blobs that were loaded and
1083 * who are not encrypted. If there are blobs we fail to read for
1084 * other reasons err on the safe side and delete them since we
1085 * can't tell if they're encrypted.
1086 */
1087 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1088 }
1089 if (shouldDelete) {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001090 del(filename, ::TYPE_ANY, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001091 }
1092 }
1093 if (!userState->deleteMasterKey()) {
1094 ALOGE("Failed to delete user %d's master key", userId);
1095 }
1096 if (!keepUnenryptedEntries) {
1097 if(!userState->reset()) {
1098 ALOGE("Failed to remove user %d's directory", userId);
1099 }
1100 }
Kenny Root655b9582013-04-04 08:37:42 -07001101 }
1102
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001103 bool isEmpty(uid_t userId) const {
1104 const UserState* userState = getUserState(userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001105 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001106 return true;
1107 }
1108
1109 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001110 if (!dir) {
1111 return true;
1112 }
Kenny Root31e27462014-09-10 11:28:03 -07001113
Kenny Roota91203b2012-02-15 15:00:46 -08001114 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001115 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001116 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001117 // We only care about files.
1118 if (file->d_type != DT_REG) {
1119 continue;
1120 }
1121
1122 // Skip anything that starts with a "."
1123 if (file->d_name[0] == '.') {
1124 continue;
1125 }
1126
Kenny Root31e27462014-09-10 11:28:03 -07001127 result = false;
1128 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001129 }
1130 closedir(dir);
1131 return result;
1132 }
1133
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001134 void lock(uid_t userId) {
1135 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001136 userState->zeroizeMasterKeysInMemory();
1137 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001138 }
1139
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001140 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1141 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001142 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1143 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001144 if (rc != NO_ERROR) {
1145 return rc;
1146 }
1147
1148 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001149 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001150 /* If we upgrade the key, we need to write it to disk again. Then
1151 * it must be read it again since the blob is encrypted each time
1152 * it's written.
1153 */
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001154 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1155 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001156 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1157 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001158 return rc;
1159 }
1160 }
Kenny Root822c3a92012-03-23 16:34:39 -07001161 }
1162
Kenny Root17208e02013-09-04 13:56:03 -07001163 /*
1164 * This will upgrade software-backed keys to hardware-backed keys when
1165 * the HAL for the device supports the newer key types.
1166 */
1167 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1168 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1169 && keyBlob->isFallback()) {
1170 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001171 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001172
1173 // The HAL allowed the import, reget the key to have the "fresh"
1174 // version.
1175 if (imported == NO_ERROR) {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001176 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001177 }
1178 }
1179
Kenny Rootd53bc922013-03-21 14:10:15 -07001180 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001181 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1182 return KEY_NOT_FOUND;
1183 }
1184
1185 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001186 }
1187
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001188 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1189 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001190 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1191 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001192 }
1193
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001194 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001195 Blob keyBlob;
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001196 ResponseCode rc = get(filename, &keyBlob, type, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001197 if (rc != ::NO_ERROR) {
1198 return rc;
1199 }
1200
1201 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1202 // A device doesn't have to implement delete_keypair.
1203 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1204 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1205 rc = ::SYSTEM_ERROR;
1206 }
1207 }
1208 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001209 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1210 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1211 if (dev->delete_key) {
1212 keymaster_key_blob_t blob;
1213 blob.key_material = keyBlob.getValue();
1214 blob.key_material_size = keyBlob.getLength();
1215 dev->delete_key(dev, &blob);
1216 }
1217 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001218 if (rc != ::NO_ERROR) {
1219 return rc;
1220 }
1221
1222 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1223 }
1224
1225 ResponseCode saw(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001226 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001227
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001228 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001229 size_t n = prefix.length();
1230
1231 DIR* dir = opendir(userState->getUserDirName());
1232 if (!dir) {
1233 ALOGW("can't open directory for user: %s", strerror(errno));
1234 return ::SYSTEM_ERROR;
1235 }
1236
1237 struct dirent* file;
1238 while ((file = readdir(dir)) != NULL) {
1239 // We only care about files.
1240 if (file->d_type != DT_REG) {
1241 continue;
1242 }
1243
1244 // Skip anything that starts with a "."
1245 if (file->d_name[0] == '.') {
1246 continue;
1247 }
1248
1249 if (!strncmp(prefix.string(), file->d_name, n)) {
1250 const char* p = &file->d_name[n];
1251 size_t plen = strlen(p);
1252
1253 size_t extra = decode_key_length(p, plen);
1254 char *match = (char*) malloc(extra + 1);
1255 if (match != NULL) {
1256 decode_key(match, p, plen);
1257 matches->push(android::String16(match, extra));
1258 free(match);
1259 } else {
1260 ALOGW("could not allocate match of size %zd", extra);
1261 }
1262 }
1263 }
1264 closedir(dir);
1265 return ::NO_ERROR;
1266 }
1267
Kenny Root07438c82012-11-02 15:41:02 -07001268 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001269 const grant_t* existing = getGrant(filename, granteeUid);
1270 if (existing == NULL) {
1271 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001272 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001273 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001274 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001275 }
1276 }
1277
Kenny Root07438c82012-11-02 15:41:02 -07001278 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001279 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1280 it != mGrants.end(); it++) {
1281 grant_t* grant = *it;
1282 if (grant->uid == granteeUid
1283 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1284 mGrants.erase(it);
1285 return true;
1286 }
Kenny Root70e3a862012-02-15 17:20:23 -08001287 }
Kenny Root70e3a862012-02-15 17:20:23 -08001288 return false;
1289 }
1290
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001291 bool hasGrant(const char* filename, const uid_t uid) const {
1292 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001293 }
1294
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001295 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001296 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001297 uint8_t* data;
1298 size_t dataLength;
1299 int rc;
1300
1301 if (mDevice->import_keypair == NULL) {
1302 ALOGE("Keymaster doesn't support import!");
1303 return SYSTEM_ERROR;
1304 }
1305
Kenny Root17208e02013-09-04 13:56:03 -07001306 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001307 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001308 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001309 /*
1310 * Maybe the device doesn't support this type of key. Try to use the
1311 * software fallback keymaster implementation. This is a little bit
1312 * lazier than checking the PKCS#8 key type, but the software
1313 * implementation will do that anyway.
1314 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001315 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001316 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001317
1318 if (rc) {
1319 ALOGE("Error while importing keypair: %d", rc);
1320 return SYSTEM_ERROR;
1321 }
Kenny Root822c3a92012-03-23 16:34:39 -07001322 }
1323
1324 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1325 free(data);
1326
Kenny Rootf9119d62013-04-03 09:22:15 -07001327 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001328 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001329
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001330 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001331 }
1332
Kenny Root1b0e3932013-09-05 13:06:32 -07001333 bool isHardwareBacked(const android::String16& keyType) const {
1334 if (mDevice == NULL) {
1335 ALOGW("can't get keymaster device");
1336 return false;
1337 }
1338
1339 if (sRSAKeyType == keyType) {
1340 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1341 } else {
1342 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1343 && (mDevice->common.module->module_api_version
1344 >= KEYMASTER_MODULE_API_VERSION_0_2);
1345 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001346 }
1347
Kenny Root655b9582013-04-04 08:37:42 -07001348 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1349 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001350 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001351 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001352
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001353 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001354 if (responseCode == NO_ERROR) {
1355 return responseCode;
1356 }
1357
1358 // If this is one of the legacy UID->UID mappings, use it.
1359 uid_t euid = get_keystore_euid(uid);
1360 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001361 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001362 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001363 if (responseCode == NO_ERROR) {
1364 return responseCode;
1365 }
1366 }
1367
1368 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001369 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001370 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001371 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001372 if (end[0] != '_' || end[1] == 0) {
1373 return KEY_NOT_FOUND;
1374 }
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001375 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001376 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001377 if (!hasGrant(filepath8.string(), uid)) {
1378 return responseCode;
1379 }
1380
1381 // It is a granted key. Try to load it.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001382 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001383 }
1384
1385 /**
1386 * Returns any existing UserState or creates it if it doesn't exist.
1387 */
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001388 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001389 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1390 it != mMasterKeys.end(); it++) {
1391 UserState* state = *it;
1392 if (state->getUserId() == userId) {
1393 return state;
1394 }
1395 }
1396
1397 UserState* userState = new UserState(userId);
1398 if (!userState->initialize()) {
1399 /* There's not much we can do if initialization fails. Trying to
1400 * unlock the keystore for that user will fail as well, so any
1401 * subsequent request for this user will just return SYSTEM_ERROR.
1402 */
1403 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1404 }
1405 mMasterKeys.add(userState);
1406 return userState;
1407 }
1408
1409 /**
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001410 * Returns any existing UserState or creates it if it doesn't exist.
1411 */
1412 UserState* getUserStateByUid(uid_t uid) {
1413 uid_t userId = get_user_id(uid);
1414 return getUserState(userId);
1415 }
1416
1417 /**
Kenny Root655b9582013-04-04 08:37:42 -07001418 * Returns NULL if the UserState doesn't already exist.
1419 */
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001420 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001421 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1422 it != mMasterKeys.end(); it++) {
1423 UserState* state = *it;
1424 if (state->getUserId() == userId) {
1425 return state;
1426 }
1427 }
1428
1429 return NULL;
1430 }
1431
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001432 /**
1433 * Returns NULL if the UserState doesn't already exist.
1434 */
1435 const UserState* getUserStateByUid(uid_t uid) const {
1436 uid_t userId = get_user_id(uid);
1437 return getUserState(userId);
1438 }
1439
Kenny Roota91203b2012-02-15 15:00:46 -08001440private:
Kenny Root655b9582013-04-04 08:37:42 -07001441 static const char* sOldMasterKey;
1442 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001443 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001444 Entropy* mEntropy;
1445
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001446 keymaster1_device_t* mDevice;
1447 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001448
Kenny Root655b9582013-04-04 08:37:42 -07001449 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001450
Kenny Root655b9582013-04-04 08:37:42 -07001451 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001452
Kenny Root655b9582013-04-04 08:37:42 -07001453 typedef struct {
1454 uint32_t version;
1455 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001456
Kenny Root655b9582013-04-04 08:37:42 -07001457 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001458
Kenny Root655b9582013-04-04 08:37:42 -07001459 const grant_t* getGrant(const char* filename, uid_t uid) const {
1460 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1461 it != mGrants.end(); it++) {
1462 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001463 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001464 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001465 return grant;
1466 }
1467 }
Kenny Root70e3a862012-02-15 17:20:23 -08001468 return NULL;
1469 }
1470
Kenny Root822c3a92012-03-23 16:34:39 -07001471 /**
1472 * Upgrade code. This will upgrade the key from the current version
1473 * to whatever is newest.
1474 */
Kenny Root655b9582013-04-04 08:37:42 -07001475 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1476 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001477 bool updated = false;
1478 uint8_t version = oldVersion;
1479
1480 /* From V0 -> V1: All old types were unknown */
1481 if (version == 0) {
1482 ALOGV("upgrading to version 1 and setting type %d", type);
1483
1484 blob->setType(type);
1485 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001486 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001487 }
1488 version = 1;
1489 updated = true;
1490 }
1491
Kenny Rootf9119d62013-04-03 09:22:15 -07001492 /* From V1 -> V2: All old keys were encrypted */
1493 if (version == 1) {
1494 ALOGV("upgrading to version 2");
1495
1496 blob->setEncrypted(true);
1497 version = 2;
1498 updated = true;
1499 }
1500
Kenny Root822c3a92012-03-23 16:34:39 -07001501 /*
1502 * If we've updated, set the key blob to the right version
1503 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001504 */
Kenny Root822c3a92012-03-23 16:34:39 -07001505 if (updated) {
1506 ALOGV("updated and writing file %s", filename);
1507 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001508 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001509
1510 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001511 }
1512
1513 /**
1514 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1515 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1516 * Then it overwrites the original blob with the new blob
1517 * format that is returned from the keymaster.
1518 */
Kenny Root655b9582013-04-04 08:37:42 -07001519 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001520 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1521 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1522 if (b.get() == NULL) {
1523 ALOGE("Problem instantiating BIO");
1524 return SYSTEM_ERROR;
1525 }
1526
1527 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1528 if (pkey.get() == NULL) {
1529 ALOGE("Couldn't read old PEM file");
1530 return SYSTEM_ERROR;
1531 }
1532
1533 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1534 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1535 if (len < 0) {
1536 ALOGE("Couldn't measure PKCS#8 length");
1537 return SYSTEM_ERROR;
1538 }
1539
Kenny Root70c98892013-02-07 09:10:36 -08001540 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1541 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001542 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1543 ALOGE("Couldn't convert to PKCS#8");
1544 return SYSTEM_ERROR;
1545 }
1546
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001547 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001548 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001549 if (rc != NO_ERROR) {
1550 return rc;
1551 }
1552
Kenny Root655b9582013-04-04 08:37:42 -07001553 return get(filename, blob, TYPE_KEY_PAIR, uid);
1554 }
1555
1556 void readMetaData() {
1557 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1558 if (in < 0) {
1559 return;
1560 }
1561 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1562 if (fileLength != sizeof(mMetaData)) {
1563 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1564 sizeof(mMetaData));
1565 }
1566 close(in);
1567 }
1568
1569 void writeMetaData() {
1570 const char* tmpFileName = ".metadata.tmp";
1571 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1572 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1573 if (out < 0) {
1574 ALOGE("couldn't write metadata file: %s", strerror(errno));
1575 return;
1576 }
1577 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1578 if (fileLength != sizeof(mMetaData)) {
1579 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1580 sizeof(mMetaData));
1581 }
1582 close(out);
1583 rename(tmpFileName, sMetaDataFile);
1584 }
1585
1586 bool upgradeKeystore() {
1587 bool upgraded = false;
1588
1589 if (mMetaData.version == 0) {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001590 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001591
1592 // Initialize first so the directory is made.
1593 userState->initialize();
1594
1595 // Migrate the old .masterkey file to user 0.
1596 if (access(sOldMasterKey, R_OK) == 0) {
1597 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1598 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1599 return false;
1600 }
1601 }
1602
1603 // Initialize again in case we had a key.
1604 userState->initialize();
1605
1606 // Try to migrate existing keys.
1607 DIR* dir = opendir(".");
1608 if (!dir) {
1609 // Give up now; maybe we can upgrade later.
1610 ALOGE("couldn't open keystore's directory; something is wrong");
1611 return false;
1612 }
1613
1614 struct dirent* file;
1615 while ((file = readdir(dir)) != NULL) {
1616 // We only care about files.
1617 if (file->d_type != DT_REG) {
1618 continue;
1619 }
1620
1621 // Skip anything that starts with a "."
1622 if (file->d_name[0] == '.') {
1623 continue;
1624 }
1625
1626 // Find the current file's user.
1627 char* end;
1628 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1629 if (end[0] != '_' || end[1] == 0) {
1630 continue;
1631 }
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001632 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001633 if (otherUser->getUserId() != 0) {
1634 unlinkat(dirfd(dir), file->d_name, 0);
1635 }
1636
1637 // Rename the file into user directory.
1638 DIR* otherdir = opendir(otherUser->getUserDirName());
1639 if (otherdir == NULL) {
1640 ALOGW("couldn't open user directory for rename");
1641 continue;
1642 }
1643 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1644 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1645 }
1646 closedir(otherdir);
1647 }
1648 closedir(dir);
1649
1650 mMetaData.version = 1;
1651 upgraded = true;
1652 }
1653
1654 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001655 }
Kenny Roota91203b2012-02-15 15:00:46 -08001656};
1657
Kenny Root655b9582013-04-04 08:37:42 -07001658const char* KeyStore::sOldMasterKey = ".masterkey";
1659const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001660
Kenny Root1b0e3932013-09-05 13:06:32 -07001661const android::String16 KeyStore::sRSAKeyType("RSA");
1662
Kenny Root07438c82012-11-02 15:41:02 -07001663namespace android {
1664class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1665public:
1666 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001667 : mKeyStore(keyStore),
1668 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001669 {
Kenny Roota91203b2012-02-15 15:00:46 -08001670 }
Kenny Roota91203b2012-02-15 15:00:46 -08001671
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001672 void binderDied(const wp<IBinder>& who) {
1673 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1674 for (auto token: operations) {
1675 abort(token);
1676 }
Kenny Root822c3a92012-03-23 16:34:39 -07001677 }
Kenny Roota91203b2012-02-15 15:00:46 -08001678
Kenny Root07438c82012-11-02 15:41:02 -07001679 int32_t test() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001680 if (!checkBinderPermission(P_TEST)) {
Kenny Root07438c82012-11-02 15:41:02 -07001681 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001682 }
Kenny Roota91203b2012-02-15 15:00:46 -08001683
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001684 return mKeyStore->getState(get_user_id(IPCThreadState::self()->getCallingUid()));
Kenny Root298e7b12012-03-26 13:54:44 -07001685 }
1686
Kenny Root07438c82012-11-02 15:41:02 -07001687 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001688 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001689 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001690 }
Kenny Root07438c82012-11-02 15:41:02 -07001691
Chad Brubaker9489b792015-04-14 11:01:45 -07001692 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001693 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001694 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001695
Kenny Root655b9582013-04-04 08:37:42 -07001696 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001697 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001698 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001699 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001700 *item = NULL;
1701 *itemLength = 0;
1702 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001703 }
Kenny Roota91203b2012-02-15 15:00:46 -08001704
Kenny Root07438c82012-11-02 15:41:02 -07001705 *item = (uint8_t*) malloc(keyBlob.getLength());
1706 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1707 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001708
Kenny Root07438c82012-11-02 15:41:02 -07001709 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001710 }
1711
Kenny Rootf9119d62013-04-03 09:22:15 -07001712 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1713 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001714 targetUid = getEffectiveUid(targetUid);
1715 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1716 flags & KEYSTORE_FLAG_ENCRYPTED);
1717 if (result != ::NO_ERROR) {
1718 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001719 }
1720
Kenny Root07438c82012-11-02 15:41:02 -07001721 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001722 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001723
1724 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001725 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1726
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001727 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001728 }
1729
Kenny Root49468902013-03-19 13:41:33 -07001730 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001731 targetUid = getEffectiveUid(targetUid);
1732 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001733 return ::PERMISSION_DENIED;
1734 }
Kenny Root07438c82012-11-02 15:41:02 -07001735 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001736 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001737 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001738 }
1739
Kenny Root49468902013-03-19 13:41:33 -07001740 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001741 targetUid = getEffectiveUid(targetUid);
1742 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001743 return ::PERMISSION_DENIED;
1744 }
1745
Kenny Root07438c82012-11-02 15:41:02 -07001746 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001747 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001748
Kenny Root655b9582013-04-04 08:37:42 -07001749 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001750 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1751 }
1752 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001753 }
1754
Kenny Root49468902013-03-19 13:41:33 -07001755 int32_t saw(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001756 targetUid = getEffectiveUid(targetUid);
1757 if (!checkBinderPermission(P_SAW, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001758 return ::PERMISSION_DENIED;
1759 }
Kenny Root07438c82012-11-02 15:41:02 -07001760 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001761 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001762
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001763 if (mKeyStore->saw(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001764 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001765 }
Kenny Root07438c82012-11-02 15:41:02 -07001766 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001767 }
1768
Kenny Root07438c82012-11-02 15:41:02 -07001769 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001770 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001771 return ::PERMISSION_DENIED;
1772 }
1773
Chad Brubaker9489b792015-04-14 11:01:45 -07001774 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubakereecdd122015-05-07 10:19:40 -07001775 mKeyStore->resetUser(get_user_id(callingUid), false);
1776 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001777 }
1778
Chad Brubakereecdd122015-05-07 10:19:40 -07001779 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001780 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001781 return ::PERMISSION_DENIED;
1782 }
Kenny Root70e3a862012-02-15 17:20:23 -08001783
Kenny Root07438c82012-11-02 15:41:02 -07001784 const String8 password8(password);
Chad Brubakereecdd122015-05-07 10:19:40 -07001785 // Flush the auth token table to prevent stale tokens from sticking
1786 // around.
1787 mAuthTokenTable.Clear();
1788
1789 if (password.size() == 0) {
1790 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001791 mKeyStore->resetUser(userId, true);
Chad Brubakereecdd122015-05-07 10:19:40 -07001792 return ::NO_ERROR;
1793 } else {
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001794 switch (mKeyStore->getState(userId)) {
Chad Brubakereecdd122015-05-07 10:19:40 -07001795 case ::STATE_UNINITIALIZED: {
1796 // generate master key, encrypt with password, write to file,
1797 // initialize mMasterKey*.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001798 return mKeyStore->initializeUser(password8, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001799 }
1800 case ::STATE_NO_ERROR: {
1801 // rewrite master key with new password.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001802 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001803 }
1804 case ::STATE_LOCKED: {
1805 ALOGE("Changing user %d's password while locked, clearing old encryption",
1806 userId);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001807 mKeyStore->resetUser(userId, true);
1808 return mKeyStore->initializeUser(password8, userId);
Chad Brubakereecdd122015-05-07 10:19:40 -07001809 }
Kenny Root07438c82012-11-02 15:41:02 -07001810 }
Chad Brubakereecdd122015-05-07 10:19:40 -07001811 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001812 }
Kenny Root70e3a862012-02-15 17:20:23 -08001813 }
1814
Chad Brubakerfd777e72015-05-12 10:43:10 -07001815 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1816 if (!checkBinderPermission(P_USER_CHANGED)) {
1817 return ::PERMISSION_DENIED;
1818 }
1819
1820 // Sanity check that the new user has an empty keystore.
1821 if (!mKeyStore->isEmpty(userId)) {
1822 ALOGW("New user %d's keystore not empty. Clearing old entries.");
1823 }
1824 // Unconditionally clear the keystore, just to be safe.
1825 mKeyStore->resetUser(userId, false);
1826
1827 // If the user has a parent user then use the parent's
1828 // masterkey/password, otherwise there's nothing to do.
1829 if (parentId != -1) {
1830 return mKeyStore->copyMasterKey(parentId, userId);
1831 } else {
1832 return ::NO_ERROR;
1833 }
1834 }
1835
1836 int32_t onUserRemoved(int32_t userId) {
1837 if (!checkBinderPermission(P_USER_CHANGED)) {
1838 return ::PERMISSION_DENIED;
1839 }
1840
1841 mKeyStore->resetUser(userId, false);
1842 return ::NO_ERROR;
1843 }
1844
Kenny Root07438c82012-11-02 15:41:02 -07001845 int32_t lock() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001846 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001847 return ::PERMISSION_DENIED;
1848 }
Kenny Root70e3a862012-02-15 17:20:23 -08001849
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001850 uid_t userId = get_user_id(IPCThreadState::self()->getCallingUid());
1851 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001852 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001853 ALOGD("calling lock in state: %d", state);
1854 return state;
1855 }
1856
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001857 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07001858 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001859 }
1860
Chad Brubakereecdd122015-05-07 10:19:40 -07001861 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001862 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001863 return ::PERMISSION_DENIED;
1864 }
1865
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001866 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001867 if (state != ::STATE_LOCKED) {
Chad Brubakereecdd122015-05-07 10:19:40 -07001868 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001869 return state;
1870 }
1871
1872 const String8 password8(pw);
Chad Brubakereecdd122015-05-07 10:19:40 -07001873 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001874 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001875 }
1876
Kenny Root07438c82012-11-02 15:41:02 -07001877 int32_t zero() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001878 if (!checkBinderPermission(P_ZERO)) {
Kenny Root07438c82012-11-02 15:41:02 -07001879 return -1;
1880 }
Kenny Root70e3a862012-02-15 17:20:23 -08001881
Chad Brubaker9489b792015-04-14 11:01:45 -07001882 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker4efce0d2015-05-12 10:42:00 -07001883 return mKeyStore->isEmpty(get_user_id(callingUid)) ? ::KEY_NOT_FOUND : ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001884 }
1885
Kenny Root96427ba2013-08-16 14:02:41 -07001886 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1887 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001888 targetUid = getEffectiveUid(targetUid);
1889 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1890 flags & KEYSTORE_FLAG_ENCRYPTED);
1891 if (result != ::NO_ERROR) {
1892 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001893 }
Kenny Root07438c82012-11-02 15:41:02 -07001894 uint8_t* data;
1895 size_t dataLength;
1896 int rc;
Kenny Root17208e02013-09-04 13:56:03 -07001897 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001898
Chad Brubaker919cb2a2015-02-05 21:58:25 -08001899 const keymaster1_device_t* device = mKeyStore->getDevice();
1900 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Kenny Root07438c82012-11-02 15:41:02 -07001901 if (device == NULL) {
1902 return ::SYSTEM_ERROR;
1903 }
1904
1905 if (device->generate_keypair == NULL) {
1906 return ::SYSTEM_ERROR;
1907 }
1908
Kenny Root17208e02013-09-04 13:56:03 -07001909 if (keyType == EVP_PKEY_DSA) {
Kenny Root96427ba2013-08-16 14:02:41 -07001910 keymaster_dsa_keygen_params_t dsa_params;
1911 memset(&dsa_params, '\0', sizeof(dsa_params));
Kenny Root07438c82012-11-02 15:41:02 -07001912
Kenny Root96427ba2013-08-16 14:02:41 -07001913 if (keySize == -1) {
1914 keySize = DSA_DEFAULT_KEY_SIZE;
1915 } else if ((keySize % 64) != 0 || keySize < DSA_MIN_KEY_SIZE
1916 || keySize > DSA_MAX_KEY_SIZE) {
1917 ALOGI("invalid key size %d", keySize);
1918 return ::SYSTEM_ERROR;
1919 }
1920 dsa_params.key_size = keySize;
1921
1922 if (args->size() == 3) {
1923 sp<KeystoreArg> gArg = args->itemAt(0);
1924 sp<KeystoreArg> pArg = args->itemAt(1);
1925 sp<KeystoreArg> qArg = args->itemAt(2);
1926
1927 if (gArg != NULL && pArg != NULL && qArg != NULL) {
1928 dsa_params.generator = reinterpret_cast<const uint8_t*>(gArg->data());
1929 dsa_params.generator_len = gArg->size();
1930
1931 dsa_params.prime_p = reinterpret_cast<const uint8_t*>(pArg->data());
1932 dsa_params.prime_p_len = pArg->size();
1933
1934 dsa_params.prime_q = reinterpret_cast<const uint8_t*>(qArg->data());
1935 dsa_params.prime_q_len = qArg->size();
1936 } else {
1937 ALOGI("not all DSA parameters were read");
1938 return ::SYSTEM_ERROR;
1939 }
1940 } else if (args->size() != 0) {
1941 ALOGI("DSA args must be 3");
1942 return ::SYSTEM_ERROR;
1943 }
1944
Kenny Root1d448c02013-11-21 10:36:53 -08001945 if (isKeyTypeSupported(device, TYPE_DSA)) {
Kenny Root17208e02013-09-04 13:56:03 -07001946 rc = device->generate_keypair(device, TYPE_DSA, &dsa_params, &data, &dataLength);
1947 } else {
1948 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001949 rc = fallback->generate_keypair(fallback, TYPE_DSA, &dsa_params, &data,
1950 &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001951 }
1952 } else if (keyType == EVP_PKEY_EC) {
Kenny Root96427ba2013-08-16 14:02:41 -07001953 keymaster_ec_keygen_params_t ec_params;
1954 memset(&ec_params, '\0', sizeof(ec_params));
1955
1956 if (keySize == -1) {
1957 keySize = EC_DEFAULT_KEY_SIZE;
1958 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1959 ALOGI("invalid key size %d", keySize);
1960 return ::SYSTEM_ERROR;
1961 }
1962 ec_params.field_size = keySize;
1963
Kenny Root1d448c02013-11-21 10:36:53 -08001964 if (isKeyTypeSupported(device, TYPE_EC)) {
Kenny Root17208e02013-09-04 13:56:03 -07001965 rc = device->generate_keypair(device, TYPE_EC, &ec_params, &data, &dataLength);
1966 } else {
1967 isFallback = true;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001968 rc = fallback->generate_keypair(fallback, TYPE_EC, &ec_params, &data, &dataLength);
Kenny Root17208e02013-09-04 13:56:03 -07001969 }
Kenny Root96427ba2013-08-16 14:02:41 -07001970 } else if (keyType == EVP_PKEY_RSA) {
1971 keymaster_rsa_keygen_params_t rsa_params;
1972 memset(&rsa_params, '\0', sizeof(rsa_params));
1973 rsa_params.public_exponent = RSA_DEFAULT_EXPONENT;
1974
1975 if (keySize == -1) {
1976 keySize = RSA_DEFAULT_KEY_SIZE;
1977 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1978 ALOGI("invalid key size %d", keySize);
1979 return ::SYSTEM_ERROR;
1980 }
1981 rsa_params.modulus_size = keySize;
1982
1983 if (args->size() > 1) {
Matteo Franchin6489e022013-12-02 14:46:29 +00001984 ALOGI("invalid number of arguments: %zu", args->size());
Kenny Root96427ba2013-08-16 14:02:41 -07001985 return ::SYSTEM_ERROR;
1986 } else if (args->size() == 1) {
1987 sp<KeystoreArg> pubExpBlob = args->itemAt(0);
1988 if (pubExpBlob != NULL) {
1989 Unique_BIGNUM pubExpBn(
1990 BN_bin2bn(reinterpret_cast<const unsigned char*>(pubExpBlob->data()),
1991 pubExpBlob->size(), NULL));
1992 if (pubExpBn.get() == NULL) {
1993 ALOGI("Could not convert public exponent to BN");
1994 return ::SYSTEM_ERROR;
1995 }
1996 unsigned long pubExp = BN_get_word(pubExpBn.get());
1997 if (pubExp == 0xFFFFFFFFL) {
1998 ALOGI("cannot represent public exponent as a long value");
1999 return ::SYSTEM_ERROR;
2000 }
2001 rsa_params.public_exponent = pubExp;
2002 }
2003 }
2004
2005 rc = device->generate_keypair(device, TYPE_RSA, &rsa_params, &data, &dataLength);
2006 } else {
2007 ALOGW("Unsupported key type %d", keyType);
2008 rc = -1;
2009 }
2010
Kenny Root07438c82012-11-02 15:41:02 -07002011 if (rc) {
2012 return ::SYSTEM_ERROR;
2013 }
2014
Kenny Root655b9582013-04-04 08:37:42 -07002015 String8 name8(name);
Chad Brubaker9489b792015-04-14 11:01:45 -07002016 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002017
2018 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
2019 free(data);
2020
Kenny Rootee8068b2013-10-07 09:49:15 -07002021 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07002022 keyBlob.setFallback(isFallback);
2023
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002024 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08002025 }
2026
Kenny Rootf9119d62013-04-03 09:22:15 -07002027 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
2028 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002029 targetUid = getEffectiveUid(targetUid);
2030 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
2031 flags & KEYSTORE_FLAG_ENCRYPTED);
2032 if (result != ::NO_ERROR) {
2033 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002034 }
Kenny Root07438c82012-11-02 15:41:02 -07002035 String8 name8(name);
Kenny Root60898892013-04-16 18:08:03 -07002036 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07002037
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002038 return mKeyStore->importKey(data, length, filename.string(), get_user_id(targetUid),
2039 flags);
Kenny Root70e3a862012-02-15 17:20:23 -08002040 }
2041
Kenny Root07438c82012-11-02 15:41:02 -07002042 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
2043 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002044 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002045 return ::PERMISSION_DENIED;
2046 }
Kenny Root07438c82012-11-02 15:41:02 -07002047
Chad Brubaker9489b792015-04-14 11:01:45 -07002048 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002049 Blob keyBlob;
2050 String8 name8(name);
2051
Kenny Rootd38a0b02013-02-13 12:59:14 -08002052 ALOGV("sign %s from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002053
Kenny Root655b9582013-04-04 08:37:42 -07002054 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Rootd38a0b02013-02-13 12:59:14 -08002055 ::TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002056 if (responseCode != ::NO_ERROR) {
2057 return responseCode;
2058 }
2059
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002060 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002061 if (device == NULL) {
2062 ALOGE("no keymaster device; cannot sign");
2063 return ::SYSTEM_ERROR;
2064 }
2065
2066 if (device->sign_data == NULL) {
2067 ALOGE("device doesn't implement signing");
2068 return ::SYSTEM_ERROR;
2069 }
2070
2071 keymaster_rsa_sign_params_t params;
2072 params.digest_type = DIGEST_NONE;
2073 params.padding_type = PADDING_NONE;
Chad Brubaker9489b792015-04-14 11:01:45 -07002074 int rc = device->sign_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002075 length, out, outLength);
Kenny Root07438c82012-11-02 15:41:02 -07002076 if (rc) {
2077 ALOGW("device couldn't sign data");
2078 return ::SYSTEM_ERROR;
2079 }
2080
2081 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08002082 }
2083
Kenny Root07438c82012-11-02 15:41:02 -07002084 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2085 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002086 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002087 return ::PERMISSION_DENIED;
2088 }
Kenny Root70e3a862012-02-15 17:20:23 -08002089
Chad Brubaker9489b792015-04-14 11:01:45 -07002090 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07002091 Blob keyBlob;
2092 String8 name8(name);
2093 int rc;
Kenny Root70e3a862012-02-15 17:20:23 -08002094
Kenny Root655b9582013-04-04 08:37:42 -07002095 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07002096 TYPE_KEY_PAIR);
Kenny Root07438c82012-11-02 15:41:02 -07002097 if (responseCode != ::NO_ERROR) {
2098 return responseCode;
2099 }
Kenny Root70e3a862012-02-15 17:20:23 -08002100
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002101 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002102 if (device == NULL) {
2103 return ::SYSTEM_ERROR;
2104 }
Kenny Root70e3a862012-02-15 17:20:23 -08002105
Kenny Root07438c82012-11-02 15:41:02 -07002106 if (device->verify_data == NULL) {
2107 return ::SYSTEM_ERROR;
2108 }
Kenny Root70e3a862012-02-15 17:20:23 -08002109
Kenny Root07438c82012-11-02 15:41:02 -07002110 keymaster_rsa_sign_params_t params;
2111 params.digest_type = DIGEST_NONE;
2112 params.padding_type = PADDING_NONE;
Kenny Root344e0bc2012-08-15 10:44:03 -07002113
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002114 rc = device->verify_data(device, &params, keyBlob.getValue(), keyBlob.getLength(), data,
2115 dataLength, signature, signatureLength);
Kenny Root07438c82012-11-02 15:41:02 -07002116 if (rc) {
2117 return ::SYSTEM_ERROR;
2118 } else {
2119 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002120 }
2121 }
Kenny Root07438c82012-11-02 15:41:02 -07002122
2123 /*
2124 * TODO: The abstraction between things stored in hardware and regular blobs
2125 * of data stored on the filesystem should be moved down to keystore itself.
2126 * Unfortunately the Java code that calls this has naming conventions that it
2127 * knows about. Ideally keystore shouldn't be used to store random blobs of
2128 * data.
2129 *
2130 * Until that happens, it's necessary to have a separate "get_pubkey" and
2131 * "del_key" since the Java code doesn't really communicate what it's
2132 * intentions are.
2133 */
2134 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002135 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002136 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002137 ALOGW("permission denied for %d: get_pubkey", callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002138 return ::PERMISSION_DENIED;
2139 }
Kenny Root07438c82012-11-02 15:41:02 -07002140
Kenny Root07438c82012-11-02 15:41:02 -07002141 Blob keyBlob;
2142 String8 name8(name);
2143
Kenny Rootd38a0b02013-02-13 12:59:14 -08002144 ALOGV("get_pubkey '%s' from uid %d", name8.string(), callingUid);
Kenny Root07438c82012-11-02 15:41:02 -07002145
Kenny Root655b9582013-04-04 08:37:42 -07002146 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root07438c82012-11-02 15:41:02 -07002147 TYPE_KEY_PAIR);
2148 if (responseCode != ::NO_ERROR) {
2149 return responseCode;
2150 }
2151
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002152 const keymaster1_device_t* device = mKeyStore->getDeviceForBlob(keyBlob);
Kenny Root07438c82012-11-02 15:41:02 -07002153 if (device == NULL) {
2154 return ::SYSTEM_ERROR;
2155 }
2156
2157 if (device->get_keypair_public == NULL) {
2158 ALOGE("device has no get_keypair_public implementation!");
2159 return ::SYSTEM_ERROR;
2160 }
2161
Kenny Root17208e02013-09-04 13:56:03 -07002162 int rc;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08002163 rc = device->get_keypair_public(device, keyBlob.getValue(), keyBlob.getLength(), pubkey,
2164 pubkeyLength);
Kenny Root07438c82012-11-02 15:41:02 -07002165 if (rc) {
2166 return ::SYSTEM_ERROR;
2167 }
2168
2169 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002170 }
Kenny Root07438c82012-11-02 15:41:02 -07002171
Kenny Root49468902013-03-19 13:41:33 -07002172 int32_t del_key(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002173 return del(name, targetUid);
Kenny Root07438c82012-11-02 15:41:02 -07002174 }
2175
2176 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002177 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002178 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2179 if (result != ::NO_ERROR) {
2180 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002181 }
2182
2183 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002184 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002185
Kenny Root655b9582013-04-04 08:37:42 -07002186 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002187 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2188 }
2189
Kenny Root655b9582013-04-04 08:37:42 -07002190 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002191 return ::NO_ERROR;
2192 }
2193
2194 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002195 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002196 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2197 if (result != ::NO_ERROR) {
2198 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002199 }
2200
2201 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002202 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002203
Kenny Root655b9582013-04-04 08:37:42 -07002204 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002205 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2206 }
2207
Kenny Root655b9582013-04-04 08:37:42 -07002208 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002209 }
2210
2211 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002212 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002213 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002214 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002215 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002216 }
Kenny Root07438c82012-11-02 15:41:02 -07002217
2218 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002219 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002220
Kenny Root655b9582013-04-04 08:37:42 -07002221 if (access(filename.string(), R_OK) == -1) {
2222 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002223 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002224 }
2225
Kenny Root655b9582013-04-04 08:37:42 -07002226 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002227 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002228 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002229 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002230 }
2231
2232 struct stat s;
2233 int ret = fstat(fd, &s);
2234 close(fd);
2235 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002236 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002237 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002238 }
2239
Kenny Root36a9e232013-02-04 14:24:15 -08002240 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002241 }
2242
Kenny Rootd53bc922013-03-21 14:10:15 -07002243 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2244 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002245 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002246 pid_t spid = IPCThreadState::self()->getCallingPid();
2247 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002248 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002249 return -1L;
2250 }
2251
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002252 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002253 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002254 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002255 return state;
2256 }
2257
Kenny Rootd53bc922013-03-21 14:10:15 -07002258 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2259 srcUid = callingUid;
2260 } else if (!is_granted_to(callingUid, srcUid)) {
2261 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002262 return ::PERMISSION_DENIED;
2263 }
2264
Kenny Rootd53bc922013-03-21 14:10:15 -07002265 if (destUid == -1) {
2266 destUid = callingUid;
2267 }
2268
2269 if (srcUid != destUid) {
2270 if (static_cast<uid_t>(srcUid) != callingUid) {
2271 ALOGD("can only duplicate from caller to other or to same uid: "
2272 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2273 return ::PERMISSION_DENIED;
2274 }
2275
2276 if (!is_granted_to(callingUid, destUid)) {
2277 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2278 return ::PERMISSION_DENIED;
2279 }
2280 }
2281
2282 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002283 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002284
Kenny Rootd53bc922013-03-21 14:10:15 -07002285 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002286 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002287
Kenny Root655b9582013-04-04 08:37:42 -07002288 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2289 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002290 return ::SYSTEM_ERROR;
2291 }
2292
Kenny Rootd53bc922013-03-21 14:10:15 -07002293 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002294 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002295 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002296 if (responseCode != ::NO_ERROR) {
2297 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002298 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002299
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002300 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002301 }
2302
Kenny Root1b0e3932013-09-05 13:06:32 -07002303 int32_t is_hardware_backed(const String16& keyType) {
2304 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002305 }
2306
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002307 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002308 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubaker01771ae2015-05-01 10:21:27 -07002309 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002310 return ::PERMISSION_DENIED;
2311 }
2312
Robin Lee4b84fdc2014-09-24 11:56:57 +01002313 String8 prefix = String8::format("%u_", targetUid);
2314 Vector<String16> aliases;
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002315 if (mKeyStore->saw(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002316 return ::SYSTEM_ERROR;
2317 }
2318
Robin Lee4b84fdc2014-09-24 11:56:57 +01002319 for (uint32_t i = 0; i < aliases.size(); i++) {
2320 String8 name8(aliases[i]);
2321 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002322 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002323 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002324 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002325 }
2326
Robin Lee4b84fdc2014-09-24 11:56:57 +01002327 int32_t reset_uid(int32_t targetUid) {
Chad Brubakereecdd122015-05-07 10:19:40 -07002328 // TODO: Remove this method from the binder interface
Chad Brubaker9489b792015-04-14 11:01:45 -07002329 targetUid = getEffectiveUid(targetUid);
Chad Brubakereecdd122015-05-07 10:19:40 -07002330 return onUserPasswordChanged(get_user_id(targetUid), String16(""));
Robin Lee4e865752014-08-19 17:37:55 +01002331 }
2332
2333 int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002334 if (!checkBinderPermission(P_SYNC_UID, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002335 return ::PERMISSION_DENIED;
2336 }
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002337 uid_t sourceUser = get_user_id(sourceUid);
2338 uid_t targetUser = get_user_id(targetUid);
Chad Brubaker9489b792015-04-14 11:01:45 -07002339
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002340 if (sourceUser == targetUser) {
Robin Lee4e865752014-08-19 17:37:55 +01002341 return ::SYSTEM_ERROR;
2342 }
2343
2344 // Initialise user keystore with existing master key held in-memory
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002345 return mKeyStore->copyMasterKey(sourceUser, targetUser);
Robin Lee4e865752014-08-19 17:37:55 +01002346 }
2347
2348 int32_t password_uid(const String16& pw, int32_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002349 targetUid = getEffectiveUid(targetUid);
2350 if (!checkBinderPermission(P_PASSWORD, targetUid)) {
Robin Lee4e865752014-08-19 17:37:55 +01002351 return ::PERMISSION_DENIED;
2352 }
Robin Lee4e865752014-08-19 17:37:55 +01002353 const String8 password8(pw);
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002354 uid_t userId = get_user_id(targetUid);
Robin Lee4e865752014-08-19 17:37:55 +01002355
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002356 switch (mKeyStore->getState(userId)) {
Robin Lee4e865752014-08-19 17:37:55 +01002357 case ::STATE_UNINITIALIZED: {
2358 // generate master key, encrypt with password, write to file, initialize mMasterKey*.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002359 return mKeyStore->initializeUser(password8, userId);
Robin Lee4e865752014-08-19 17:37:55 +01002360 }
2361 case ::STATE_NO_ERROR: {
2362 // rewrite master key with new password.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002363 return mKeyStore->writeMasterKey(password8, userId);
Robin Lee4e865752014-08-19 17:37:55 +01002364 }
2365 case ::STATE_LOCKED: {
2366 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002367 return mKeyStore->readMasterKey(password8, userId);
Robin Lee4e865752014-08-19 17:37:55 +01002368 }
2369 }
2370 return ::SYSTEM_ERROR;
2371 }
2372
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002373 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2374 const keymaster1_device_t* device = mKeyStore->getDevice();
2375 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2376 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2377 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2378 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2379 device->add_rng_entropy != NULL) {
2380 devResult = device->add_rng_entropy(device, data, dataLength);
2381 }
2382 if (fallback->add_rng_entropy) {
2383 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2384 }
2385 if (devResult) {
2386 return devResult;
2387 }
2388 if (fallbackResult) {
2389 return fallbackResult;
2390 }
2391 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002392 }
2393
Chad Brubaker17d68b92015-02-05 22:04:16 -08002394 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002395 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2396 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002397 uid = getEffectiveUid(uid);
2398 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2399 flags & KEYSTORE_FLAG_ENCRYPTED);
2400 if (rc != ::NO_ERROR) {
2401 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002402 }
2403
Chad Brubaker9489b792015-04-14 11:01:45 -07002404 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002405 bool isFallback = false;
2406 keymaster_key_blob_t blob;
2407 keymaster_key_characteristics_t *out = NULL;
2408
2409 const keymaster1_device_t* device = mKeyStore->getDevice();
2410 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2411 if (device == NULL) {
2412 return ::SYSTEM_ERROR;
2413 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002414 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002415 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2416 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002417 if (!entropy) {
2418 rc = KM_ERROR_OK;
2419 } else if (device->add_rng_entropy) {
2420 rc = device->add_rng_entropy(device, entropy, entropyLength);
2421 } else {
2422 rc = KM_ERROR_UNIMPLEMENTED;
2423 }
2424 if (rc == KM_ERROR_OK) {
2425 rc = device->generate_key(device, params.params.data(), params.params.size(),
2426 &blob, &out);
2427 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002428 }
2429 // If the HW device didn't support generate_key or generate_key failed
2430 // fall back to the software implementation.
2431 if (rc && fallback->generate_key != NULL) {
2432 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002433 if (!entropy) {
2434 rc = KM_ERROR_OK;
2435 } else if (fallback->add_rng_entropy) {
2436 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2437 } else {
2438 rc = KM_ERROR_UNIMPLEMENTED;
2439 }
2440 if (rc == KM_ERROR_OK) {
2441 rc = fallback->generate_key(fallback, params.params.data(), params.params.size(),
2442 &blob,
2443 &out);
2444 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002445 }
2446
2447 if (out) {
2448 if (outCharacteristics) {
2449 outCharacteristics->characteristics = *out;
2450 } else {
2451 keymaster_free_characteristics(out);
2452 }
2453 free(out);
2454 }
2455
2456 if (rc) {
2457 return rc;
2458 }
2459
2460 String8 name8(name);
2461 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2462
2463 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2464 keyBlob.setFallback(isFallback);
2465 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2466
2467 free(const_cast<uint8_t*>(blob.key_material));
2468
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002469 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002470 }
2471
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002472 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002473 const keymaster_blob_t* clientId,
2474 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002475 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002476 if (!outCharacteristics) {
2477 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2478 }
2479
2480 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2481
2482 Blob keyBlob;
2483 String8 name8(name);
2484 int rc;
2485
2486 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2487 TYPE_KEYMASTER_10);
2488 if (responseCode != ::NO_ERROR) {
2489 return responseCode;
2490 }
2491 keymaster_key_blob_t key;
2492 key.key_material_size = keyBlob.getLength();
2493 key.key_material = keyBlob.getValue();
2494 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2495 keymaster_key_characteristics_t *out = NULL;
2496 if (!dev->get_key_characteristics) {
2497 ALOGW("device does not implement get_key_characteristics");
2498 return KM_ERROR_UNIMPLEMENTED;
2499 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002500 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002501 if (out) {
2502 outCharacteristics->characteristics = *out;
2503 free(out);
2504 }
2505 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002506 }
2507
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002508 int32_t importKey(const String16& name, const KeymasterArguments& params,
2509 keymaster_key_format_t format, const uint8_t *keyData,
2510 size_t keyLength, int uid, int flags,
2511 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002512 uid = getEffectiveUid(uid);
2513 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2514 flags & KEYSTORE_FLAG_ENCRYPTED);
2515 if (rc != ::NO_ERROR) {
2516 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002517 }
2518
Chad Brubaker9489b792015-04-14 11:01:45 -07002519 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002520 bool isFallback = false;
2521 keymaster_key_blob_t blob;
2522 keymaster_key_characteristics_t *out = NULL;
2523
2524 const keymaster1_device_t* device = mKeyStore->getDevice();
2525 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2526 if (device == NULL) {
2527 return ::SYSTEM_ERROR;
2528 }
2529 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2530 device->import_key != NULL) {
2531 rc = device->import_key(device, params.params.data(), params.params.size(),
2532 format, keyData, keyLength, &blob, &out);
2533 }
2534 if (rc && fallback->import_key != NULL) {
2535 isFallback = true;
2536 rc = fallback->import_key(fallback, params.params.data(), params.params.size(),
2537 format, keyData, keyLength, &blob, &out);
2538 }
2539 if (out) {
2540 if (outCharacteristics) {
2541 outCharacteristics->characteristics = *out;
2542 } else {
2543 keymaster_free_characteristics(out);
2544 }
2545 free(out);
2546 }
2547 if (rc) {
2548 return rc;
2549 }
2550
2551 String8 name8(name);
2552 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2553
2554 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2555 keyBlob.setFallback(isFallback);
2556 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2557
2558 free((void*) blob.key_material);
2559
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002560 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002561 }
2562
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002563 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002564 const keymaster_blob_t* clientId,
2565 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002566
2567 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2568
2569 Blob keyBlob;
2570 String8 name8(name);
2571 int rc;
2572
2573 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2574 TYPE_KEYMASTER_10);
2575 if (responseCode != ::NO_ERROR) {
2576 result->resultCode = responseCode;
2577 return;
2578 }
2579 keymaster_key_blob_t key;
2580 key.key_material_size = keyBlob.getLength();
2581 key.key_material = keyBlob.getValue();
2582 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2583 if (!dev->export_key) {
2584 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2585 return;
2586 }
2587 uint8_t* ptr = NULL;
Chad Brubakerd6634422015-03-21 22:36:07 -07002588 rc = dev->export_key(dev, format, &key, clientId, appData,
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002589 &ptr, &result->dataLength);
2590 result->exportData.reset(ptr);
2591 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002592 }
2593
Chad Brubakerad6514a2015-04-09 14:00:26 -07002594
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002595 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002596 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
2597 size_t entropyLength, KeymasterArguments* outParams, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002598 if (!result || !outParams) {
2599 ALOGE("Unexpected null arguments to begin()");
2600 return;
2601 }
2602 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2603 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2604 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2605 result->resultCode = ::PERMISSION_DENIED;
2606 return;
2607 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002608 if (!checkAllowedOperationParams(params.params)) {
2609 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2610 return;
2611 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002612 Blob keyBlob;
2613 String8 name8(name);
2614 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2615 TYPE_KEYMASTER_10);
2616 if (responseCode != ::NO_ERROR) {
2617 result->resultCode = responseCode;
2618 return;
2619 }
2620 keymaster_key_blob_t key;
2621 key.key_material_size = keyBlob.getLength();
2622 key.key_material = keyBlob.getValue();
2623 keymaster_key_param_t* out;
2624 size_t outSize;
2625 keymaster_operation_handle_t handle;
2626 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002627 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002628 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002629 Unique_keymaster_key_characteristics characteristics;
2630 characteristics.reset(new keymaster_key_characteristics_t);
2631 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2632 if (err) {
2633 result->resultCode = err;
2634 return;
2635 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002636 const hw_auth_token_t* authToken = NULL;
2637 int32_t authResult = getAuthToken(characteristics.get(), 0, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002638 /*failOnTokenMissing*/ false);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002639 // If per-operation auth is needed we need to begin the operation and
2640 // the client will need to authorize that operation before calling
2641 // update. Any other auth issues stop here.
2642 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2643 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002644 return;
2645 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002646 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002647 // Add entropy to the device first.
2648 if (entropy) {
2649 if (dev->add_rng_entropy) {
2650 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2651 } else {
2652 err = KM_ERROR_UNIMPLEMENTED;
2653 }
2654 if (err) {
2655 result->resultCode = err;
2656 return;
2657 }
2658 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002659 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
2660 &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002661
2662 // If there are too many operations abort the oldest operation that was
2663 // started as pruneable and try again.
2664 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2665 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2666 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2667 if (abort(oldest) != ::NO_ERROR) {
2668 break;
2669 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002670 err = dev->begin(dev, purpose, &key, opParams.data(), opParams.size(), &out, &outSize,
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002671 &handle);
2672 }
2673 if (err) {
2674 result->resultCode = err;
2675 return;
2676 }
2677 if (out) {
2678 outParams->params.assign(out, out + outSize);
2679 free(out);
2680 }
2681
Chad Brubakerad6514a2015-04-09 14:00:26 -07002682 sp<IBinder> operationToken = mOperationMap.addOperation(handle, dev, appToken,
2683 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002684 pruneable);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002685 if (authToken) {
2686 mOperationMap.setOperationAuthToken(operationToken, authToken);
2687 }
2688 // Return the authentication lookup result. If this is a per operation
2689 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2690 // application should get an auth token using the handle before the
2691 // first call to update, which will fail if keystore hasn't received the
2692 // auth token.
2693 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002694 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002695 result->handle = handle;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002696 }
2697
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002698 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2699 size_t dataLength, OperationResult* result) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002700 if (!checkAllowedOperationParams(params.params)) {
2701 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2702 return;
2703 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002704 const keymaster1_device_t* dev;
2705 keymaster_operation_handle_t handle;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002706 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002707 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2708 return;
2709 }
2710 uint8_t* output_buf = NULL;
2711 size_t output_length = 0;
2712 size_t consumed = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002713 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002714 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2715 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002716 result->resultCode = authResult;
2717 return;
2718 }
2719 keymaster_error_t err = dev->update(dev, handle, opParams.data(), opParams.size(), data,
2720 dataLength, &consumed, &output_buf, &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002721 result->data.reset(output_buf);
2722 result->dataLength = output_length;
2723 result->inputConsumed = consumed;
2724 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002725 }
2726
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002727 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
2728 const uint8_t* signature, size_t signatureLength, OperationResult* result) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002729 if (!checkAllowedOperationParams(params.params)) {
2730 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2731 return;
2732 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002733 const keymaster1_device_t* dev;
2734 keymaster_operation_handle_t handle;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002735 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002736 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2737 return;
2738 }
2739 uint8_t* output_buf = NULL;
2740 size_t output_length = 0;
Chad Brubaker06801e02015-03-31 15:13:13 -07002741 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002742 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2743 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002744 result->resultCode = authResult;
2745 return;
2746 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002747
Chad Brubaker06801e02015-03-31 15:13:13 -07002748 keymaster_error_t err = dev->finish(dev, handle, opParams.data(), opParams.size(),
2749 signature, signatureLength, &output_buf,
2750 &output_length);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002751 // Remove the operation regardless of the result
2752 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002753 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002754 result->data.reset(output_buf);
2755 result->dataLength = output_length;
2756 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002757 }
2758
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002759 int32_t abort(const sp<IBinder>& token) {
2760 const keymaster1_device_t* dev;
2761 keymaster_operation_handle_t handle;
Chad Brubaker06801e02015-03-31 15:13:13 -07002762 if (!mOperationMap.getOperation(token, &handle, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002763 return KM_ERROR_INVALID_OPERATION_HANDLE;
2764 }
2765 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002766 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002767 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002768 rc = KM_ERROR_UNIMPLEMENTED;
2769 } else {
2770 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002771 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002772 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002773 if (rc) {
2774 return rc;
2775 }
2776 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002777 }
2778
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002779 bool isOperationAuthorized(const sp<IBinder>& token) {
2780 const keymaster1_device_t* dev;
2781 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002782 const keymaster_key_characteristics_t* characteristics;
2783 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002784 return false;
2785 }
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002786 const hw_auth_token_t* authToken = NULL;
2787 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002788 std::vector<keymaster_key_param_t> ignored;
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002789 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2790 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002791 }
2792
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002793 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002794 if (!checkBinderPermission(P_ADD_AUTH)) {
2795 ALOGW("addAuthToken: permission denied for %d",
2796 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002797 return ::PERMISSION_DENIED;
2798 }
2799 if (length != sizeof(hw_auth_token_t)) {
2800 return KM_ERROR_INVALID_ARGUMENT;
2801 }
2802 hw_auth_token_t* authToken = new hw_auth_token_t;
2803 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2804 // The table takes ownership of authToken.
2805 mAuthTokenTable.AddAuthenticationToken(authToken);
2806 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002807 }
2808
Kenny Root07438c82012-11-02 15:41:02 -07002809private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002810 static const int32_t UID_SELF = -1;
2811
2812 /**
2813 * Get the effective target uid for a binder operation that takes an
2814 * optional uid as the target.
2815 */
2816 inline uid_t getEffectiveUid(int32_t targetUid) {
2817 if (targetUid == UID_SELF) {
2818 return IPCThreadState::self()->getCallingUid();
2819 }
2820 return static_cast<uid_t>(targetUid);
2821 }
2822
2823 /**
2824 * Check if the caller of the current binder method has the required
2825 * permission and if acting on other uids the grants to do so.
2826 */
2827 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2828 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2829 pid_t spid = IPCThreadState::self()->getCallingPid();
2830 if (!has_permission(callingUid, permission, spid)) {
2831 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2832 return false;
2833 }
2834 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2835 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2836 return false;
2837 }
2838 return true;
2839 }
2840
2841 /**
2842 * Check if the caller of the current binder method has the required
Chad Brubaker01771ae2015-05-01 10:21:27 -07002843 * permission and the target uid is the caller or the caller is system.
2844 */
2845 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2846 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2847 pid_t spid = IPCThreadState::self()->getCallingPid();
2848 if (!has_permission(callingUid, permission, spid)) {
2849 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2850 return false;
2851 }
2852 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2853 }
2854
2855 /**
2856 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002857 * permission or the target of the operation is the caller's uid. This is
2858 * for operation where the permission is only for cross-uid activity and all
2859 * uids are allowed to act on their own (ie: clearing all entries for a
2860 * given uid).
2861 */
2862 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2863 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2864 if (getEffectiveUid(targetUid) == callingUid) {
2865 return true;
2866 } else {
2867 return checkBinderPermission(permission, targetUid);
2868 }
2869 }
2870
2871 /**
2872 * Helper method to check that the caller has the required permission as
2873 * well as the keystore is in the unlocked state if checkUnlocked is true.
2874 *
2875 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2876 * otherwise the state of keystore when not unlocked and checkUnlocked is
2877 * true.
2878 */
2879 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2880 bool checkUnlocked = true) {
2881 if (!checkBinderPermission(permission, targetUid)) {
2882 return ::PERMISSION_DENIED;
2883 }
Chad Brubaker4efce0d2015-05-12 10:42:00 -07002884 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002885 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2886 return state;
2887 }
2888
2889 return ::NO_ERROR;
2890
2891 }
2892
Kenny Root9d45d1c2013-02-14 10:32:30 -08002893 inline bool isKeystoreUnlocked(State state) {
2894 switch (state) {
2895 case ::STATE_NO_ERROR:
2896 return true;
2897 case ::STATE_UNINITIALIZED:
2898 case ::STATE_LOCKED:
2899 return false;
2900 }
2901 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002902 }
2903
Chad Brubaker919cb2a2015-02-05 21:58:25 -08002904 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002905 const int32_t device_api = device->common.module->module_api_version;
2906 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2907 switch (keyType) {
2908 case TYPE_RSA:
2909 case TYPE_DSA:
2910 case TYPE_EC:
2911 return true;
2912 default:
2913 return false;
2914 }
2915 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2916 switch (keyType) {
2917 case TYPE_RSA:
2918 return true;
2919 case TYPE_DSA:
2920 return device->flags & KEYMASTER_SUPPORTS_DSA;
2921 case TYPE_EC:
2922 return device->flags & KEYMASTER_SUPPORTS_EC;
2923 default:
2924 return false;
2925 }
2926 } else {
2927 return keyType == TYPE_RSA;
2928 }
2929 }
2930
Chad Brubakeraebbfc22015-04-23 11:06:16 -07002931 /**
2932 * Check that all keymaster_key_param_t's provided by the application are
2933 * allowed. Any parameter that keystore adds itself should be disallowed here.
2934 */
2935 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2936 for (auto param: params) {
2937 switch (param.tag) {
2938 case KM_TAG_AUTH_TOKEN:
2939 return false;
2940 default:
2941 break;
2942 }
2943 }
2944 return true;
2945 }
2946
2947 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2948 const keymaster1_device_t* dev,
2949 const std::vector<keymaster_key_param_t>& params,
2950 keymaster_key_characteristics_t* out) {
2951 UniquePtr<keymaster_blob_t> appId;
2952 UniquePtr<keymaster_blob_t> appData;
2953 for (auto param : params) {
2954 if (param.tag == KM_TAG_APPLICATION_ID) {
2955 appId.reset(new keymaster_blob_t);
2956 appId->data = param.blob.data;
2957 appId->data_length = param.blob.data_length;
2958 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2959 appData.reset(new keymaster_blob_t);
2960 appData->data = param.blob.data;
2961 appData->data_length = param.blob.data_length;
2962 }
2963 }
2964 keymaster_key_characteristics_t* result = NULL;
2965 if (!dev->get_key_characteristics) {
2966 return KM_ERROR_UNIMPLEMENTED;
2967 }
2968 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2969 appData.get(), &result);
2970 if (result) {
2971 *out = *result;
2972 free(result);
2973 }
2974 return error;
2975 }
2976
2977 /**
2978 * Get the auth token for this operation from the auth token table.
2979 *
2980 * Returns ::NO_ERROR if the auth token was set or none was required.
2981 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2982 * authorization token exists for that operation and
2983 * failOnTokenMissing is false.
2984 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2985 * token for the operation
2986 */
2987 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2988 keymaster_operation_handle_t handle,
2989 const hw_auth_token_t** authToken,
2990 bool failOnTokenMissing = true) {
2991
2992 std::vector<keymaster_key_param_t> allCharacteristics;
2993 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2994 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2995 }
2996 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2997 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2998 }
2999 keymaster::AuthTokenTable::Error err =
3000 mAuthTokenTable.FindAuthorization(allCharacteristics.data(),
3001 allCharacteristics.size(), handle, authToken);
3002 switch (err) {
3003 case keymaster::AuthTokenTable::OK:
3004 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
3005 return ::NO_ERROR;
3006 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
3007 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
3008 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
3009 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
3010 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
3011 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
3012 (int32_t) ::OP_AUTH_NEEDED;
3013 default:
3014 ALOGE("Unexpected FindAuthorization return value %d", err);
3015 return KM_ERROR_INVALID_ARGUMENT;
3016 }
3017 }
3018
3019 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
3020 const hw_auth_token_t* token) {
3021 if (token) {
3022 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
3023 reinterpret_cast<const uint8_t*>(token),
3024 sizeof(hw_auth_token_t)));
3025 }
3026 }
3027
3028 /**
3029 * Add the auth token for the operation to the param list if the operation
3030 * requires authorization. Uses the cached result in the OperationMap if available
3031 * otherwise gets the token from the AuthTokenTable and caches the result.
3032 *
3033 * Returns ::NO_ERROR if the auth token was added or not needed.
3034 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
3035 * authenticated.
3036 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
3037 * operation token.
3038 */
3039 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
3040 std::vector<keymaster_key_param_t>* params) {
3041 const hw_auth_token_t* authToken = NULL;
Chad Brubaker6b541162015-04-29 19:58:34 -07003042 mOperationMap.getOperationAuthToken(token, &authToken);
3043 if (!authToken) {
Chad Brubakeraebbfc22015-04-23 11:06:16 -07003044 const keymaster1_device_t* dev;
3045 keymaster_operation_handle_t handle;
3046 const keymaster_key_characteristics_t* characteristics = NULL;
3047 if (!mOperationMap.getOperation(token, &handle, &dev, &characteristics)) {
3048 return KM_ERROR_INVALID_OPERATION_HANDLE;
3049 }
3050 int32_t result = getAuthToken(characteristics, handle, &authToken);
3051 if (result != ::NO_ERROR) {
3052 return result;
3053 }
3054 if (authToken) {
3055 mOperationMap.setOperationAuthToken(token, authToken);
3056 }
3057 }
3058 addAuthToParams(params, authToken);
3059 return ::NO_ERROR;
3060 }
3061
Kenny Root07438c82012-11-02 15:41:02 -07003062 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003063 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003064 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07003065};
3066
3067}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003068
3069int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003070 if (argc < 2) {
3071 ALOGE("A directory must be specified!");
3072 return 1;
3073 }
3074 if (chdir(argv[1]) == -1) {
3075 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3076 return 1;
3077 }
3078
3079 Entropy entropy;
3080 if (!entropy.open()) {
3081 return 1;
3082 }
Kenny Root70e3a862012-02-15 17:20:23 -08003083
Shawn Willdena5bbf2f2015-02-24 09:31:25 -07003084 keymaster0_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003085 if (keymaster_device_initialize(&dev)) {
3086 ALOGE("keystore keymaster could not be initialized; exiting");
3087 return 1;
3088 }
3089
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003090 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003091 if (fallback_keymaster_device_initialize(&fallback)) {
3092 ALOGE("software keymaster could not be initialized; exiting");
3093 return 1;
3094 }
3095
Riley Spahneaabae92014-06-30 12:39:52 -07003096 ks_is_selinux_enabled = is_selinux_enabled();
3097 if (ks_is_selinux_enabled) {
3098 union selinux_callback cb;
3099 cb.func_log = selinux_log_callback;
3100 selinux_set_callback(SELINUX_CB_LOG, cb);
3101 if (getcon(&tctx) != 0) {
3102 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3103 return -1;
3104 }
3105 } else {
3106 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3107 }
3108
Chad Brubaker919cb2a2015-02-05 21:58:25 -08003109 KeyStore keyStore(&entropy, reinterpret_cast<keymaster1_device_t*>(dev), fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003110 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003111 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3112 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3113 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3114 if (ret != android::OK) {
3115 ALOGE("Couldn't register binder service!");
3116 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003117 }
Kenny Root07438c82012-11-02 15:41:02 -07003118
3119 /*
3120 * We're the only thread in existence, so we're just going to process
3121 * Binder transaction as a single-threaded program.
3122 */
3123 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003124
3125 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003126 return 1;
3127}