blob: ae3b1e4add3a6ab937d2427eb4fd1b9ee666e6df [file] [log] [blame]
Kenny Roota91203b2012-02-15 15:00:46 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Kenny Root07438c82012-11-02 15:41:02 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "keystore"
19
Kenny Roota91203b2012-02-15 15:00:46 -080020#include <stdio.h>
21#include <stdint.h>
22#include <string.h>
Elliott Hughesaaf98022015-01-25 08:40:44 -080023#include <strings.h>
Kenny Roota91203b2012-02-15 15:00:46 -080024#include <unistd.h>
25#include <signal.h>
26#include <errno.h>
27#include <dirent.h>
Kenny Root655b9582013-04-04 08:37:42 -070028#include <errno.h>
Kenny Roota91203b2012-02-15 15:00:46 -080029#include <fcntl.h>
30#include <limits.h>
Kenny Root822c3a92012-03-23 16:34:39 -070031#include <assert.h>
Kenny Roota91203b2012-02-15 15:00:46 -080032#include <sys/types.h>
33#include <sys/socket.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <arpa/inet.h>
37
38#include <openssl/aes.h>
Kenny Root822c3a92012-03-23 16:34:39 -070039#include <openssl/bio.h>
Kenny Roota91203b2012-02-15 15:00:46 -080040#include <openssl/evp.h>
41#include <openssl/md5.h>
Kenny Root822c3a92012-03-23 16:34:39 -070042#include <openssl/pem.h>
Kenny Roota91203b2012-02-15 15:00:46 -080043
Shawn Willden80843db2015-02-24 09:31:25 -070044#include <hardware/keymaster0.h>
Kenny Root70e3a862012-02-15 17:20:23 -080045
Chad Brubaker67d2a502015-03-11 17:21:18 +000046#include <keymaster/soft_keymaster_device.h>
Shawn Willden04006752015-04-30 11:12:33 -060047#include <keymaster/soft_keymaster_logger.h>
48#include <keymaster/softkeymaster.h>
Kenny Root17208e02013-09-04 13:56:03 -070049
Kenny Root26cfc082013-09-11 14:38:56 -070050#include <UniquePtr.h>
Kenny Root655b9582013-04-04 08:37:42 -070051#include <utils/String8.h>
Kenny Root655b9582013-04-04 08:37:42 -070052#include <utils/Vector.h>
Kenny Root70e3a862012-02-15 17:20:23 -080053
Kenny Root07438c82012-11-02 15:41:02 -070054#include <keystore/IKeystoreService.h>
55#include <binder/IPCThreadState.h>
56#include <binder/IServiceManager.h>
57
Kenny Roota91203b2012-02-15 15:00:46 -080058#include <cutils/log.h>
59#include <cutils/sockets.h>
60#include <private/android_filesystem_config.h>
61
Kenny Root07438c82012-11-02 15:41:02 -070062#include <keystore/keystore.h>
Kenny Roota91203b2012-02-15 15:00:46 -080063
Riley Spahneaabae92014-06-30 12:39:52 -070064#include <selinux/android.h>
65
Chad Brubaker3a7d9e62015-06-04 15:01:46 -070066#include <sstream>
67
Chad Brubakerd80c7b42015-03-31 11:04:28 -070068#include "auth_token_table.h"
Kenny Root96427ba2013-08-16 14:02:41 -070069#include "defaults.h"
Chad Brubaker40a1a9b2015-02-20 14:08:13 -080070#include "operation.h"
Kenny Root96427ba2013-08-16 14:02:41 -070071
Kenny Roota91203b2012-02-15 15:00:46 -080072/* KeyStore is a secured storage for key-value pairs. In this implementation,
73 * each file stores one key-value pair. Keys are encoded in file names, and
74 * values are encrypted with checksums. The encryption key is protected by a
75 * user-defined password. To keep things simple, buffers are always larger than
76 * the maximum space we needed, so boundary checks on buffers are omitted. */
77
78#define KEY_SIZE ((NAME_MAX - 15) / 2)
79#define VALUE_SIZE 32768
80#define PASSWORD_SIZE VALUE_SIZE
81
Kenny Root822c3a92012-03-23 16:34:39 -070082
Kenny Root96427ba2013-08-16 14:02:41 -070083struct BIGNUM_Delete {
84 void operator()(BIGNUM* p) const {
85 BN_free(p);
86 }
87};
88typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
89
Kenny Root822c3a92012-03-23 16:34:39 -070090struct BIO_Delete {
91 void operator()(BIO* p) const {
92 BIO_free(p);
93 }
94};
95typedef UniquePtr<BIO, BIO_Delete> Unique_BIO;
96
97struct EVP_PKEY_Delete {
98 void operator()(EVP_PKEY* p) const {
99 EVP_PKEY_free(p);
100 }
101};
102typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
103
104struct PKCS8_PRIV_KEY_INFO_Delete {
105 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
106 PKCS8_PRIV_KEY_INFO_free(p);
107 }
108};
109typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
110
Chad Brubakerbd07a232015-06-01 10:44:27 -0700111static int keymaster_device_initialize(keymaster1_device_t** dev) {
Kenny Root70e3a862012-02-15 17:20:23 -0800112 int rc;
113
114 const hw_module_t* mod;
Chad Brubakerbd07a232015-06-01 10:44:27 -0700115 keymaster::SoftKeymasterDevice* softkeymaster = NULL;
Kenny Root70e3a862012-02-15 17:20:23 -0800116 rc = hw_get_module_by_class(KEYSTORE_HARDWARE_MODULE_ID, NULL, &mod);
117 if (rc) {
118 ALOGE("could not find any keystore module");
119 goto out;
120 }
121
Chad Brubakerbd07a232015-06-01 10:44:27 -0700122 rc = mod->methods->open(mod, KEYSTORE_KEYMASTER, reinterpret_cast<struct hw_device_t**>(dev));
Kenny Root70e3a862012-02-15 17:20:23 -0800123 if (rc) {
124 ALOGE("could not open keymaster device in %s (%s)",
125 KEYSTORE_HARDWARE_MODULE_ID, strerror(-rc));
126 goto out;
127 }
128
Chad Brubakerbd07a232015-06-01 10:44:27 -0700129 // Wrap older hardware modules with a softkeymaster adapter.
130 if ((*dev)->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0) {
131 return 0;
132 }
133 softkeymaster =
134 new keymaster::SoftKeymasterDevice(reinterpret_cast<keymaster0_device_t*>(*dev));
135 *dev = softkeymaster->keymaster_device();
Kenny Root70e3a862012-02-15 17:20:23 -0800136 return 0;
137
138out:
139 *dev = NULL;
140 return rc;
141}
142
Shawn Willden04006752015-04-30 11:12:33 -0600143// softkeymaster_logger appears not to be used in keystore, but it installs itself as the
144// logger used by SoftKeymasterDevice.
145static keymaster::SoftKeymasterLogger softkeymaster_logger;
146
Chad Brubaker67d2a502015-03-11 17:21:18 +0000147static int fallback_keymaster_device_initialize(keymaster1_device_t** dev) {
148 keymaster::SoftKeymasterDevice* softkeymaster =
149 new keymaster::SoftKeymasterDevice();
Shawn Willden9fd05a92015-04-30 11:01:19 -0600150 *dev = softkeymaster->keymaster_device();
151 // softkeymaster will be freed by *dev->close_device; don't delete here.
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800152 return 0;
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800153}
154
Chad Brubakerbd07a232015-06-01 10:44:27 -0700155static void keymaster_device_release(keymaster1_device_t* dev) {
156 dev->common.close(&dev->common);
Kenny Root70e3a862012-02-15 17:20:23 -0800157}
158
Kenny Root07438c82012-11-02 15:41:02 -0700159/***************
160 * PERMISSIONS *
161 ***************/
162
163/* Here are the permissions, actions, users, and the main function. */
164typedef enum {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700165 P_GET_STATE = 1 << 0,
Robin Lee4e865752014-08-19 17:37:55 +0100166 P_GET = 1 << 1,
167 P_INSERT = 1 << 2,
168 P_DELETE = 1 << 3,
169 P_EXIST = 1 << 4,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700170 P_LIST = 1 << 5,
Robin Lee4e865752014-08-19 17:37:55 +0100171 P_RESET = 1 << 6,
172 P_PASSWORD = 1 << 7,
173 P_LOCK = 1 << 8,
174 P_UNLOCK = 1 << 9,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700175 P_IS_EMPTY = 1 << 10,
Robin Lee4e865752014-08-19 17:37:55 +0100176 P_SIGN = 1 << 11,
177 P_VERIFY = 1 << 12,
178 P_GRANT = 1 << 13,
179 P_DUPLICATE = 1 << 14,
180 P_CLEAR_UID = 1 << 15,
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700181 P_ADD_AUTH = 1 << 16,
182 P_USER_CHANGED = 1 << 17,
Kenny Root07438c82012-11-02 15:41:02 -0700183} perm_t;
184
185static struct user_euid {
186 uid_t uid;
187 uid_t euid;
188} user_euids[] = {
189 {AID_VPN, AID_SYSTEM},
190 {AID_WIFI, AID_SYSTEM},
191 {AID_ROOT, AID_SYSTEM},
192};
193
Riley Spahneaabae92014-06-30 12:39:52 -0700194/* perm_labels associcated with keystore_key SELinux class verbs. */
195const char *perm_labels[] = {
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700196 "get_state",
Riley Spahneaabae92014-06-30 12:39:52 -0700197 "get",
198 "insert",
199 "delete",
200 "exist",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700201 "list",
Riley Spahneaabae92014-06-30 12:39:52 -0700202 "reset",
203 "password",
204 "lock",
205 "unlock",
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700206 "is_empty",
Riley Spahneaabae92014-06-30 12:39:52 -0700207 "sign",
208 "verify",
209 "grant",
210 "duplicate",
Robin Lee4e865752014-08-19 17:37:55 +0100211 "clear_uid",
Chad Brubakerd80c7b42015-03-31 11:04:28 -0700212 "add_auth",
Chad Brubakerc0f031a2015-05-12 10:43:10 -0700213 "user_changed",
Riley Spahneaabae92014-06-30 12:39:52 -0700214};
215
Kenny Root07438c82012-11-02 15:41:02 -0700216static struct user_perm {
217 uid_t uid;
218 perm_t perms;
219} user_perms[] = {
220 {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0)) },
221 {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
222 {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY) },
223 {AID_ROOT, static_cast<perm_t>(P_GET) },
224};
225
Chad Brubakere6c3bfa2015-05-12 15:18:26 -0700226static const perm_t DEFAULT_PERMS = static_cast<perm_t>(P_GET_STATE | P_GET | P_INSERT | P_DELETE
227 | P_EXIST | P_LIST | P_SIGN | P_VERIFY);
Kenny Root07438c82012-11-02 15:41:02 -0700228
Riley Spahneaabae92014-06-30 12:39:52 -0700229static char *tctx;
230static int ks_is_selinux_enabled;
231
232static const char *get_perm_label(perm_t perm) {
233 unsigned int index = ffs(perm);
234 if (index > 0 && index <= (sizeof(perm_labels) / sizeof(perm_labels[0]))) {
235 return perm_labels[index - 1];
236 } else {
237 ALOGE("Keystore: Failed to retrieve permission label.\n");
238 abort();
239 }
240}
241
Kenny Root655b9582013-04-04 08:37:42 -0700242/**
243 * Returns the app ID (in the Android multi-user sense) for the current
244 * UNIX UID.
245 */
246static uid_t get_app_id(uid_t uid) {
247 return uid % AID_USER;
248}
249
250/**
251 * Returns the user ID (in the Android multi-user sense) for the current
252 * UNIX UID.
253 */
254static uid_t get_user_id(uid_t uid) {
255 return uid / AID_USER;
256}
257
Chih-Hung Hsieha25b2a32014-09-03 12:14:45 -0700258static bool keystore_selinux_check_access(uid_t /*uid*/, perm_t perm, pid_t spid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700259 if (!ks_is_selinux_enabled) {
260 return true;
261 }
Nick Kralevich66dbf672014-06-30 17:09:14 +0000262
Riley Spahneaabae92014-06-30 12:39:52 -0700263 char *sctx = NULL;
264 const char *selinux_class = "keystore_key";
265 const char *str_perm = get_perm_label(perm);
266
267 if (!str_perm) {
268 return false;
269 }
270
271 if (getpidcon(spid, &sctx) != 0) {
272 ALOGE("SELinux: Failed to get source pid context.\n");
273 return false;
274 }
275
276 bool allowed = selinux_check_access(sctx, tctx, selinux_class, str_perm,
277 NULL) == 0;
278 freecon(sctx);
279 return allowed;
280}
281
282static bool has_permission(uid_t uid, perm_t perm, pid_t spid) {
Kenny Root655b9582013-04-04 08:37:42 -0700283 // All system users are equivalent for multi-user support.
284 if (get_app_id(uid) == AID_SYSTEM) {
285 uid = AID_SYSTEM;
286 }
287
Kenny Root07438c82012-11-02 15:41:02 -0700288 for (size_t i = 0; i < sizeof(user_perms)/sizeof(user_perms[0]); i++) {
289 struct user_perm user = user_perms[i];
290 if (user.uid == uid) {
Riley Spahneaabae92014-06-30 12:39:52 -0700291 return (user.perms & perm) &&
292 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700293 }
294 }
295
Riley Spahneaabae92014-06-30 12:39:52 -0700296 return (DEFAULT_PERMS & perm) &&
297 keystore_selinux_check_access(uid, perm, spid);
Kenny Root07438c82012-11-02 15:41:02 -0700298}
299
Kenny Root49468902013-03-19 13:41:33 -0700300/**
301 * Returns the UID that the callingUid should act as. This is here for
302 * legacy support of the WiFi and VPN systems and should be removed
303 * when WiFi can operate in its own namespace.
304 */
Kenny Root07438c82012-11-02 15:41:02 -0700305static uid_t get_keystore_euid(uid_t uid) {
306 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
307 struct user_euid user = user_euids[i];
308 if (user.uid == uid) {
309 return user.euid;
310 }
311 }
312
313 return uid;
314}
315
Kenny Root49468902013-03-19 13:41:33 -0700316/**
317 * Returns true if the callingUid is allowed to interact in the targetUid's
318 * namespace.
319 */
320static bool is_granted_to(uid_t callingUid, uid_t targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -0700321 if (callingUid == targetUid) {
322 return true;
323 }
Kenny Root49468902013-03-19 13:41:33 -0700324 for (size_t i = 0; i < sizeof(user_euids)/sizeof(user_euids[0]); i++) {
325 struct user_euid user = user_euids[i];
326 if (user.euid == callingUid && user.uid == targetUid) {
327 return true;
328 }
329 }
330
331 return false;
332}
333
Kenny Roota91203b2012-02-15 15:00:46 -0800334/* Here is the encoding of keys. This is necessary in order to allow arbitrary
335 * characters in keys. Characters in [0-~] are not encoded. Others are encoded
336 * into two bytes. The first byte is one of [+-.] which represents the first
337 * two bits of the character. The second byte encodes the rest of the bits into
338 * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
339 * that Base64 cannot be used here due to the need of prefix match on keys. */
340
Kenny Root655b9582013-04-04 08:37:42 -0700341static size_t encode_key_length(const android::String8& keyName) {
342 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
343 size_t length = keyName.length();
344 for (int i = length; i > 0; --i, ++in) {
345 if (*in < '0' || *in > '~') {
346 ++length;
347 }
348 }
349 return length;
350}
351
Kenny Root07438c82012-11-02 15:41:02 -0700352static int encode_key(char* out, const android::String8& keyName) {
353 const uint8_t* in = reinterpret_cast<const uint8_t*>(keyName.string());
354 size_t length = keyName.length();
Kenny Roota91203b2012-02-15 15:00:46 -0800355 for (int i = length; i > 0; --i, ++in, ++out) {
Kenny Root655b9582013-04-04 08:37:42 -0700356 if (*in < '0' || *in > '~') {
Kenny Roota91203b2012-02-15 15:00:46 -0800357 *out = '+' + (*in >> 6);
358 *++out = '0' + (*in & 0x3F);
359 ++length;
Kenny Root655b9582013-04-04 08:37:42 -0700360 } else {
361 *out = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800362 }
363 }
364 *out = '\0';
Kenny Root70e3a862012-02-15 17:20:23 -0800365 return length;
366}
367
Kenny Root07438c82012-11-02 15:41:02 -0700368/*
369 * Converts from the "escaped" format on disk to actual name.
370 * This will be smaller than the input string.
371 *
372 * Characters that should combine with the next at the end will be truncated.
373 */
374static size_t decode_key_length(const char* in, size_t length) {
375 size_t outLength = 0;
376
377 for (const char* end = in + length; in < end; in++) {
378 /* This combines with the next character. */
379 if (*in < '0' || *in > '~') {
380 continue;
381 }
382
383 outLength++;
384 }
385 return outLength;
386}
387
388static void decode_key(char* out, const char* in, size_t length) {
389 for (const char* end = in + length; in < end; in++) {
390 if (*in < '0' || *in > '~') {
391 /* Truncate combining characters at the end. */
392 if (in + 1 >= end) {
393 break;
394 }
395
396 *out = (*in++ - '+') << 6;
397 *out++ |= (*in - '0') & 0x3F;
Kenny Roota91203b2012-02-15 15:00:46 -0800398 } else {
Kenny Root07438c82012-11-02 15:41:02 -0700399 *out++ = *in;
Kenny Roota91203b2012-02-15 15:00:46 -0800400 }
401 }
402 *out = '\0';
Kenny Roota91203b2012-02-15 15:00:46 -0800403}
404
405static size_t readFully(int fd, uint8_t* data, size_t size) {
406 size_t remaining = size;
407 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800408 ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
Kenny Root5281edb2012-11-21 15:14:04 -0800409 if (n <= 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800410 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800411 }
412 data += n;
413 remaining -= n;
414 }
415 return size;
416}
417
418static size_t writeFully(int fd, uint8_t* data, size_t size) {
419 size_t remaining = size;
420 while (remaining > 0) {
Kenny Root150ca932012-11-14 14:29:02 -0800421 ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
422 if (n < 0) {
423 ALOGW("write failed: %s", strerror(errno));
424 return size - remaining;
Kenny Roota91203b2012-02-15 15:00:46 -0800425 }
426 data += n;
427 remaining -= n;
428 }
429 return size;
430}
431
432class Entropy {
433public:
434 Entropy() : mRandom(-1) {}
435 ~Entropy() {
Kenny Root150ca932012-11-14 14:29:02 -0800436 if (mRandom >= 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800437 close(mRandom);
438 }
439 }
440
441 bool open() {
442 const char* randomDevice = "/dev/urandom";
Kenny Root150ca932012-11-14 14:29:02 -0800443 mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
444 if (mRandom < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800445 ALOGE("open: %s: %s", randomDevice, strerror(errno));
446 return false;
447 }
448 return true;
449 }
450
Kenny Root51878182012-03-13 12:53:19 -0700451 bool generate_random_data(uint8_t* data, size_t size) const {
Kenny Roota91203b2012-02-15 15:00:46 -0800452 return (readFully(mRandom, data, size) == size);
453 }
454
455private:
456 int mRandom;
457};
458
459/* Here is the file format. There are two parts in blob.value, the secret and
460 * the description. The secret is stored in ciphertext, and its original size
461 * can be found in blob.length. The description is stored after the secret in
462 * plaintext, and its size is specified in blob.info. The total size of the two
Kenny Root822c3a92012-03-23 16:34:39 -0700463 * parts must be no more than VALUE_SIZE bytes. The first field is the version,
Kenny Rootf9119d62013-04-03 09:22:15 -0700464 * the second is the blob's type, and the third byte is flags. Fields other
Kenny Roota91203b2012-02-15 15:00:46 -0800465 * than blob.info, blob.length, and blob.value are modified by encryptBlob()
466 * and decryptBlob(). Thus they should not be accessed from outside. */
467
Kenny Root822c3a92012-03-23 16:34:39 -0700468/* ** Note to future implementors of encryption: **
469 * Currently this is the construction:
470 * metadata || Enc(MD5(data) || data)
471 *
472 * This should be the construction used for encrypting if re-implementing:
473 *
474 * Derive independent keys for encryption and MAC:
475 * Kenc = AES_encrypt(masterKey, "Encrypt")
476 * Kmac = AES_encrypt(masterKey, "MAC")
477 *
478 * Store this:
479 * metadata || AES_CTR_encrypt(Kenc, rand_IV, data) ||
480 * HMAC(Kmac, metadata || Enc(data))
481 */
Kenny Roota91203b2012-02-15 15:00:46 -0800482struct __attribute__((packed)) blob {
Kenny Root822c3a92012-03-23 16:34:39 -0700483 uint8_t version;
484 uint8_t type;
Kenny Rootf9119d62013-04-03 09:22:15 -0700485 uint8_t flags;
Kenny Roota91203b2012-02-15 15:00:46 -0800486 uint8_t info;
487 uint8_t vector[AES_BLOCK_SIZE];
Kenny Root822c3a92012-03-23 16:34:39 -0700488 uint8_t encrypted[0]; // Marks offset to encrypted data.
Kenny Roota91203b2012-02-15 15:00:46 -0800489 uint8_t digest[MD5_DIGEST_LENGTH];
Kenny Root822c3a92012-03-23 16:34:39 -0700490 uint8_t digested[0]; // Marks offset to digested data.
Kenny Roota91203b2012-02-15 15:00:46 -0800491 int32_t length; // in network byte order when encrypted
492 uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
493};
494
Kenny Root822c3a92012-03-23 16:34:39 -0700495typedef enum {
Kenny Rootd53bc922013-03-21 14:10:15 -0700496 TYPE_ANY = 0, // meta type that matches anything
Kenny Root822c3a92012-03-23 16:34:39 -0700497 TYPE_GENERIC = 1,
498 TYPE_MASTER_KEY = 2,
499 TYPE_KEY_PAIR = 3,
Chad Brubaker17d68b92015-02-05 22:04:16 -0800500 TYPE_KEYMASTER_10 = 4,
Kenny Root822c3a92012-03-23 16:34:39 -0700501} BlobType;
502
Kenny Rootf9119d62013-04-03 09:22:15 -0700503static const uint8_t CURRENT_BLOB_VERSION = 2;
Kenny Root822c3a92012-03-23 16:34:39 -0700504
Kenny Roota91203b2012-02-15 15:00:46 -0800505class Blob {
506public:
Kenny Root07438c82012-11-02 15:41:02 -0700507 Blob(const uint8_t* value, int32_t valueLength, const uint8_t* info, uint8_t infoLength,
508 BlobType type) {
Alex Klyubin1773b442015-02-20 12:33:33 -0800509 memset(&mBlob, 0, sizeof(mBlob));
Kenny Roota91203b2012-02-15 15:00:46 -0800510 mBlob.length = valueLength;
511 memcpy(mBlob.value, value, valueLength);
512
513 mBlob.info = infoLength;
514 memcpy(mBlob.value + valueLength, info, infoLength);
Kenny Root822c3a92012-03-23 16:34:39 -0700515
Kenny Root07438c82012-11-02 15:41:02 -0700516 mBlob.version = CURRENT_BLOB_VERSION;
Kenny Root822c3a92012-03-23 16:34:39 -0700517 mBlob.type = uint8_t(type);
Kenny Rootf9119d62013-04-03 09:22:15 -0700518
Kenny Rootee8068b2013-10-07 09:49:15 -0700519 if (type == TYPE_MASTER_KEY) {
520 mBlob.flags = KEYSTORE_FLAG_ENCRYPTED;
521 } else {
522 mBlob.flags = KEYSTORE_FLAG_NONE;
523 }
Kenny Roota91203b2012-02-15 15:00:46 -0800524 }
525
526 Blob(blob b) {
527 mBlob = b;
528 }
529
Alex Klyubin1773b442015-02-20 12:33:33 -0800530 Blob() {
531 memset(&mBlob, 0, sizeof(mBlob));
532 }
Kenny Roota91203b2012-02-15 15:00:46 -0800533
Kenny Root51878182012-03-13 12:53:19 -0700534 const uint8_t* getValue() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800535 return mBlob.value;
536 }
537
Kenny Root51878182012-03-13 12:53:19 -0700538 int32_t getLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800539 return mBlob.length;
540 }
541
Kenny Root51878182012-03-13 12:53:19 -0700542 const uint8_t* getInfo() const {
543 return mBlob.value + mBlob.length;
544 }
545
546 uint8_t getInfoLength() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800547 return mBlob.info;
548 }
549
Kenny Root822c3a92012-03-23 16:34:39 -0700550 uint8_t getVersion() const {
551 return mBlob.version;
552 }
553
Kenny Rootf9119d62013-04-03 09:22:15 -0700554 bool isEncrypted() const {
555 if (mBlob.version < 2) {
556 return true;
557 }
558
559 return mBlob.flags & KEYSTORE_FLAG_ENCRYPTED;
560 }
561
562 void setEncrypted(bool encrypted) {
563 if (encrypted) {
564 mBlob.flags |= KEYSTORE_FLAG_ENCRYPTED;
565 } else {
566 mBlob.flags &= ~KEYSTORE_FLAG_ENCRYPTED;
567 }
568 }
569
Kenny Root17208e02013-09-04 13:56:03 -0700570 bool isFallback() const {
571 return mBlob.flags & KEYSTORE_FLAG_FALLBACK;
572 }
573
574 void setFallback(bool fallback) {
575 if (fallback) {
576 mBlob.flags |= KEYSTORE_FLAG_FALLBACK;
577 } else {
578 mBlob.flags &= ~KEYSTORE_FLAG_FALLBACK;
579 }
580 }
581
Kenny Root822c3a92012-03-23 16:34:39 -0700582 void setVersion(uint8_t version) {
583 mBlob.version = version;
584 }
585
586 BlobType getType() const {
587 return BlobType(mBlob.type);
588 }
589
590 void setType(BlobType type) {
591 mBlob.type = uint8_t(type);
592 }
593
Kenny Rootf9119d62013-04-03 09:22:15 -0700594 ResponseCode writeBlob(const char* filename, AES_KEY *aes_key, State state, Entropy* entropy) {
595 ALOGV("writing blob %s", filename);
596 if (isEncrypted()) {
597 if (state != STATE_NO_ERROR) {
598 ALOGD("couldn't insert encrypted blob while not unlocked");
599 return LOCKED;
600 }
601
602 if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
603 ALOGW("Could not read random data for: %s", filename);
604 return SYSTEM_ERROR;
605 }
Kenny Roota91203b2012-02-15 15:00:46 -0800606 }
607
608 // data includes the value and the value's length
609 size_t dataLength = mBlob.length + sizeof(mBlob.length);
610 // pad data to the AES_BLOCK_SIZE
611 size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
612 / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
613 // encrypted data includes the digest value
614 size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
615 // move info after space for padding
616 memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
617 // zero padding area
618 memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
619
620 mBlob.length = htonl(mBlob.length);
Kenny Roota91203b2012-02-15 15:00:46 -0800621
Kenny Rootf9119d62013-04-03 09:22:15 -0700622 if (isEncrypted()) {
623 MD5(mBlob.digested, digestedLength, mBlob.digest);
Kenny Roota91203b2012-02-15 15:00:46 -0800624
Kenny Rootf9119d62013-04-03 09:22:15 -0700625 uint8_t vector[AES_BLOCK_SIZE];
626 memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
627 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
628 aes_key, vector, AES_ENCRYPT);
629 }
630
Kenny Roota91203b2012-02-15 15:00:46 -0800631 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
632 size_t fileLength = encryptedLength + headerLength + mBlob.info;
633
634 const char* tmpFileName = ".tmp";
Kenny Root150ca932012-11-14 14:29:02 -0800635 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
636 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
637 if (out < 0) {
638 ALOGW("could not open file: %s: %s", tmpFileName, strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800639 return SYSTEM_ERROR;
640 }
641 size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
642 if (close(out) != 0) {
643 return SYSTEM_ERROR;
644 }
645 if (writtenBytes != fileLength) {
Kenny Root150ca932012-11-14 14:29:02 -0800646 ALOGW("blob not fully written %zu != %zu", writtenBytes, fileLength);
Kenny Roota91203b2012-02-15 15:00:46 -0800647 unlink(tmpFileName);
648 return SYSTEM_ERROR;
649 }
Kenny Root150ca932012-11-14 14:29:02 -0800650 if (rename(tmpFileName, filename) == -1) {
651 ALOGW("could not rename blob to %s: %s", filename, strerror(errno));
652 return SYSTEM_ERROR;
653 }
654 return NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800655 }
656
Kenny Rootf9119d62013-04-03 09:22:15 -0700657 ResponseCode readBlob(const char* filename, AES_KEY *aes_key, State state) {
658 ALOGV("reading blob %s", filename);
Kenny Root150ca932012-11-14 14:29:02 -0800659 int in = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
660 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800661 return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
662 }
663 // fileLength may be less than sizeof(mBlob) since the in
664 // memory version has extra padding to tolerate rounding up to
665 // the AES_BLOCK_SIZE
666 size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
667 if (close(in) != 0) {
668 return SYSTEM_ERROR;
669 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700670
671 if (isEncrypted() && (state != STATE_NO_ERROR)) {
672 return LOCKED;
673 }
674
Kenny Roota91203b2012-02-15 15:00:46 -0800675 size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
676 if (fileLength < headerLength) {
677 return VALUE_CORRUPTED;
678 }
679
680 ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
Kenny Rootf9119d62013-04-03 09:22:15 -0700681 if (encryptedLength < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800682 return VALUE_CORRUPTED;
683 }
Kenny Rootf9119d62013-04-03 09:22:15 -0700684
685 ssize_t digestedLength;
686 if (isEncrypted()) {
687 if (encryptedLength % AES_BLOCK_SIZE != 0) {
688 return VALUE_CORRUPTED;
689 }
690
691 AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
692 mBlob.vector, AES_DECRYPT);
693 digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
694 uint8_t computedDigest[MD5_DIGEST_LENGTH];
695 MD5(mBlob.digested, digestedLength, computedDigest);
696 if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
697 return VALUE_CORRUPTED;
698 }
699 } else {
700 digestedLength = encryptedLength;
Kenny Roota91203b2012-02-15 15:00:46 -0800701 }
702
703 ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
704 mBlob.length = ntohl(mBlob.length);
705 if (mBlob.length < 0 || mBlob.length > maxValueLength) {
706 return VALUE_CORRUPTED;
707 }
708 if (mBlob.info != 0) {
709 // move info from after padding to after data
710 memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
711 }
Kenny Root07438c82012-11-02 15:41:02 -0700712 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800713 }
714
715private:
716 struct blob mBlob;
717};
718
Kenny Root655b9582013-04-04 08:37:42 -0700719class UserState {
Kenny Roota91203b2012-02-15 15:00:46 -0800720public:
Kenny Root655b9582013-04-04 08:37:42 -0700721 UserState(uid_t userId) : mUserId(userId), mRetry(MAX_RETRY) {
722 asprintf(&mUserDir, "user_%u", mUserId);
723 asprintf(&mMasterKeyFile, "%s/.masterkey", mUserDir);
724 }
725
726 ~UserState() {
727 free(mUserDir);
728 free(mMasterKeyFile);
729 }
730
731 bool initialize() {
732 if ((mkdir(mUserDir, S_IRUSR | S_IWUSR | S_IXUSR) < 0) && (errno != EEXIST)) {
733 ALOGE("Could not create directory '%s'", mUserDir);
734 return false;
735 }
736
737 if (access(mMasterKeyFile, R_OK) == 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800738 setState(STATE_LOCKED);
739 } else {
740 setState(STATE_UNINITIALIZED);
741 }
Kenny Root70e3a862012-02-15 17:20:23 -0800742
Kenny Root655b9582013-04-04 08:37:42 -0700743 return true;
744 }
745
746 uid_t getUserId() const {
747 return mUserId;
748 }
749
750 const char* getUserDirName() const {
751 return mUserDir;
752 }
753
754 const char* getMasterKeyFileName() const {
755 return mMasterKeyFile;
756 }
757
758 void setState(State state) {
759 mState = state;
760 if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
761 mRetry = MAX_RETRY;
762 }
Kenny Roota91203b2012-02-15 15:00:46 -0800763 }
764
Kenny Root51878182012-03-13 12:53:19 -0700765 State getState() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800766 return mState;
767 }
768
Kenny Root51878182012-03-13 12:53:19 -0700769 int8_t getRetry() const {
Kenny Roota91203b2012-02-15 15:00:46 -0800770 return mRetry;
771 }
772
Kenny Root655b9582013-04-04 08:37:42 -0700773 void zeroizeMasterKeysInMemory() {
774 memset(mMasterKey, 0, sizeof(mMasterKey));
775 memset(mSalt, 0, sizeof(mSalt));
776 memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
777 memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
Kenny Root70e3a862012-02-15 17:20:23 -0800778 }
779
Chad Brubaker96d6d782015-05-07 10:19:40 -0700780 bool deleteMasterKey() {
781 setState(STATE_UNINITIALIZED);
782 zeroizeMasterKeysInMemory();
783 return unlink(mMasterKeyFile) == 0 || errno == ENOENT;
784 }
785
Kenny Root655b9582013-04-04 08:37:42 -0700786 ResponseCode initialize(const android::String8& pw, Entropy* entropy) {
787 if (!generateMasterKey(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800788 return SYSTEM_ERROR;
789 }
Kenny Root655b9582013-04-04 08:37:42 -0700790 ResponseCode response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800791 if (response != NO_ERROR) {
792 return response;
793 }
794 setupMasterKeys();
Kenny Root07438c82012-11-02 15:41:02 -0700795 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -0800796 }
797
Robin Lee4e865752014-08-19 17:37:55 +0100798 ResponseCode copyMasterKey(UserState* src) {
799 if (mState != STATE_UNINITIALIZED) {
800 return ::SYSTEM_ERROR;
801 }
802 if (src->getState() != STATE_NO_ERROR) {
803 return ::SYSTEM_ERROR;
804 }
805 memcpy(mMasterKey, src->mMasterKey, MASTER_KEY_SIZE_BYTES);
806 setupMasterKeys();
807 return ::NO_ERROR;
808 }
809
Kenny Root655b9582013-04-04 08:37:42 -0700810 ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy) {
Kenny Roota91203b2012-02-15 15:00:46 -0800811 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
812 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
813 AES_KEY passwordAesKey;
814 AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
Kenny Root822c3a92012-03-23 16:34:39 -0700815 Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
Kenny Rootf9119d62013-04-03 09:22:15 -0700816 return masterKeyBlob.writeBlob(mMasterKeyFile, &passwordAesKey, STATE_NO_ERROR, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800817 }
818
Kenny Root655b9582013-04-04 08:37:42 -0700819 ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy) {
820 int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
Kenny Root150ca932012-11-14 14:29:02 -0800821 if (in < 0) {
Kenny Roota91203b2012-02-15 15:00:46 -0800822 return SYSTEM_ERROR;
823 }
824
825 // we read the raw blob to just to get the salt to generate
826 // the AES key, then we create the Blob to use with decryptBlob
827 blob rawBlob;
828 size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
829 if (close(in) != 0) {
830 return SYSTEM_ERROR;
831 }
832 // find salt at EOF if present, otherwise we have an old file
833 uint8_t* salt;
834 if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
835 salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
836 } else {
837 salt = NULL;
838 }
839 uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
840 generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
841 AES_KEY passwordAesKey;
842 AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
843 Blob masterKeyBlob(rawBlob);
Kenny Rootf9119d62013-04-03 09:22:15 -0700844 ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, &passwordAesKey,
845 STATE_NO_ERROR);
Kenny Roota91203b2012-02-15 15:00:46 -0800846 if (response == SYSTEM_ERROR) {
Kenny Rootf9119d62013-04-03 09:22:15 -0700847 return response;
Kenny Roota91203b2012-02-15 15:00:46 -0800848 }
849 if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
850 // if salt was missing, generate one and write a new master key file with the salt.
851 if (salt == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -0700852 if (!generateSalt(entropy)) {
Kenny Roota91203b2012-02-15 15:00:46 -0800853 return SYSTEM_ERROR;
854 }
Kenny Root655b9582013-04-04 08:37:42 -0700855 response = writeMasterKey(pw, entropy);
Kenny Roota91203b2012-02-15 15:00:46 -0800856 }
857 if (response == NO_ERROR) {
858 memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
859 setupMasterKeys();
860 }
861 return response;
862 }
863 if (mRetry <= 0) {
864 reset();
865 return UNINITIALIZED;
866 }
867 --mRetry;
868 switch (mRetry) {
869 case 0: return WRONG_PASSWORD_0;
870 case 1: return WRONG_PASSWORD_1;
871 case 2: return WRONG_PASSWORD_2;
872 case 3: return WRONG_PASSWORD_3;
873 default: return WRONG_PASSWORD_3;
874 }
875 }
876
Kenny Root655b9582013-04-04 08:37:42 -0700877 AES_KEY* getEncryptionKey() {
878 return &mMasterKeyEncryption;
879 }
880
881 AES_KEY* getDecryptionKey() {
882 return &mMasterKeyDecryption;
883 }
884
Kenny Roota91203b2012-02-15 15:00:46 -0800885 bool reset() {
Kenny Root655b9582013-04-04 08:37:42 -0700886 DIR* dir = opendir(getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -0800887 if (!dir) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700888 // If the directory doesn't exist then nothing to do.
889 if (errno == ENOENT) {
890 return true;
891 }
Kenny Root655b9582013-04-04 08:37:42 -0700892 ALOGW("couldn't open user directory: %s", strerror(errno));
Kenny Roota91203b2012-02-15 15:00:46 -0800893 return false;
894 }
Kenny Root655b9582013-04-04 08:37:42 -0700895
896 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -0800897 while ((file = readdir(dir)) != NULL) {
Chad Brubaker96d6d782015-05-07 10:19:40 -0700898 // skip . and ..
899 if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
Kenny Root655b9582013-04-04 08:37:42 -0700900 continue;
901 }
902
903 unlinkat(dirfd(dir), file->d_name, 0);
Kenny Roota91203b2012-02-15 15:00:46 -0800904 }
905 closedir(dir);
906 return true;
907 }
908
Kenny Root655b9582013-04-04 08:37:42 -0700909private:
910 static const int MASTER_KEY_SIZE_BYTES = 16;
911 static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
912
913 static const int MAX_RETRY = 4;
914 static const size_t SALT_SIZE = 16;
915
916 void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
917 uint8_t* salt) {
918 size_t saltSize;
919 if (salt != NULL) {
920 saltSize = SALT_SIZE;
921 } else {
922 // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
923 salt = (uint8_t*) "keystore";
924 // sizeof = 9, not strlen = 8
925 saltSize = sizeof("keystore");
926 }
927
928 PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt,
929 saltSize, 8192, keySize, key);
930 }
931
932 bool generateSalt(Entropy* entropy) {
933 return entropy->generate_random_data(mSalt, sizeof(mSalt));
934 }
935
936 bool generateMasterKey(Entropy* entropy) {
937 if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
938 return false;
939 }
940 if (!generateSalt(entropy)) {
941 return false;
942 }
943 return true;
944 }
945
946 void setupMasterKeys() {
947 AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
948 AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
949 setState(STATE_NO_ERROR);
950 }
951
952 uid_t mUserId;
953
954 char* mUserDir;
955 char* mMasterKeyFile;
956
957 State mState;
958 int8_t mRetry;
959
960 uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
961 uint8_t mSalt[SALT_SIZE];
962
963 AES_KEY mMasterKeyEncryption;
964 AES_KEY mMasterKeyDecryption;
965};
966
967typedef struct {
968 uint32_t uid;
969 const uint8_t* filename;
970} grant_t;
971
972class KeyStore {
973public:
Chad Brubaker67d2a502015-03-11 17:21:18 +0000974 KeyStore(Entropy* entropy, keymaster1_device_t* device, keymaster1_device_t* fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700975 : mEntropy(entropy)
976 , mDevice(device)
Chad Brubakerfc18edc2015-01-12 15:17:18 -0800977 , mFallbackDevice(fallback)
Kenny Root655b9582013-04-04 08:37:42 -0700978 {
979 memset(&mMetaData, '\0', sizeof(mMetaData));
980 }
981
982 ~KeyStore() {
983 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
984 it != mGrants.end(); it++) {
985 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700986 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800987 mGrants.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700988
989 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
990 it != mMasterKeys.end(); it++) {
991 delete *it;
Kenny Root655b9582013-04-04 08:37:42 -0700992 }
haitao fangc35d4eb2013-12-06 11:34:49 +0800993 mMasterKeys.clear();
Kenny Root655b9582013-04-04 08:37:42 -0700994 }
995
Chad Brubaker67d2a502015-03-11 17:21:18 +0000996 /**
997 * Depending on the hardware keymaster version is this may return a
998 * keymaster0_device_t* cast to a keymaster1_device_t*. All methods from
999 * keymaster0 are safe to call, calls to keymaster1_device_t methods should
1000 * be guarded by a check on the device's version.
1001 */
1002 keymaster1_device_t *getDevice() const {
Kenny Root655b9582013-04-04 08:37:42 -07001003 return mDevice;
1004 }
1005
Chad Brubaker67d2a502015-03-11 17:21:18 +00001006 keymaster1_device_t *getFallbackDevice() const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001007 return mFallbackDevice;
1008 }
1009
Chad Brubaker67d2a502015-03-11 17:21:18 +00001010 keymaster1_device_t *getDeviceForBlob(const Blob& blob) const {
Chad Brubakerfc18edc2015-01-12 15:17:18 -08001011 return blob.isFallback() ? mFallbackDevice: mDevice;
1012 }
1013
Kenny Root655b9582013-04-04 08:37:42 -07001014 ResponseCode initialize() {
1015 readMetaData();
1016 if (upgradeKeystore()) {
1017 writeMetaData();
1018 }
1019
1020 return ::NO_ERROR;
1021 }
1022
Chad Brubaker72593ee2015-05-12 10:42:00 -07001023 State getState(uid_t userId) {
1024 return getUserState(userId)->getState();
Kenny Root655b9582013-04-04 08:37:42 -07001025 }
1026
Chad Brubaker72593ee2015-05-12 10:42:00 -07001027 ResponseCode initializeUser(const android::String8& pw, uid_t userId) {
1028 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001029 return userState->initialize(pw, mEntropy);
1030 }
1031
Chad Brubaker72593ee2015-05-12 10:42:00 -07001032 ResponseCode copyMasterKey(uid_t srcUser, uid_t dstUser) {
1033 UserState *userState = getUserState(dstUser);
1034 UserState *initState = getUserState(srcUser);
Robin Lee4e865752014-08-19 17:37:55 +01001035 return userState->copyMasterKey(initState);
1036 }
1037
Chad Brubaker72593ee2015-05-12 10:42:00 -07001038 ResponseCode writeMasterKey(const android::String8& pw, uid_t userId) {
1039 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001040 return userState->writeMasterKey(pw, mEntropy);
1041 }
1042
Chad Brubaker72593ee2015-05-12 10:42:00 -07001043 ResponseCode readMasterKey(const android::String8& pw, uid_t userId) {
1044 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001045 return userState->readMasterKey(pw, mEntropy);
1046 }
1047
1048 android::String8 getKeyName(const android::String8& keyName) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001049 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001050 encode_key(encoded, keyName);
1051 return android::String8(encoded);
1052 }
1053
1054 android::String8 getKeyNameForUid(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001055 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001056 encode_key(encoded, keyName);
1057 return android::String8::format("%u_%s", uid, encoded);
1058 }
1059
1060 android::String8 getKeyNameForUidWithDir(const android::String8& keyName, uid_t uid) {
Douglas Leunga77e8092013-06-13 16:34:43 -07001061 char encoded[encode_key_length(keyName) + 1]; // add 1 for null char
Kenny Root655b9582013-04-04 08:37:42 -07001062 encode_key(encoded, keyName);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001063 return android::String8::format("%s/%u_%s", getUserStateByUid(uid)->getUserDirName(), uid,
Kenny Root655b9582013-04-04 08:37:42 -07001064 encoded);
1065 }
1066
Chad Brubaker96d6d782015-05-07 10:19:40 -07001067 /*
1068 * Delete entries owned by userId. If keepUnencryptedEntries is true
1069 * then only encrypted entries will be removed, otherwise all entries will
1070 * be removed.
1071 */
1072 void resetUser(uid_t userId, bool keepUnenryptedEntries) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001073 android::String8 prefix("");
1074 android::Vector<android::String16> aliases;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001075 UserState* userState = getUserState(userId);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001076 if (list(prefix, &aliases, userId) != ::NO_ERROR) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001077 return;
1078 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001079 for (uint32_t i = 0; i < aliases.size(); i++) {
1080 android::String8 filename(aliases[i]);
1081 filename = android::String8::format("%s/%s", userState->getUserDirName(),
Chad Brubaker96d6d782015-05-07 10:19:40 -07001082 getKeyName(filename).string());
1083 bool shouldDelete = true;
1084 if (keepUnenryptedEntries) {
1085 Blob blob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001086 ResponseCode rc = get(filename, &blob, ::TYPE_ANY, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001087
Chad Brubaker96d6d782015-05-07 10:19:40 -07001088 /* get can fail if the blob is encrypted and the state is
1089 * not unlocked, only skip deleting blobs that were loaded and
1090 * who are not encrypted. If there are blobs we fail to read for
1091 * other reasons err on the safe side and delete them since we
1092 * can't tell if they're encrypted.
1093 */
1094 shouldDelete = !(rc == ::NO_ERROR && !blob.isEncrypted());
1095 }
1096 if (shouldDelete) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001097 del(filename, ::TYPE_ANY, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001098 }
1099 }
1100 if (!userState->deleteMasterKey()) {
1101 ALOGE("Failed to delete user %d's master key", userId);
1102 }
1103 if (!keepUnenryptedEntries) {
1104 if(!userState->reset()) {
1105 ALOGE("Failed to remove user %d's directory", userId);
1106 }
1107 }
Kenny Root655b9582013-04-04 08:37:42 -07001108 }
1109
Chad Brubaker72593ee2015-05-12 10:42:00 -07001110 bool isEmpty(uid_t userId) const {
1111 const UserState* userState = getUserState(userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001112 if (userState == NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001113 return true;
1114 }
1115
1116 DIR* dir = opendir(userState->getUserDirName());
Kenny Roota91203b2012-02-15 15:00:46 -08001117 if (!dir) {
1118 return true;
1119 }
Kenny Root31e27462014-09-10 11:28:03 -07001120
Kenny Roota91203b2012-02-15 15:00:46 -08001121 bool result = true;
Kenny Root31e27462014-09-10 11:28:03 -07001122 struct dirent* file;
Kenny Roota91203b2012-02-15 15:00:46 -08001123 while ((file = readdir(dir)) != NULL) {
Kenny Root655b9582013-04-04 08:37:42 -07001124 // We only care about files.
1125 if (file->d_type != DT_REG) {
1126 continue;
1127 }
1128
1129 // Skip anything that starts with a "."
1130 if (file->d_name[0] == '.') {
1131 continue;
1132 }
1133
Kenny Root31e27462014-09-10 11:28:03 -07001134 result = false;
1135 break;
Kenny Roota91203b2012-02-15 15:00:46 -08001136 }
1137 closedir(dir);
1138 return result;
1139 }
1140
Chad Brubaker72593ee2015-05-12 10:42:00 -07001141 void lock(uid_t userId) {
1142 UserState* userState = getUserState(userId);
Kenny Root655b9582013-04-04 08:37:42 -07001143 userState->zeroizeMasterKeysInMemory();
1144 userState->setState(STATE_LOCKED);
Kenny Roota91203b2012-02-15 15:00:46 -08001145 }
1146
Chad Brubaker72593ee2015-05-12 10:42:00 -07001147 ResponseCode get(const char* filename, Blob* keyBlob, const BlobType type, uid_t userId) {
1148 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001149 ResponseCode rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1150 userState->getState());
Kenny Root822c3a92012-03-23 16:34:39 -07001151 if (rc != NO_ERROR) {
1152 return rc;
1153 }
1154
1155 const uint8_t version = keyBlob->getVersion();
Kenny Root07438c82012-11-02 15:41:02 -07001156 if (version < CURRENT_BLOB_VERSION) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001157 /* If we upgrade the key, we need to write it to disk again. Then
1158 * it must be read it again since the blob is encrypted each time
1159 * it's written.
1160 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001161 if (upgradeBlob(filename, keyBlob, version, type, userId)) {
1162 if ((rc = this->put(filename, keyBlob, userId)) != NO_ERROR
Kenny Rootf9119d62013-04-03 09:22:15 -07001163 || (rc = keyBlob->readBlob(filename, userState->getDecryptionKey(),
1164 userState->getState())) != NO_ERROR) {
Kenny Rootcfeae072013-04-04 08:39:57 -07001165 return rc;
1166 }
1167 }
Kenny Root822c3a92012-03-23 16:34:39 -07001168 }
1169
Kenny Root17208e02013-09-04 13:56:03 -07001170 /*
1171 * This will upgrade software-backed keys to hardware-backed keys when
1172 * the HAL for the device supports the newer key types.
1173 */
1174 if (rc == NO_ERROR && type == TYPE_KEY_PAIR
1175 && mDevice->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_0_2
1176 && keyBlob->isFallback()) {
1177 ResponseCode imported = importKey(keyBlob->getValue(), keyBlob->getLength(), filename,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001178 userId, keyBlob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root17208e02013-09-04 13:56:03 -07001179
1180 // The HAL allowed the import, reget the key to have the "fresh"
1181 // version.
1182 if (imported == NO_ERROR) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001183 rc = get(filename, keyBlob, TYPE_KEY_PAIR, userId);
Kenny Root17208e02013-09-04 13:56:03 -07001184 }
1185 }
1186
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001187 // Keymaster 0.3 keys are valid keymaster 1.0 keys, so silently upgrade.
1188 if (keyBlob->getType() == TYPE_KEY_PAIR) {
Chad Brubaker3cc40122015-06-04 13:49:44 -07001189 keyBlob->setType(TYPE_KEYMASTER_10);
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001190 rc = this->put(filename, keyBlob, userId);
Chad Brubaker3cc40122015-06-04 13:49:44 -07001191 }
1192
Kenny Rootd53bc922013-03-21 14:10:15 -07001193 if (type != TYPE_ANY && keyBlob->getType() != type) {
Kenny Root822c3a92012-03-23 16:34:39 -07001194 ALOGW("key found but type doesn't match: %d vs %d", keyBlob->getType(), type);
1195 return KEY_NOT_FOUND;
1196 }
1197
1198 return rc;
Kenny Roota91203b2012-02-15 15:00:46 -08001199 }
1200
Chad Brubaker72593ee2015-05-12 10:42:00 -07001201 ResponseCode put(const char* filename, Blob* keyBlob, uid_t userId) {
1202 UserState* userState = getUserState(userId);
Kenny Rootf9119d62013-04-03 09:22:15 -07001203 return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
1204 mEntropy);
Kenny Roota91203b2012-02-15 15:00:46 -08001205 }
1206
Chad Brubaker72593ee2015-05-12 10:42:00 -07001207 ResponseCode del(const char *filename, const BlobType type, uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001208 Blob keyBlob;
Chad Brubaker72593ee2015-05-12 10:42:00 -07001209 ResponseCode rc = get(filename, &keyBlob, type, userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001210 if (rc != ::NO_ERROR) {
1211 return rc;
1212 }
1213
1214 if (keyBlob.getType() == ::TYPE_KEY_PAIR) {
1215 // A device doesn't have to implement delete_keypair.
1216 if (mDevice->delete_keypair != NULL && !keyBlob.isFallback()) {
1217 if (mDevice->delete_keypair(mDevice, keyBlob.getValue(), keyBlob.getLength())) {
1218 rc = ::SYSTEM_ERROR;
1219 }
1220 }
1221 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08001222 if (keyBlob.getType() == ::TYPE_KEYMASTER_10) {
1223 keymaster1_device_t* dev = getDeviceForBlob(keyBlob);
1224 if (dev->delete_key) {
1225 keymaster_key_blob_t blob;
1226 blob.key_material = keyBlob.getValue();
1227 blob.key_material_size = keyBlob.getLength();
1228 dev->delete_key(dev, &blob);
1229 }
1230 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01001231 if (rc != ::NO_ERROR) {
1232 return rc;
1233 }
1234
1235 return (unlink(filename) && errno != ENOENT) ? ::SYSTEM_ERROR : ::NO_ERROR;
1236 }
1237
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001238 ResponseCode list(const android::String8& prefix, android::Vector<android::String16> *matches,
Chad Brubaker72593ee2015-05-12 10:42:00 -07001239 uid_t userId) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001240
Chad Brubaker72593ee2015-05-12 10:42:00 -07001241 UserState* userState = getUserState(userId);
Robin Lee4b84fdc2014-09-24 11:56:57 +01001242 size_t n = prefix.length();
1243
1244 DIR* dir = opendir(userState->getUserDirName());
1245 if (!dir) {
1246 ALOGW("can't open directory for user: %s", strerror(errno));
1247 return ::SYSTEM_ERROR;
1248 }
1249
1250 struct dirent* file;
1251 while ((file = readdir(dir)) != NULL) {
1252 // We only care about files.
1253 if (file->d_type != DT_REG) {
1254 continue;
1255 }
1256
1257 // Skip anything that starts with a "."
1258 if (file->d_name[0] == '.') {
1259 continue;
1260 }
1261
1262 if (!strncmp(prefix.string(), file->d_name, n)) {
1263 const char* p = &file->d_name[n];
1264 size_t plen = strlen(p);
1265
1266 size_t extra = decode_key_length(p, plen);
1267 char *match = (char*) malloc(extra + 1);
1268 if (match != NULL) {
1269 decode_key(match, p, plen);
1270 matches->push(android::String16(match, extra));
1271 free(match);
1272 } else {
1273 ALOGW("could not allocate match of size %zd", extra);
1274 }
1275 }
1276 }
1277 closedir(dir);
1278 return ::NO_ERROR;
1279 }
1280
Kenny Root07438c82012-11-02 15:41:02 -07001281 void addGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001282 const grant_t* existing = getGrant(filename, granteeUid);
1283 if (existing == NULL) {
1284 grant_t* grant = new grant_t;
Kenny Root07438c82012-11-02 15:41:02 -07001285 grant->uid = granteeUid;
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001286 grant->filename = reinterpret_cast<const uint8_t*>(strdup(filename));
Kenny Root655b9582013-04-04 08:37:42 -07001287 mGrants.add(grant);
Kenny Root70e3a862012-02-15 17:20:23 -08001288 }
1289 }
1290
Kenny Root07438c82012-11-02 15:41:02 -07001291 bool removeGrant(const char* filename, uid_t granteeUid) {
Kenny Root655b9582013-04-04 08:37:42 -07001292 for (android::Vector<grant_t*>::iterator it(mGrants.begin());
1293 it != mGrants.end(); it++) {
1294 grant_t* grant = *it;
1295 if (grant->uid == granteeUid
1296 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
1297 mGrants.erase(it);
1298 return true;
1299 }
Kenny Root70e3a862012-02-15 17:20:23 -08001300 }
Kenny Root70e3a862012-02-15 17:20:23 -08001301 return false;
1302 }
1303
Brian Carlstroma8c703d2012-07-17 14:43:46 -07001304 bool hasGrant(const char* filename, const uid_t uid) const {
1305 return getGrant(filename, uid) != NULL;
Kenny Root70e3a862012-02-15 17:20:23 -08001306 }
1307
Chad Brubaker72593ee2015-05-12 10:42:00 -07001308 ResponseCode importKey(const uint8_t* key, size_t keyLen, const char* filename, uid_t userId,
Kenny Rootf9119d62013-04-03 09:22:15 -07001309 int32_t flags) {
Kenny Root822c3a92012-03-23 16:34:39 -07001310 uint8_t* data;
1311 size_t dataLength;
1312 int rc;
1313
1314 if (mDevice->import_keypair == NULL) {
1315 ALOGE("Keymaster doesn't support import!");
1316 return SYSTEM_ERROR;
1317 }
1318
Kenny Root17208e02013-09-04 13:56:03 -07001319 bool isFallback = false;
Kenny Root07438c82012-11-02 15:41:02 -07001320 rc = mDevice->import_keypair(mDevice, key, keyLen, &data, &dataLength);
Kenny Root822c3a92012-03-23 16:34:39 -07001321 if (rc) {
Kenny Roota39da5a2014-09-25 13:07:24 -07001322 /*
1323 * Maybe the device doesn't support this type of key. Try to use the
1324 * software fallback keymaster implementation. This is a little bit
1325 * lazier than checking the PKCS#8 key type, but the software
1326 * implementation will do that anyway.
1327 */
Chad Brubaker7c1eb752015-02-20 14:08:59 -08001328 rc = mFallbackDevice->import_keypair(mFallbackDevice, key, keyLen, &data, &dataLength);
Kenny Roota39da5a2014-09-25 13:07:24 -07001329 isFallback = true;
Kenny Root17208e02013-09-04 13:56:03 -07001330
1331 if (rc) {
1332 ALOGE("Error while importing keypair: %d", rc);
1333 return SYSTEM_ERROR;
1334 }
Kenny Root822c3a92012-03-23 16:34:39 -07001335 }
1336
1337 Blob keyBlob(data, dataLength, NULL, 0, TYPE_KEY_PAIR);
1338 free(data);
1339
Kenny Rootf9119d62013-04-03 09:22:15 -07001340 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
Kenny Root17208e02013-09-04 13:56:03 -07001341 keyBlob.setFallback(isFallback);
Kenny Rootf9119d62013-04-03 09:22:15 -07001342
Chad Brubaker72593ee2015-05-12 10:42:00 -07001343 return put(filename, &keyBlob, userId);
Kenny Root822c3a92012-03-23 16:34:39 -07001344 }
1345
Kenny Root1b0e3932013-09-05 13:06:32 -07001346 bool isHardwareBacked(const android::String16& keyType) const {
1347 if (mDevice == NULL) {
1348 ALOGW("can't get keymaster device");
1349 return false;
1350 }
1351
1352 if (sRSAKeyType == keyType) {
1353 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0;
1354 } else {
1355 return (mDevice->flags & KEYMASTER_SOFTWARE_ONLY) == 0
1356 && (mDevice->common.module->module_api_version
1357 >= KEYMASTER_MODULE_API_VERSION_0_2);
1358 }
Kenny Root8ddf35a2013-03-29 11:15:50 -07001359 }
1360
Kenny Root655b9582013-04-04 08:37:42 -07001361 ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
1362 const BlobType type) {
Kenny Root86b16e82013-09-09 11:15:54 -07001363 android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001364 uid_t userId = get_user_id(uid);
Kenny Root655b9582013-04-04 08:37:42 -07001365
Chad Brubaker72593ee2015-05-12 10:42:00 -07001366 ResponseCode responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001367 if (responseCode == NO_ERROR) {
1368 return responseCode;
1369 }
1370
1371 // If this is one of the legacy UID->UID mappings, use it.
1372 uid_t euid = get_keystore_euid(uid);
1373 if (euid != uid) {
Kenny Root86b16e82013-09-09 11:15:54 -07001374 filepath8 = getKeyNameForUidWithDir(keyName, euid);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001375 responseCode = get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001376 if (responseCode == NO_ERROR) {
1377 return responseCode;
1378 }
1379 }
1380
1381 // They might be using a granted key.
Kenny Root86b16e82013-09-09 11:15:54 -07001382 android::String8 filename8 = getKeyName(keyName);
Kenny Root655b9582013-04-04 08:37:42 -07001383 char* end;
Kenny Root86b16e82013-09-09 11:15:54 -07001384 strtoul(filename8.string(), &end, 10);
Kenny Root655b9582013-04-04 08:37:42 -07001385 if (end[0] != '_' || end[1] == 0) {
1386 return KEY_NOT_FOUND;
1387 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001388 filepath8 = android::String8::format("%s/%s", getUserState(userId)->getUserDirName(),
Kenny Root86b16e82013-09-09 11:15:54 -07001389 filename8.string());
Kenny Root655b9582013-04-04 08:37:42 -07001390 if (!hasGrant(filepath8.string(), uid)) {
1391 return responseCode;
1392 }
1393
1394 // It is a granted key. Try to load it.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001395 return get(filepath8.string(), keyBlob, type, userId);
Kenny Root655b9582013-04-04 08:37:42 -07001396 }
1397
1398 /**
1399 * Returns any existing UserState or creates it if it doesn't exist.
1400 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001401 UserState* getUserState(uid_t userId) {
Kenny Root655b9582013-04-04 08:37:42 -07001402 for (android::Vector<UserState*>::iterator it(mMasterKeys.begin());
1403 it != mMasterKeys.end(); it++) {
1404 UserState* state = *it;
1405 if (state->getUserId() == userId) {
1406 return state;
1407 }
1408 }
1409
1410 UserState* userState = new UserState(userId);
1411 if (!userState->initialize()) {
1412 /* There's not much we can do if initialization fails. Trying to
1413 * unlock the keystore for that user will fail as well, so any
1414 * subsequent request for this user will just return SYSTEM_ERROR.
1415 */
1416 ALOGE("User initialization failed for %u; subsuquent operations will fail", userId);
1417 }
1418 mMasterKeys.add(userState);
1419 return userState;
1420 }
1421
1422 /**
Chad Brubaker72593ee2015-05-12 10:42:00 -07001423 * Returns any existing UserState or creates it if it doesn't exist.
1424 */
1425 UserState* getUserStateByUid(uid_t uid) {
1426 uid_t userId = get_user_id(uid);
1427 return getUserState(userId);
1428 }
1429
1430 /**
Kenny Root655b9582013-04-04 08:37:42 -07001431 * Returns NULL if the UserState doesn't already exist.
1432 */
Chad Brubaker72593ee2015-05-12 10:42:00 -07001433 const UserState* getUserState(uid_t userId) const {
Kenny Root655b9582013-04-04 08:37:42 -07001434 for (android::Vector<UserState*>::const_iterator it(mMasterKeys.begin());
1435 it != mMasterKeys.end(); it++) {
1436 UserState* state = *it;
1437 if (state->getUserId() == userId) {
1438 return state;
1439 }
1440 }
1441
1442 return NULL;
1443 }
1444
Chad Brubaker72593ee2015-05-12 10:42:00 -07001445 /**
1446 * Returns NULL if the UserState doesn't already exist.
1447 */
1448 const UserState* getUserStateByUid(uid_t uid) const {
1449 uid_t userId = get_user_id(uid);
1450 return getUserState(userId);
1451 }
1452
Kenny Roota91203b2012-02-15 15:00:46 -08001453private:
Kenny Root655b9582013-04-04 08:37:42 -07001454 static const char* sOldMasterKey;
1455 static const char* sMetaDataFile;
Kenny Root1b0e3932013-09-05 13:06:32 -07001456 static const android::String16 sRSAKeyType;
Kenny Roota91203b2012-02-15 15:00:46 -08001457 Entropy* mEntropy;
1458
Chad Brubaker67d2a502015-03-11 17:21:18 +00001459 keymaster1_device_t* mDevice;
1460 keymaster1_device_t* mFallbackDevice;
Kenny Root70e3a862012-02-15 17:20:23 -08001461
Kenny Root655b9582013-04-04 08:37:42 -07001462 android::Vector<UserState*> mMasterKeys;
Kenny Roota91203b2012-02-15 15:00:46 -08001463
Kenny Root655b9582013-04-04 08:37:42 -07001464 android::Vector<grant_t*> mGrants;
Kenny Roota91203b2012-02-15 15:00:46 -08001465
Kenny Root655b9582013-04-04 08:37:42 -07001466 typedef struct {
1467 uint32_t version;
1468 } keystore_metadata_t;
Kenny Roota91203b2012-02-15 15:00:46 -08001469
Kenny Root655b9582013-04-04 08:37:42 -07001470 keystore_metadata_t mMetaData;
Kenny Root70e3a862012-02-15 17:20:23 -08001471
Kenny Root655b9582013-04-04 08:37:42 -07001472 const grant_t* getGrant(const char* filename, uid_t uid) const {
1473 for (android::Vector<grant_t*>::const_iterator it(mGrants.begin());
1474 it != mGrants.end(); it++) {
1475 grant_t* grant = *it;
Kenny Root70e3a862012-02-15 17:20:23 -08001476 if (grant->uid == uid
Kenny Root655b9582013-04-04 08:37:42 -07001477 && !strcmp(reinterpret_cast<const char*>(grant->filename), filename)) {
Kenny Root70e3a862012-02-15 17:20:23 -08001478 return grant;
1479 }
1480 }
Kenny Root70e3a862012-02-15 17:20:23 -08001481 return NULL;
1482 }
1483
Kenny Root822c3a92012-03-23 16:34:39 -07001484 /**
1485 * Upgrade code. This will upgrade the key from the current version
1486 * to whatever is newest.
1487 */
Kenny Root655b9582013-04-04 08:37:42 -07001488 bool upgradeBlob(const char* filename, Blob* blob, const uint8_t oldVersion,
1489 const BlobType type, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001490 bool updated = false;
1491 uint8_t version = oldVersion;
1492
1493 /* From V0 -> V1: All old types were unknown */
1494 if (version == 0) {
1495 ALOGV("upgrading to version 1 and setting type %d", type);
1496
1497 blob->setType(type);
1498 if (type == TYPE_KEY_PAIR) {
Kenny Root655b9582013-04-04 08:37:42 -07001499 importBlobAsKey(blob, filename, uid);
Kenny Root822c3a92012-03-23 16:34:39 -07001500 }
1501 version = 1;
1502 updated = true;
1503 }
1504
Kenny Rootf9119d62013-04-03 09:22:15 -07001505 /* From V1 -> V2: All old keys were encrypted */
1506 if (version == 1) {
1507 ALOGV("upgrading to version 2");
1508
1509 blob->setEncrypted(true);
1510 version = 2;
1511 updated = true;
1512 }
1513
Kenny Root822c3a92012-03-23 16:34:39 -07001514 /*
1515 * If we've updated, set the key blob to the right version
1516 * and write it.
Kenny Rootcfeae072013-04-04 08:39:57 -07001517 */
Kenny Root822c3a92012-03-23 16:34:39 -07001518 if (updated) {
1519 ALOGV("updated and writing file %s", filename);
1520 blob->setVersion(version);
Kenny Root822c3a92012-03-23 16:34:39 -07001521 }
Kenny Rootcfeae072013-04-04 08:39:57 -07001522
1523 return updated;
Kenny Root822c3a92012-03-23 16:34:39 -07001524 }
1525
1526 /**
1527 * Takes a blob that is an PEM-encoded RSA key as a byte array and
1528 * converts it to a DER-encoded PKCS#8 for import into a keymaster.
1529 * Then it overwrites the original blob with the new blob
1530 * format that is returned from the keymaster.
1531 */
Kenny Root655b9582013-04-04 08:37:42 -07001532 ResponseCode importBlobAsKey(Blob* blob, const char* filename, uid_t uid) {
Kenny Root822c3a92012-03-23 16:34:39 -07001533 // We won't even write to the blob directly with this BIO, so const_cast is okay.
1534 Unique_BIO b(BIO_new_mem_buf(const_cast<uint8_t*>(blob->getValue()), blob->getLength()));
1535 if (b.get() == NULL) {
1536 ALOGE("Problem instantiating BIO");
1537 return SYSTEM_ERROR;
1538 }
1539
1540 Unique_EVP_PKEY pkey(PEM_read_bio_PrivateKey(b.get(), NULL, NULL, NULL));
1541 if (pkey.get() == NULL) {
1542 ALOGE("Couldn't read old PEM file");
1543 return SYSTEM_ERROR;
1544 }
1545
1546 Unique_PKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(pkey.get()));
1547 int len = i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), NULL);
1548 if (len < 0) {
1549 ALOGE("Couldn't measure PKCS#8 length");
1550 return SYSTEM_ERROR;
1551 }
1552
Kenny Root70c98892013-02-07 09:10:36 -08001553 UniquePtr<unsigned char[]> pkcs8key(new unsigned char[len]);
1554 uint8_t* tmp = pkcs8key.get();
Kenny Root822c3a92012-03-23 16:34:39 -07001555 if (i2d_PKCS8_PRIV_KEY_INFO(pkcs8.get(), &tmp) != len) {
1556 ALOGE("Couldn't convert to PKCS#8");
1557 return SYSTEM_ERROR;
1558 }
1559
Chad Brubaker72593ee2015-05-12 10:42:00 -07001560 ResponseCode rc = importKey(pkcs8key.get(), len, filename, get_user_id(uid),
Kenny Rootf9119d62013-04-03 09:22:15 -07001561 blob->isEncrypted() ? KEYSTORE_FLAG_ENCRYPTED : KEYSTORE_FLAG_NONE);
Kenny Root822c3a92012-03-23 16:34:39 -07001562 if (rc != NO_ERROR) {
1563 return rc;
1564 }
1565
Kenny Root655b9582013-04-04 08:37:42 -07001566 return get(filename, blob, TYPE_KEY_PAIR, uid);
1567 }
1568
1569 void readMetaData() {
1570 int in = TEMP_FAILURE_RETRY(open(sMetaDataFile, O_RDONLY));
1571 if (in < 0) {
1572 return;
1573 }
1574 size_t fileLength = readFully(in, (uint8_t*) &mMetaData, sizeof(mMetaData));
1575 if (fileLength != sizeof(mMetaData)) {
1576 ALOGI("Metadata file is %zd bytes (%zd experted); upgrade?", fileLength,
1577 sizeof(mMetaData));
1578 }
1579 close(in);
1580 }
1581
1582 void writeMetaData() {
1583 const char* tmpFileName = ".metadata.tmp";
1584 int out = TEMP_FAILURE_RETRY(open(tmpFileName,
1585 O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR));
1586 if (out < 0) {
1587 ALOGE("couldn't write metadata file: %s", strerror(errno));
1588 return;
1589 }
1590 size_t fileLength = writeFully(out, (uint8_t*) &mMetaData, sizeof(mMetaData));
1591 if (fileLength != sizeof(mMetaData)) {
1592 ALOGI("Could only write %zd bytes to metadata file (%zd expected)", fileLength,
1593 sizeof(mMetaData));
1594 }
1595 close(out);
1596 rename(tmpFileName, sMetaDataFile);
1597 }
1598
1599 bool upgradeKeystore() {
1600 bool upgraded = false;
1601
1602 if (mMetaData.version == 0) {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001603 UserState* userState = getUserStateByUid(0);
Kenny Root655b9582013-04-04 08:37:42 -07001604
1605 // Initialize first so the directory is made.
1606 userState->initialize();
1607
1608 // Migrate the old .masterkey file to user 0.
1609 if (access(sOldMasterKey, R_OK) == 0) {
1610 if (rename(sOldMasterKey, userState->getMasterKeyFileName()) < 0) {
1611 ALOGE("couldn't migrate old masterkey: %s", strerror(errno));
1612 return false;
1613 }
1614 }
1615
1616 // Initialize again in case we had a key.
1617 userState->initialize();
1618
1619 // Try to migrate existing keys.
1620 DIR* dir = opendir(".");
1621 if (!dir) {
1622 // Give up now; maybe we can upgrade later.
1623 ALOGE("couldn't open keystore's directory; something is wrong");
1624 return false;
1625 }
1626
1627 struct dirent* file;
1628 while ((file = readdir(dir)) != NULL) {
1629 // We only care about files.
1630 if (file->d_type != DT_REG) {
1631 continue;
1632 }
1633
1634 // Skip anything that starts with a "."
1635 if (file->d_name[0] == '.') {
1636 continue;
1637 }
1638
1639 // Find the current file's user.
1640 char* end;
1641 unsigned long thisUid = strtoul(file->d_name, &end, 10);
1642 if (end[0] != '_' || end[1] == 0) {
1643 continue;
1644 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07001645 UserState* otherUser = getUserStateByUid(thisUid);
Kenny Root655b9582013-04-04 08:37:42 -07001646 if (otherUser->getUserId() != 0) {
1647 unlinkat(dirfd(dir), file->d_name, 0);
1648 }
1649
1650 // Rename the file into user directory.
1651 DIR* otherdir = opendir(otherUser->getUserDirName());
1652 if (otherdir == NULL) {
1653 ALOGW("couldn't open user directory for rename");
1654 continue;
1655 }
1656 if (renameat(dirfd(dir), file->d_name, dirfd(otherdir), file->d_name) < 0) {
1657 ALOGW("couldn't rename blob: %s: %s", file->d_name, strerror(errno));
1658 }
1659 closedir(otherdir);
1660 }
1661 closedir(dir);
1662
1663 mMetaData.version = 1;
1664 upgraded = true;
1665 }
1666
1667 return upgraded;
Kenny Root822c3a92012-03-23 16:34:39 -07001668 }
Kenny Roota91203b2012-02-15 15:00:46 -08001669};
1670
Kenny Root655b9582013-04-04 08:37:42 -07001671const char* KeyStore::sOldMasterKey = ".masterkey";
1672const char* KeyStore::sMetaDataFile = ".metadata";
Kenny Root70e3a862012-02-15 17:20:23 -08001673
Kenny Root1b0e3932013-09-05 13:06:32 -07001674const android::String16 KeyStore::sRSAKeyType("RSA");
1675
Kenny Root07438c82012-11-02 15:41:02 -07001676namespace android {
1677class KeyStoreProxy : public BnKeystoreService, public IBinder::DeathRecipient {
1678public:
1679 KeyStoreProxy(KeyStore* keyStore)
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001680 : mKeyStore(keyStore),
1681 mOperationMap(this)
Kenny Root07438c82012-11-02 15:41:02 -07001682 {
Kenny Roota91203b2012-02-15 15:00:46 -08001683 }
Kenny Roota91203b2012-02-15 15:00:46 -08001684
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08001685 void binderDied(const wp<IBinder>& who) {
1686 auto operations = mOperationMap.getOperationsForToken(who.unsafe_get());
1687 for (auto token: operations) {
1688 abort(token);
1689 }
Kenny Root822c3a92012-03-23 16:34:39 -07001690 }
Kenny Roota91203b2012-02-15 15:00:46 -08001691
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001692 int32_t getState(int32_t userId) {
1693 if (!checkBinderPermission(P_GET_STATE)) {
Kenny Root07438c82012-11-02 15:41:02 -07001694 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001695 }
Kenny Roota91203b2012-02-15 15:00:46 -08001696
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001697 return mKeyStore->getState(userId);
Kenny Root298e7b12012-03-26 13:54:44 -07001698 }
1699
Kenny Root07438c82012-11-02 15:41:02 -07001700 int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001701 if (!checkBinderPermission(P_GET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001702 return ::PERMISSION_DENIED;
Kenny Roota91203b2012-02-15 15:00:46 -08001703 }
Kenny Root07438c82012-11-02 15:41:02 -07001704
Chad Brubaker9489b792015-04-14 11:01:45 -07001705 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Kenny Root07438c82012-11-02 15:41:02 -07001706 String8 name8(name);
Kenny Root07438c82012-11-02 15:41:02 -07001707 Blob keyBlob;
Nick Kralevich66dbf672014-06-30 17:09:14 +00001708
Kenny Root655b9582013-04-04 08:37:42 -07001709 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
Kenny Root49468902013-03-19 13:41:33 -07001710 TYPE_GENERIC);
Kenny Root07438c82012-11-02 15:41:02 -07001711 if (responseCode != ::NO_ERROR) {
Kenny Root655b9582013-04-04 08:37:42 -07001712 ALOGW("Could not read %s", name8.string());
Kenny Root07438c82012-11-02 15:41:02 -07001713 *item = NULL;
1714 *itemLength = 0;
1715 return responseCode;
Kenny Roota91203b2012-02-15 15:00:46 -08001716 }
Kenny Roota91203b2012-02-15 15:00:46 -08001717
Kenny Root07438c82012-11-02 15:41:02 -07001718 *item = (uint8_t*) malloc(keyBlob.getLength());
1719 memcpy(*item, keyBlob.getValue(), keyBlob.getLength());
1720 *itemLength = keyBlob.getLength();
Kenny Roota91203b2012-02-15 15:00:46 -08001721
Kenny Root07438c82012-11-02 15:41:02 -07001722 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001723 }
1724
Kenny Rootf9119d62013-04-03 09:22:15 -07001725 int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
1726 int32_t flags) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001727 targetUid = getEffectiveUid(targetUid);
1728 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1729 flags & KEYSTORE_FLAG_ENCRYPTED);
1730 if (result != ::NO_ERROR) {
1731 return result;
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001732 }
1733
Kenny Root07438c82012-11-02 15:41:02 -07001734 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001735 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root07438c82012-11-02 15:41:02 -07001736
1737 Blob keyBlob(item, itemLength, NULL, 0, ::TYPE_GENERIC);
Kenny Rootee8068b2013-10-07 09:49:15 -07001738 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
1739
Chad Brubaker72593ee2015-05-12 10:42:00 -07001740 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001741 }
1742
Kenny Root49468902013-03-19 13:41:33 -07001743 int32_t del(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001744 targetUid = getEffectiveUid(targetUid);
1745 if (!checkBinderPermission(P_DELETE, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001746 return ::PERMISSION_DENIED;
1747 }
Kenny Root07438c82012-11-02 15:41:02 -07001748 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001749 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07001750 return mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001751 }
1752
Kenny Root49468902013-03-19 13:41:33 -07001753 int32_t exist(const String16& name, int targetUid) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001754 targetUid = getEffectiveUid(targetUid);
1755 if (!checkBinderPermission(P_EXIST, targetUid)) {
Kenny Rootb88c3eb2013-02-13 14:43:43 -08001756 return ::PERMISSION_DENIED;
1757 }
1758
Kenny Root07438c82012-11-02 15:41:02 -07001759 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07001760 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001761
Kenny Root655b9582013-04-04 08:37:42 -07001762 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07001763 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
1764 }
1765 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001766 }
1767
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001768 int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001769 targetUid = getEffectiveUid(targetUid);
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001770 if (!checkBinderPermission(P_LIST, targetUid)) {
Kenny Root07438c82012-11-02 15:41:02 -07001771 return ::PERMISSION_DENIED;
1772 }
Kenny Root07438c82012-11-02 15:41:02 -07001773 const String8 prefix8(prefix);
Kenny Root655b9582013-04-04 08:37:42 -07001774 String8 filename(mKeyStore->getKeyNameForUid(prefix8, targetUid));
Kenny Root70e3a862012-02-15 17:20:23 -08001775
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001776 if (mKeyStore->list(filename, matches, get_user_id(targetUid)) != ::NO_ERROR) {
Robin Lee4b84fdc2014-09-24 11:56:57 +01001777 return ::SYSTEM_ERROR;
Kenny Root9a53d3e2012-08-14 10:47:54 -07001778 }
Kenny Root07438c82012-11-02 15:41:02 -07001779 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001780 }
1781
Kenny Root07438c82012-11-02 15:41:02 -07001782 int32_t reset() {
Chad Brubaker9489b792015-04-14 11:01:45 -07001783 if (!checkBinderPermission(P_RESET)) {
Kenny Root07438c82012-11-02 15:41:02 -07001784 return ::PERMISSION_DENIED;
1785 }
1786
Chad Brubaker9489b792015-04-14 11:01:45 -07001787 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker96d6d782015-05-07 10:19:40 -07001788 mKeyStore->resetUser(get_user_id(callingUid), false);
1789 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001790 }
1791
Chad Brubaker96d6d782015-05-07 10:19:40 -07001792 int32_t onUserPasswordChanged(int32_t userId, const String16& password) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001793 if (!checkBinderPermission(P_PASSWORD)) {
Kenny Root07438c82012-11-02 15:41:02 -07001794 return ::PERMISSION_DENIED;
1795 }
Kenny Root70e3a862012-02-15 17:20:23 -08001796
Kenny Root07438c82012-11-02 15:41:02 -07001797 const String8 password8(password);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001798 // Flush the auth token table to prevent stale tokens from sticking
1799 // around.
1800 mAuthTokenTable.Clear();
1801
1802 if (password.size() == 0) {
1803 ALOGI("Secure lockscreen for user %d removed, deleting encrypted entries", userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001804 mKeyStore->resetUser(userId, true);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001805 return ::NO_ERROR;
1806 } else {
Chad Brubaker72593ee2015-05-12 10:42:00 -07001807 switch (mKeyStore->getState(userId)) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001808 case ::STATE_UNINITIALIZED: {
1809 // generate master key, encrypt with password, write to file,
1810 // initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001811 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001812 }
1813 case ::STATE_NO_ERROR: {
1814 // rewrite master key with new password.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001815 return mKeyStore->writeMasterKey(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001816 }
1817 case ::STATE_LOCKED: {
1818 ALOGE("Changing user %d's password while locked, clearing old encryption",
1819 userId);
Chad Brubaker72593ee2015-05-12 10:42:00 -07001820 mKeyStore->resetUser(userId, true);
1821 return mKeyStore->initializeUser(password8, userId);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001822 }
Kenny Root07438c82012-11-02 15:41:02 -07001823 }
Chad Brubaker96d6d782015-05-07 10:19:40 -07001824 return ::SYSTEM_ERROR;
Kenny Root07438c82012-11-02 15:41:02 -07001825 }
Kenny Root70e3a862012-02-15 17:20:23 -08001826 }
1827
Chad Brubakerc0f031a2015-05-12 10:43:10 -07001828 int32_t onUserAdded(int32_t userId, int32_t parentId) {
1829 if (!checkBinderPermission(P_USER_CHANGED)) {
1830 return ::PERMISSION_DENIED;
1831 }
1832
1833 // Sanity check that the new user has an empty keystore.
1834 if (!mKeyStore->isEmpty(userId)) {
1835 ALOGW("New user %d's keystore not empty. Clearing old entries.", userId);
1836 }
1837 // Unconditionally clear the keystore, just to be safe.
1838 mKeyStore->resetUser(userId, false);
1839
1840 // If the user has a parent user then use the parent's
1841 // masterkey/password, otherwise there's nothing to do.
1842 if (parentId != -1) {
1843 return mKeyStore->copyMasterKey(parentId, userId);
1844 } else {
1845 return ::NO_ERROR;
1846 }
1847 }
1848
1849 int32_t onUserRemoved(int32_t userId) {
1850 if (!checkBinderPermission(P_USER_CHANGED)) {
1851 return ::PERMISSION_DENIED;
1852 }
1853
1854 mKeyStore->resetUser(userId, false);
1855 return ::NO_ERROR;
1856 }
1857
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001858 int32_t lock(int32_t userId) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001859 if (!checkBinderPermission(P_LOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001860 return ::PERMISSION_DENIED;
1861 }
Kenny Root70e3a862012-02-15 17:20:23 -08001862
Chad Brubaker72593ee2015-05-12 10:42:00 -07001863 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001864 if (state != ::STATE_NO_ERROR) {
Kenny Root07438c82012-11-02 15:41:02 -07001865 ALOGD("calling lock in state: %d", state);
1866 return state;
1867 }
1868
Chad Brubaker72593ee2015-05-12 10:42:00 -07001869 mKeyStore->lock(userId);
Kenny Root07438c82012-11-02 15:41:02 -07001870 return ::NO_ERROR;
Kenny Root70e3a862012-02-15 17:20:23 -08001871 }
1872
Chad Brubaker96d6d782015-05-07 10:19:40 -07001873 int32_t unlock(int32_t userId, const String16& pw) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001874 if (!checkBinderPermission(P_UNLOCK)) {
Kenny Root07438c82012-11-02 15:41:02 -07001875 return ::PERMISSION_DENIED;
1876 }
1877
Chad Brubaker72593ee2015-05-12 10:42:00 -07001878 State state = mKeyStore->getState(userId);
Kenny Root9d45d1c2013-02-14 10:32:30 -08001879 if (state != ::STATE_LOCKED) {
Chad Brubaker96d6d782015-05-07 10:19:40 -07001880 ALOGI("calling unlock when not locked, ignoring.");
Kenny Root07438c82012-11-02 15:41:02 -07001881 return state;
1882 }
1883
1884 const String8 password8(pw);
Chad Brubaker96d6d782015-05-07 10:19:40 -07001885 // read master key, decrypt with password, initialize mMasterKey*.
Chad Brubaker72593ee2015-05-12 10:42:00 -07001886 return mKeyStore->readMasterKey(password8, userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001887 }
1888
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001889 bool isEmpty(int32_t userId) {
1890 if (!checkBinderPermission(P_IS_EMPTY)) {
1891 return false;
Kenny Root07438c82012-11-02 15:41:02 -07001892 }
Kenny Root70e3a862012-02-15 17:20:23 -08001893
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07001894 return mKeyStore->isEmpty(userId);
Kenny Root70e3a862012-02-15 17:20:23 -08001895 }
1896
Kenny Root96427ba2013-08-16 14:02:41 -07001897 int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
1898 int32_t flags, Vector<sp<KeystoreArg> >* args) {
Chad Brubaker9489b792015-04-14 11:01:45 -07001899 targetUid = getEffectiveUid(targetUid);
1900 int32_t result = checkBinderPermissionAndKeystoreState(P_INSERT, targetUid,
1901 flags & KEYSTORE_FLAG_ENCRYPTED);
1902 if (result != ::NO_ERROR) {
1903 return result;
Kenny Root07438c82012-11-02 15:41:02 -07001904 }
Kenny Root07438c82012-11-02 15:41:02 -07001905
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001906 KeymasterArguments params;
1907 addLegacyKeyAuthorizations(params.params);
Kenny Root07438c82012-11-02 15:41:02 -07001908
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001909 switch (keyType) {
1910 case EVP_PKEY_EC: {
1911 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC));
1912 if (keySize == -1) {
1913 keySize = EC_DEFAULT_KEY_SIZE;
1914 } else if (keySize < EC_MIN_KEY_SIZE || keySize > EC_MAX_KEY_SIZE) {
1915 ALOGI("invalid key size %d", keySize);
Kenny Root96427ba2013-08-16 14:02:41 -07001916 return ::SYSTEM_ERROR;
1917 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001918 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
1919 break;
Kenny Root96427ba2013-08-16 14:02:41 -07001920 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001921 case EVP_PKEY_RSA: {
1922 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1923 if (keySize == -1) {
1924 keySize = RSA_DEFAULT_KEY_SIZE;
1925 } else if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) {
1926 ALOGI("invalid key size %d", keySize);
1927 return ::SYSTEM_ERROR;
Kenny Root96427ba2013-08-16 14:02:41 -07001928 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001929 params.params.push_back(keymaster_param_int(KM_TAG_KEY_SIZE, keySize));
1930 unsigned long exponent = RSA_DEFAULT_EXPONENT;
1931 if (args->size() > 1) {
1932 ALOGI("invalid number of arguments: %zu", args->size());
1933 return ::SYSTEM_ERROR;
1934 } else if (args->size() == 1) {
1935 sp<KeystoreArg> expArg = args->itemAt(0);
1936 if (expArg != NULL) {
1937 Unique_BIGNUM pubExpBn(
1938 BN_bin2bn(reinterpret_cast<const unsigned char*>(expArg->data()),
1939 expArg->size(), NULL));
1940 if (pubExpBn.get() == NULL) {
1941 ALOGI("Could not convert public exponent to BN");
1942 return ::SYSTEM_ERROR;
1943 }
1944 exponent = BN_get_word(pubExpBn.get());
1945 if (exponent == 0xFFFFFFFFL) {
1946 ALOGW("cannot represent public exponent as a long value");
1947 return ::SYSTEM_ERROR;
1948 }
1949 } else {
1950 ALOGW("public exponent not read");
1951 return ::SYSTEM_ERROR;
1952 }
1953 }
1954 params.params.push_back(keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT,
1955 exponent));
1956 break;
Kenny Root96427ba2013-08-16 14:02:41 -07001957 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001958 default: {
1959 ALOGW("Unsupported key type %d", keyType);
1960 return ::SYSTEM_ERROR;
1961 }
Kenny Root96427ba2013-08-16 14:02:41 -07001962 }
1963
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001964 int32_t rc = generateKey(name, params, NULL, 0, targetUid, flags,
1965 /*outCharacteristics*/ NULL);
1966 if (rc != ::NO_ERROR) {
1967 ALOGW("generate failed: %d", rc);
Kenny Root07438c82012-11-02 15:41:02 -07001968 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001969 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08001970 }
1971
Kenny Rootf9119d62013-04-03 09:22:15 -07001972 int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
1973 int32_t flags) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001974 KeymasterArguments params;
1975 addLegacyKeyAuthorizations(params.params);
1976 const uint8_t* ptr = data;
Kenny Root07438c82012-11-02 15:41:02 -07001977
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07001978 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, length));
1979 if (!pkcs8.get()) {
1980 return ::SYSTEM_ERROR;
1981 }
1982 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
1983 if (!pkey.get()) {
1984 return ::SYSTEM_ERROR;
1985 }
1986 int type = EVP_PKEY_type(pkey->type);
1987 switch (type) {
1988 case EVP_PKEY_RSA:
1989 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA));
1990 break;
1991 case EVP_PKEY_EC:
1992 params.params.push_back(keymaster_param_enum(KM_TAG_ALGORITHM,
1993 KM_ALGORITHM_EC));
1994 break;
1995 default:
1996 ALOGW("Unsupported key type %d", type);
1997 return ::SYSTEM_ERROR;
1998 }
1999 int32_t rc = importKey(name, params, KM_KEY_FORMAT_PKCS8, data, length, targetUid, flags,
2000 /*outCharacteristics*/ NULL);
2001 if (rc != ::NO_ERROR) {
2002 ALOGW("importKey failed: %d", rc);
2003 }
2004 return translateResultToLegacyResult(rc);
Kenny Root70e3a862012-02-15 17:20:23 -08002005 }
2006
Kenny Root07438c82012-11-02 15:41:02 -07002007 int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002008 size_t* outLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002009 if (!checkBinderPermission(P_SIGN)) {
Kenny Root07438c82012-11-02 15:41:02 -07002010 return ::PERMISSION_DENIED;
2011 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002012 return doLegacySignVerify(name, data, length, out, outLength, NULL, 0, KM_PURPOSE_SIGN);
Kenny Root70e3a862012-02-15 17:20:23 -08002013 }
2014
Kenny Root07438c82012-11-02 15:41:02 -07002015 int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
2016 const uint8_t* signature, size_t signatureLength) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002017 if (!checkBinderPermission(P_VERIFY)) {
Kenny Root07438c82012-11-02 15:41:02 -07002018 return ::PERMISSION_DENIED;
2019 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002020 return doLegacySignVerify(name, data, dataLength, NULL, NULL, signature, signatureLength,
2021 KM_PURPOSE_VERIFY);
Kenny Roota91203b2012-02-15 15:00:46 -08002022 }
Kenny Root07438c82012-11-02 15:41:02 -07002023
2024 /*
2025 * TODO: The abstraction between things stored in hardware and regular blobs
2026 * of data stored on the filesystem should be moved down to keystore itself.
2027 * Unfortunately the Java code that calls this has naming conventions that it
2028 * knows about. Ideally keystore shouldn't be used to store random blobs of
2029 * data.
2030 *
2031 * Until that happens, it's necessary to have a separate "get_pubkey" and
2032 * "del_key" since the Java code doesn't really communicate what it's
2033 * intentions are.
2034 */
2035 int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002036 ExportResult result;
2037 exportKey(name, KM_KEY_FORMAT_X509, NULL, NULL, &result);
2038 if (result.resultCode != ::NO_ERROR) {
2039 ALOGW("export failed: %d", result.resultCode);
2040 return translateResultToLegacyResult(result.resultCode);
Kenny Root07438c82012-11-02 15:41:02 -07002041 }
Kenny Root07438c82012-11-02 15:41:02 -07002042
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002043 *pubkey = result.exportData.release();
2044 *pubkeyLength = result.dataLength;
Kenny Root07438c82012-11-02 15:41:02 -07002045 return ::NO_ERROR;
Kenny Roota91203b2012-02-15 15:00:46 -08002046 }
Kenny Root07438c82012-11-02 15:41:02 -07002047
Kenny Root07438c82012-11-02 15:41:02 -07002048 int32_t grant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002049 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002050 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2051 if (result != ::NO_ERROR) {
2052 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002053 }
2054
2055 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002056 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002057
Kenny Root655b9582013-04-04 08:37:42 -07002058 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002059 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2060 }
2061
Kenny Root655b9582013-04-04 08:37:42 -07002062 mKeyStore->addGrant(filename.string(), granteeUid);
Kenny Root07438c82012-11-02 15:41:02 -07002063 return ::NO_ERROR;
2064 }
2065
2066 int32_t ungrant(const String16& name, int32_t granteeUid) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002067 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002068 int32_t result = checkBinderPermissionAndKeystoreState(P_GRANT);
2069 if (result != ::NO_ERROR) {
2070 return result;
Kenny Root07438c82012-11-02 15:41:02 -07002071 }
2072
2073 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002074 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002075
Kenny Root655b9582013-04-04 08:37:42 -07002076 if (access(filename.string(), R_OK) == -1) {
Kenny Root07438c82012-11-02 15:41:02 -07002077 return (errno != ENOENT) ? ::SYSTEM_ERROR : ::KEY_NOT_FOUND;
2078 }
2079
Kenny Root655b9582013-04-04 08:37:42 -07002080 return mKeyStore->removeGrant(filename.string(), granteeUid) ? ::NO_ERROR : ::KEY_NOT_FOUND;
Kenny Root07438c82012-11-02 15:41:02 -07002081 }
2082
2083 int64_t getmtime(const String16& name) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002084 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Chad Brubaker9489b792015-04-14 11:01:45 -07002085 if (!checkBinderPermission(P_GET)) {
Kenny Rootd38a0b02013-02-13 12:59:14 -08002086 ALOGW("permission denied for %d: getmtime", callingUid);
Kenny Root36a9e232013-02-04 14:24:15 -08002087 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002088 }
Kenny Root07438c82012-11-02 15:41:02 -07002089
2090 String8 name8(name);
Kenny Root655b9582013-04-04 08:37:42 -07002091 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, callingUid));
Kenny Root07438c82012-11-02 15:41:02 -07002092
Kenny Root655b9582013-04-04 08:37:42 -07002093 if (access(filename.string(), R_OK) == -1) {
2094 ALOGW("could not access %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002095 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002096 }
2097
Kenny Root655b9582013-04-04 08:37:42 -07002098 int fd = TEMP_FAILURE_RETRY(open(filename.string(), O_NOFOLLOW, O_RDONLY));
Kenny Root07438c82012-11-02 15:41:02 -07002099 if (fd < 0) {
Kenny Root655b9582013-04-04 08:37:42 -07002100 ALOGW("could not open %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002101 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002102 }
2103
2104 struct stat s;
2105 int ret = fstat(fd, &s);
2106 close(fd);
2107 if (ret == -1) {
Kenny Root655b9582013-04-04 08:37:42 -07002108 ALOGW("could not stat %s for getmtime", filename.string());
Kenny Root36a9e232013-02-04 14:24:15 -08002109 return -1L;
Kenny Root07438c82012-11-02 15:41:02 -07002110 }
2111
Kenny Root36a9e232013-02-04 14:24:15 -08002112 return static_cast<int64_t>(s.st_mtime);
Kenny Root07438c82012-11-02 15:41:02 -07002113 }
2114
Kenny Rootd53bc922013-03-21 14:10:15 -07002115 int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
2116 int32_t destUid) {
Kenny Root02254072013-03-20 11:48:19 -07002117 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Riley Spahneaabae92014-06-30 12:39:52 -07002118 pid_t spid = IPCThreadState::self()->getCallingPid();
2119 if (!has_permission(callingUid, P_DUPLICATE, spid)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002120 ALOGW("permission denied for %d: duplicate", callingUid);
Kenny Root02254072013-03-20 11:48:19 -07002121 return -1L;
2122 }
2123
Chad Brubaker72593ee2015-05-12 10:42:00 -07002124 State state = mKeyStore->getState(get_user_id(callingUid));
Kenny Root02254072013-03-20 11:48:19 -07002125 if (!isKeystoreUnlocked(state)) {
Kenny Rootd53bc922013-03-21 14:10:15 -07002126 ALOGD("calling duplicate in state: %d", state);
Kenny Root02254072013-03-20 11:48:19 -07002127 return state;
2128 }
2129
Kenny Rootd53bc922013-03-21 14:10:15 -07002130 if (srcUid == -1 || static_cast<uid_t>(srcUid) == callingUid) {
2131 srcUid = callingUid;
2132 } else if (!is_granted_to(callingUid, srcUid)) {
2133 ALOGD("migrate not granted from source: %d -> %d", callingUid, srcUid);
Kenny Root02254072013-03-20 11:48:19 -07002134 return ::PERMISSION_DENIED;
2135 }
2136
Kenny Rootd53bc922013-03-21 14:10:15 -07002137 if (destUid == -1) {
2138 destUid = callingUid;
2139 }
2140
2141 if (srcUid != destUid) {
2142 if (static_cast<uid_t>(srcUid) != callingUid) {
2143 ALOGD("can only duplicate from caller to other or to same uid: "
2144 "calling=%d, srcUid=%d, destUid=%d", callingUid, srcUid, destUid);
2145 return ::PERMISSION_DENIED;
2146 }
2147
2148 if (!is_granted_to(callingUid, destUid)) {
2149 ALOGD("duplicate not granted to dest: %d -> %d", callingUid, destUid);
2150 return ::PERMISSION_DENIED;
2151 }
2152 }
2153
2154 String8 source8(srcKey);
Kenny Root655b9582013-04-04 08:37:42 -07002155 String8 sourceFile(mKeyStore->getKeyNameForUidWithDir(source8, srcUid));
Kenny Root02254072013-03-20 11:48:19 -07002156
Kenny Rootd53bc922013-03-21 14:10:15 -07002157 String8 target8(destKey);
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002158 String8 targetFile(mKeyStore->getKeyNameForUidWithDir(target8, destUid));
Kenny Root02254072013-03-20 11:48:19 -07002159
Kenny Root655b9582013-04-04 08:37:42 -07002160 if (access(targetFile.string(), W_OK) != -1 || errno != ENOENT) {
2161 ALOGD("destination already exists: %s", targetFile.string());
Kenny Root02254072013-03-20 11:48:19 -07002162 return ::SYSTEM_ERROR;
2163 }
2164
Kenny Rootd53bc922013-03-21 14:10:15 -07002165 Blob keyBlob;
Kenny Root655b9582013-04-04 08:37:42 -07002166 ResponseCode responseCode = mKeyStore->get(sourceFile.string(), &keyBlob, TYPE_ANY,
Chad Brubaker72593ee2015-05-12 10:42:00 -07002167 get_user_id(srcUid));
Kenny Rootd53bc922013-03-21 14:10:15 -07002168 if (responseCode != ::NO_ERROR) {
2169 return responseCode;
Kenny Root02254072013-03-20 11:48:19 -07002170 }
Kenny Rootd53bc922013-03-21 14:10:15 -07002171
Chad Brubaker72593ee2015-05-12 10:42:00 -07002172 return mKeyStore->put(targetFile.string(), &keyBlob, get_user_id(destUid));
Kenny Root02254072013-03-20 11:48:19 -07002173 }
2174
Kenny Root1b0e3932013-09-05 13:06:32 -07002175 int32_t is_hardware_backed(const String16& keyType) {
2176 return mKeyStore->isHardwareBacked(keyType) ? 1 : 0;
Kenny Root8ddf35a2013-03-29 11:15:50 -07002177 }
2178
Kenny Rootfa27d5b2013-10-15 09:01:08 -07002179 int32_t clear_uid(int64_t targetUid64) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002180 uid_t targetUid = getEffectiveUid(targetUid64);
Chad Brubakerb37a5232015-05-01 10:21:27 -07002181 if (!checkBinderPermissionSelfOrSystem(P_CLEAR_UID, targetUid)) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002182 return ::PERMISSION_DENIED;
2183 }
2184
Robin Lee4b84fdc2014-09-24 11:56:57 +01002185 String8 prefix = String8::format("%u_", targetUid);
2186 Vector<String16> aliases;
Chad Brubakere6c3bfa2015-05-12 15:18:26 -07002187 if (mKeyStore->list(prefix, &aliases, get_user_id(targetUid)) != ::NO_ERROR) {
Kenny Roota9bb5492013-04-01 16:29:11 -07002188 return ::SYSTEM_ERROR;
2189 }
2190
Robin Lee4b84fdc2014-09-24 11:56:57 +01002191 for (uint32_t i = 0; i < aliases.size(); i++) {
2192 String8 name8(aliases[i]);
2193 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, targetUid));
Chad Brubaker72593ee2015-05-12 10:42:00 -07002194 mKeyStore->del(filename.string(), ::TYPE_ANY, get_user_id(targetUid));
Kenny Roota9bb5492013-04-01 16:29:11 -07002195 }
Robin Lee4b84fdc2014-09-24 11:56:57 +01002196 return ::NO_ERROR;
Kenny Roota9bb5492013-04-01 16:29:11 -07002197 }
2198
Chad Brubaker9c8612c2015-02-09 11:32:54 -08002199 int32_t addRngEntropy(const uint8_t* data, size_t dataLength) {
2200 const keymaster1_device_t* device = mKeyStore->getDevice();
2201 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
2202 int32_t devResult = KM_ERROR_UNIMPLEMENTED;
2203 int32_t fallbackResult = KM_ERROR_UNIMPLEMENTED;
2204 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2205 device->add_rng_entropy != NULL) {
2206 devResult = device->add_rng_entropy(device, data, dataLength);
2207 }
2208 if (fallback->add_rng_entropy) {
2209 fallbackResult = fallback->add_rng_entropy(fallback, data, dataLength);
2210 }
2211 if (devResult) {
2212 return devResult;
2213 }
2214 if (fallbackResult) {
2215 return fallbackResult;
2216 }
2217 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002218 }
2219
Chad Brubaker17d68b92015-02-05 22:04:16 -08002220 int32_t generateKey(const String16& name, const KeymasterArguments& params,
Chad Brubaker154d7692015-03-27 13:59:31 -07002221 const uint8_t* entropy, size_t entropyLength, int uid, int flags,
2222 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002223 uid = getEffectiveUid(uid);
2224 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2225 flags & KEYSTORE_FLAG_ENCRYPTED);
2226 if (rc != ::NO_ERROR) {
2227 return rc;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002228 }
2229
Chad Brubaker9489b792015-04-14 11:01:45 -07002230 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker17d68b92015-02-05 22:04:16 -08002231 bool isFallback = false;
2232 keymaster_key_blob_t blob;
2233 keymaster_key_characteristics_t *out = NULL;
2234
2235 const keymaster1_device_t* device = mKeyStore->getDevice();
2236 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002237 std::vector<keymaster_key_param_t> opParams(params.params);
2238 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
Chad Brubaker17d68b92015-02-05 22:04:16 -08002239 if (device == NULL) {
2240 return ::SYSTEM_ERROR;
2241 }
Chad Brubaker154d7692015-03-27 13:59:31 -07002242 // TODO: Seed from Linux RNG before this.
Chad Brubaker17d68b92015-02-05 22:04:16 -08002243 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2244 device->generate_key != NULL) {
Chad Brubaker154d7692015-03-27 13:59:31 -07002245 if (!entropy) {
2246 rc = KM_ERROR_OK;
2247 } else if (device->add_rng_entropy) {
2248 rc = device->add_rng_entropy(device, entropy, entropyLength);
2249 } else {
2250 rc = KM_ERROR_UNIMPLEMENTED;
2251 }
2252 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002253 rc = device->generate_key(device, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002254 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002255 }
2256 // If the HW device didn't support generate_key or generate_key failed
2257 // fall back to the software implementation.
2258 if (rc && fallback->generate_key != NULL) {
2259 isFallback = true;
Chad Brubaker154d7692015-03-27 13:59:31 -07002260 if (!entropy) {
2261 rc = KM_ERROR_OK;
2262 } else if (fallback->add_rng_entropy) {
2263 rc = fallback->add_rng_entropy(fallback, entropy, entropyLength);
2264 } else {
2265 rc = KM_ERROR_UNIMPLEMENTED;
2266 }
2267 if (rc == KM_ERROR_OK) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002268 rc = fallback->generate_key(fallback, &inParams, &blob, &out);
Chad Brubaker154d7692015-03-27 13:59:31 -07002269 }
Chad Brubaker17d68b92015-02-05 22:04:16 -08002270 }
2271
2272 if (out) {
2273 if (outCharacteristics) {
2274 outCharacteristics->characteristics = *out;
2275 } else {
2276 keymaster_free_characteristics(out);
2277 }
2278 free(out);
2279 }
2280
2281 if (rc) {
2282 return rc;
2283 }
2284
2285 String8 name8(name);
2286 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2287
2288 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2289 keyBlob.setFallback(isFallback);
2290 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2291
2292 free(const_cast<uint8_t*>(blob.key_material));
2293
Chad Brubaker72593ee2015-05-12 10:42:00 -07002294 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002295 }
2296
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002297 int32_t getKeyCharacteristics(const String16& name,
Chad Brubakerd6634422015-03-21 22:36:07 -07002298 const keymaster_blob_t* clientId,
2299 const keymaster_blob_t* appData,
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002300 KeyCharacteristics* outCharacteristics) {
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002301 if (!outCharacteristics) {
2302 return KM_ERROR_UNEXPECTED_NULL_POINTER;
2303 }
2304
2305 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2306
2307 Blob keyBlob;
2308 String8 name8(name);
2309 int rc;
2310
2311 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2312 TYPE_KEYMASTER_10);
2313 if (responseCode != ::NO_ERROR) {
2314 return responseCode;
2315 }
2316 keymaster_key_blob_t key;
2317 key.key_material_size = keyBlob.getLength();
2318 key.key_material = keyBlob.getValue();
2319 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2320 keymaster_key_characteristics_t *out = NULL;
2321 if (!dev->get_key_characteristics) {
2322 ALOGW("device does not implement get_key_characteristics");
2323 return KM_ERROR_UNIMPLEMENTED;
2324 }
Chad Brubakerd6634422015-03-21 22:36:07 -07002325 rc = dev->get_key_characteristics(dev, &key, clientId, appData, &out);
Chad Brubakerf3f071f2015-02-10 19:38:51 -08002326 if (out) {
2327 outCharacteristics->characteristics = *out;
2328 free(out);
2329 }
2330 return rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002331 }
2332
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002333 int32_t importKey(const String16& name, const KeymasterArguments& params,
2334 keymaster_key_format_t format, const uint8_t *keyData,
2335 size_t keyLength, int uid, int flags,
2336 KeyCharacteristics* outCharacteristics) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002337 uid = getEffectiveUid(uid);
2338 int rc = checkBinderPermissionAndKeystoreState(P_INSERT, uid,
2339 flags & KEYSTORE_FLAG_ENCRYPTED);
2340 if (rc != ::NO_ERROR) {
2341 return rc;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002342 }
2343
Chad Brubaker9489b792015-04-14 11:01:45 -07002344 rc = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002345 bool isFallback = false;
2346 keymaster_key_blob_t blob;
2347 keymaster_key_characteristics_t *out = NULL;
2348
2349 const keymaster1_device_t* device = mKeyStore->getDevice();
2350 const keymaster1_device_t* fallback = mKeyStore->getFallbackDevice();
Chad Brubaker57e106d2015-06-01 12:59:00 -07002351 std::vector<keymaster_key_param_t> opParams(params.params);
2352 const keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2353 const keymaster_blob_t input = {keyData, keyLength};
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002354 if (device == NULL) {
2355 return ::SYSTEM_ERROR;
2356 }
2357 if (device->common.module->module_api_version >= KEYMASTER_MODULE_API_VERSION_1_0 &&
2358 device->import_key != NULL) {
Chad Brubaker57e106d2015-06-01 12:59:00 -07002359 rc = device->import_key(device, &inParams, format,&input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002360 }
2361 if (rc && fallback->import_key != NULL) {
2362 isFallback = true;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002363 rc = fallback->import_key(fallback, &inParams, format, &input, &blob, &out);
Chad Brubaker4c353cb2015-02-11 14:36:11 -08002364 }
2365 if (out) {
2366 if (outCharacteristics) {
2367 outCharacteristics->characteristics = *out;
2368 } else {
2369 keymaster_free_characteristics(out);
2370 }
2371 free(out);
2372 }
2373 if (rc) {
2374 return rc;
2375 }
2376
2377 String8 name8(name);
2378 String8 filename(mKeyStore->getKeyNameForUidWithDir(name8, uid));
2379
2380 Blob keyBlob(blob.key_material, blob.key_material_size, NULL, 0, ::TYPE_KEYMASTER_10);
2381 keyBlob.setFallback(isFallback);
2382 keyBlob.setEncrypted(flags & KEYSTORE_FLAG_ENCRYPTED);
2383
2384 free((void*) blob.key_material);
2385
Chad Brubaker72593ee2015-05-12 10:42:00 -07002386 return mKeyStore->put(filename.string(), &keyBlob, get_user_id(uid));
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002387 }
2388
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002389 void exportKey(const String16& name, keymaster_key_format_t format,
Chad Brubakerd6634422015-03-21 22:36:07 -07002390 const keymaster_blob_t* clientId,
2391 const keymaster_blob_t* appData, ExportResult* result) {
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002392
2393 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2394
2395 Blob keyBlob;
2396 String8 name8(name);
2397 int rc;
2398
2399 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2400 TYPE_KEYMASTER_10);
2401 if (responseCode != ::NO_ERROR) {
2402 result->resultCode = responseCode;
2403 return;
2404 }
2405 keymaster_key_blob_t key;
2406 key.key_material_size = keyBlob.getLength();
2407 key.key_material = keyBlob.getValue();
2408 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
2409 if (!dev->export_key) {
2410 result->resultCode = KM_ERROR_UNIMPLEMENTED;
2411 return;
2412 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002413 keymaster_blob_t output = {NULL, 0};
2414 rc = dev->export_key(dev, format, &key, clientId, appData, &output);
2415 result->exportData.reset(const_cast<uint8_t*>(output.data));
2416 result->dataLength = output.data_length;
Chad Brubaker07b0cda2015-02-18 15:52:54 -08002417 result->resultCode = rc ? rc : ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002418 }
2419
Chad Brubakerad6514a2015-04-09 14:00:26 -07002420
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002421 void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
Chad Brubaker154d7692015-03-27 13:59:31 -07002422 bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
Chad Brubaker57e106d2015-06-01 12:59:00 -07002423 size_t entropyLength, OperationResult* result) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002424 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2425 if (!pruneable && get_app_id(callingUid) != AID_SYSTEM) {
2426 ALOGE("Non-system uid %d trying to start non-pruneable operation", callingUid);
2427 result->resultCode = ::PERMISSION_DENIED;
2428 return;
2429 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002430 if (!checkAllowedOperationParams(params.params)) {
2431 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2432 return;
2433 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002434 Blob keyBlob;
2435 String8 name8(name);
2436 ResponseCode responseCode = mKeyStore->getKeyForName(&keyBlob, name8, callingUid,
2437 TYPE_KEYMASTER_10);
2438 if (responseCode != ::NO_ERROR) {
2439 result->resultCode = responseCode;
2440 return;
2441 }
2442 keymaster_key_blob_t key;
2443 key.key_material_size = keyBlob.getLength();
2444 key.key_material = keyBlob.getValue();
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002445 keymaster_operation_handle_t handle;
2446 keymaster1_device_t* dev = mKeyStore->getDeviceForBlob(keyBlob);
Chad Brubaker154d7692015-03-27 13:59:31 -07002447 keymaster_error_t err = KM_ERROR_UNIMPLEMENTED;
Chad Brubaker06801e02015-03-31 15:13:13 -07002448 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubakerad6514a2015-04-09 14:00:26 -07002449 Unique_keymaster_key_characteristics characteristics;
2450 characteristics.reset(new keymaster_key_characteristics_t);
2451 err = getOperationCharacteristics(key, dev, opParams, characteristics.get());
2452 if (err) {
2453 result->resultCode = err;
2454 return;
2455 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002456 const hw_auth_token_t* authToken = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002457 int32_t authResult = getAuthToken(characteristics.get(), 0, purpose, &authToken,
Chad Brubaker06801e02015-03-31 15:13:13 -07002458 /*failOnTokenMissing*/ false);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002459 // If per-operation auth is needed we need to begin the operation and
2460 // the client will need to authorize that operation before calling
2461 // update. Any other auth issues stop here.
2462 if (authResult != ::NO_ERROR && authResult != ::OP_AUTH_NEEDED) {
2463 result->resultCode = authResult;
Chad Brubaker06801e02015-03-31 15:13:13 -07002464 return;
2465 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002466 addAuthToParams(&opParams, authToken);
Chad Brubaker154d7692015-03-27 13:59:31 -07002467 // Add entropy to the device first.
2468 if (entropy) {
2469 if (dev->add_rng_entropy) {
2470 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2471 } else {
2472 err = KM_ERROR_UNIMPLEMENTED;
2473 }
2474 if (err) {
2475 result->resultCode = err;
2476 return;
2477 }
2478 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002479 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2480 keymaster_key_param_set_t outParams = {NULL, 0};
2481 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002482
2483 // If there are too many operations abort the oldest operation that was
2484 // started as pruneable and try again.
2485 while (err == KM_ERROR_TOO_MANY_OPERATIONS && mOperationMap.hasPruneableOperation()) {
2486 sp<IBinder> oldest = mOperationMap.getOldestPruneableOperation();
2487 ALOGD("Ran out of operation handles, trying to prune %p", oldest.get());
2488 if (abort(oldest) != ::NO_ERROR) {
2489 break;
2490 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002491 err = dev->begin(dev, purpose, &key, &inParams, &outParams, &handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002492 }
2493 if (err) {
2494 result->resultCode = err;
2495 return;
2496 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002497
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002498 sp<IBinder> operationToken = mOperationMap.addOperation(handle, purpose, dev, appToken,
Chad Brubakerad6514a2015-04-09 14:00:26 -07002499 characteristics.release(),
Chad Brubaker06801e02015-03-31 15:13:13 -07002500 pruneable);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002501 if (authToken) {
2502 mOperationMap.setOperationAuthToken(operationToken, authToken);
2503 }
2504 // Return the authentication lookup result. If this is a per operation
2505 // auth'd key then the resultCode will be ::OP_AUTH_NEEDED and the
2506 // application should get an auth token using the handle before the
2507 // first call to update, which will fail if keystore hasn't received the
2508 // auth token.
2509 result->resultCode = authResult;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002510 result->token = operationToken;
Chad Brubakerc3a18562015-03-17 18:21:35 -07002511 result->handle = handle;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002512 if (outParams.params) {
2513 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2514 free(outParams.params);
2515 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002516 }
2517
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002518 void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
2519 size_t dataLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002520 if (!checkAllowedOperationParams(params.params)) {
2521 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2522 return;
2523 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002524 const keymaster1_device_t* dev;
2525 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002526 keymaster_purpose_t purpose;
2527 if (!mOperationMap.getOperation(token, &handle, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002528 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2529 return;
2530 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002531 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002532 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2533 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002534 result->resultCode = authResult;
2535 return;
2536 }
Chad Brubaker57e106d2015-06-01 12:59:00 -07002537 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2538 keymaster_blob_t input = {data, dataLength};
2539 size_t consumed = 0;
2540 keymaster_blob_t output = {NULL, 0};
2541 keymaster_key_param_set_t outParams = {NULL, 0};
2542
2543 keymaster_error_t err = dev->update(dev, handle, &inParams, &input, &consumed, &outParams,
2544 &output);
2545 result->data.reset(const_cast<uint8_t*>(output.data));
2546 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002547 result->inputConsumed = consumed;
2548 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002549 if (outParams.params) {
2550 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2551 free(outParams.params);
2552 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002553 }
2554
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002555 void finish(const sp<IBinder>& token, const KeymasterArguments& params,
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002556 const uint8_t* signature, size_t signatureLength,
2557 const uint8_t* entropy, size_t entropyLength, OperationResult* result) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002558 if (!checkAllowedOperationParams(params.params)) {
2559 result->resultCode = KM_ERROR_INVALID_ARGUMENT;
2560 return;
2561 }
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002562 const keymaster1_device_t* dev;
2563 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002564 keymaster_purpose_t purpose;
2565 if (!mOperationMap.getOperation(token, &handle, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002566 result->resultCode = KM_ERROR_INVALID_OPERATION_HANDLE;
2567 return;
2568 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002569 std::vector<keymaster_key_param_t> opParams(params.params);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002570 int32_t authResult = addOperationAuthTokenIfNeeded(token, &opParams);
2571 if (authResult != ::NO_ERROR) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002572 result->resultCode = authResult;
2573 return;
2574 }
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002575 keymaster_error_t err;
2576 if (entropy) {
2577 if (dev->add_rng_entropy) {
2578 err = dev->add_rng_entropy(dev, entropy, entropyLength);
2579 } else {
2580 err = KM_ERROR_UNIMPLEMENTED;
2581 }
2582 if (err) {
2583 result->resultCode = err;
2584 return;
2585 }
2586 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002587
Chad Brubaker57e106d2015-06-01 12:59:00 -07002588 keymaster_key_param_set_t inParams = {opParams.data(), opParams.size()};
2589 keymaster_blob_t input = {signature, signatureLength};
2590 keymaster_blob_t output = {NULL, 0};
2591 keymaster_key_param_set_t outParams = {NULL, 0};
Chad Brubaker0d33e0b2015-05-29 12:30:19 -07002592 err = dev->finish(dev, handle, &inParams, &input, &outParams, &output);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002593 // Remove the operation regardless of the result
2594 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002595 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker57e106d2015-06-01 12:59:00 -07002596
2597 result->data.reset(const_cast<uint8_t*>(output.data));
2598 result->dataLength = output.data_length;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002599 result->resultCode = err ? (int32_t) err : ::NO_ERROR;
Chad Brubaker57e106d2015-06-01 12:59:00 -07002600 if (outParams.params) {
2601 result->outParams.params.assign(outParams.params, outParams.params + outParams.length);
2602 free(outParams.params);
2603 }
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002604 }
2605
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002606 int32_t abort(const sp<IBinder>& token) {
2607 const keymaster1_device_t* dev;
2608 keymaster_operation_handle_t handle;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002609 keymaster_purpose_t purpose;
2610 if (!mOperationMap.getOperation(token, &handle, &purpose, &dev, NULL)) {
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002611 return KM_ERROR_INVALID_OPERATION_HANDLE;
2612 }
2613 mOperationMap.removeOperation(token);
Chad Brubaker06801e02015-03-31 15:13:13 -07002614 int32_t rc;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002615 if (!dev->abort) {
Chad Brubaker06801e02015-03-31 15:13:13 -07002616 rc = KM_ERROR_UNIMPLEMENTED;
2617 } else {
2618 rc = dev->abort(dev, handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002619 }
Chad Brubaker06801e02015-03-31 15:13:13 -07002620 mAuthTokenTable.MarkCompleted(handle);
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08002621 if (rc) {
2622 return rc;
2623 }
2624 return ::NO_ERROR;
Chad Brubaker9899d6b2015-02-03 13:03:00 -08002625 }
2626
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002627 bool isOperationAuthorized(const sp<IBinder>& token) {
2628 const keymaster1_device_t* dev;
2629 keymaster_operation_handle_t handle;
Chad Brubakerad6514a2015-04-09 14:00:26 -07002630 const keymaster_key_characteristics_t* characteristics;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002631 keymaster_purpose_t purpose;
2632 if (!mOperationMap.getOperation(token, &handle, &purpose, &dev, &characteristics)) {
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002633 return false;
2634 }
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002635 const hw_auth_token_t* authToken = NULL;
2636 mOperationMap.getOperationAuthToken(token, &authToken);
Chad Brubaker06801e02015-03-31 15:13:13 -07002637 std::vector<keymaster_key_param_t> ignored;
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002638 int32_t authResult = addOperationAuthTokenIfNeeded(token, &ignored);
2639 return authResult == ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002640 }
2641
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002642 int32_t addAuthToken(const uint8_t* token, size_t length) {
Chad Brubaker9489b792015-04-14 11:01:45 -07002643 if (!checkBinderPermission(P_ADD_AUTH)) {
2644 ALOGW("addAuthToken: permission denied for %d",
2645 IPCThreadState::self()->getCallingUid());
Chad Brubakerd80c7b42015-03-31 11:04:28 -07002646 return ::PERMISSION_DENIED;
2647 }
2648 if (length != sizeof(hw_auth_token_t)) {
2649 return KM_ERROR_INVALID_ARGUMENT;
2650 }
2651 hw_auth_token_t* authToken = new hw_auth_token_t;
2652 memcpy(reinterpret_cast<void*>(authToken), token, sizeof(hw_auth_token_t));
2653 // The table takes ownership of authToken.
2654 mAuthTokenTable.AddAuthenticationToken(authToken);
2655 return ::NO_ERROR;
Chad Brubaker2ed2baa2015-03-21 21:20:10 -07002656 }
2657
Kenny Root07438c82012-11-02 15:41:02 -07002658private:
Chad Brubaker9489b792015-04-14 11:01:45 -07002659 static const int32_t UID_SELF = -1;
2660
2661 /**
2662 * Get the effective target uid for a binder operation that takes an
2663 * optional uid as the target.
2664 */
2665 inline uid_t getEffectiveUid(int32_t targetUid) {
2666 if (targetUid == UID_SELF) {
2667 return IPCThreadState::self()->getCallingUid();
2668 }
2669 return static_cast<uid_t>(targetUid);
2670 }
2671
2672 /**
2673 * Check if the caller of the current binder method has the required
2674 * permission and if acting on other uids the grants to do so.
2675 */
2676 inline bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF) {
2677 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2678 pid_t spid = IPCThreadState::self()->getCallingPid();
2679 if (!has_permission(callingUid, permission, spid)) {
2680 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2681 return false;
2682 }
2683 if (!is_granted_to(callingUid, getEffectiveUid(targetUid))) {
2684 ALOGW("uid %d not granted to act for %d", callingUid, targetUid);
2685 return false;
2686 }
2687 return true;
2688 }
2689
2690 /**
2691 * Check if the caller of the current binder method has the required
Chad Brubakerb37a5232015-05-01 10:21:27 -07002692 * permission and the target uid is the caller or the caller is system.
2693 */
2694 inline bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid) {
2695 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2696 pid_t spid = IPCThreadState::self()->getCallingPid();
2697 if (!has_permission(callingUid, permission, spid)) {
2698 ALOGW("permission %s denied for %d", get_perm_label(permission), callingUid);
2699 return false;
2700 }
2701 return getEffectiveUid(targetUid) == callingUid || callingUid == AID_SYSTEM;
2702 }
2703
2704 /**
2705 * Check if the caller of the current binder method has the required
Chad Brubaker9489b792015-04-14 11:01:45 -07002706 * permission or the target of the operation is the caller's uid. This is
2707 * for operation where the permission is only for cross-uid activity and all
2708 * uids are allowed to act on their own (ie: clearing all entries for a
2709 * given uid).
2710 */
2711 inline bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid) {
2712 uid_t callingUid = IPCThreadState::self()->getCallingUid();
2713 if (getEffectiveUid(targetUid) == callingUid) {
2714 return true;
2715 } else {
2716 return checkBinderPermission(permission, targetUid);
2717 }
2718 }
2719
2720 /**
2721 * Helper method to check that the caller has the required permission as
2722 * well as the keystore is in the unlocked state if checkUnlocked is true.
2723 *
2724 * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
2725 * otherwise the state of keystore when not unlocked and checkUnlocked is
2726 * true.
2727 */
2728 inline int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
2729 bool checkUnlocked = true) {
2730 if (!checkBinderPermission(permission, targetUid)) {
2731 return ::PERMISSION_DENIED;
2732 }
Chad Brubaker72593ee2015-05-12 10:42:00 -07002733 State state = mKeyStore->getState(get_user_id(getEffectiveUid(targetUid)));
Chad Brubaker9489b792015-04-14 11:01:45 -07002734 if (checkUnlocked && !isKeystoreUnlocked(state)) {
2735 return state;
2736 }
2737
2738 return ::NO_ERROR;
2739
2740 }
2741
Kenny Root9d45d1c2013-02-14 10:32:30 -08002742 inline bool isKeystoreUnlocked(State state) {
2743 switch (state) {
2744 case ::STATE_NO_ERROR:
2745 return true;
2746 case ::STATE_UNINITIALIZED:
2747 case ::STATE_LOCKED:
2748 return false;
2749 }
2750 return false;
Kenny Root07438c82012-11-02 15:41:02 -07002751 }
2752
Chad Brubaker67d2a502015-03-11 17:21:18 +00002753 bool isKeyTypeSupported(const keymaster1_device_t* device, keymaster_keypair_t keyType) {
Kenny Root1d448c02013-11-21 10:36:53 -08002754 const int32_t device_api = device->common.module->module_api_version;
2755 if (device_api == KEYMASTER_MODULE_API_VERSION_0_2) {
2756 switch (keyType) {
2757 case TYPE_RSA:
2758 case TYPE_DSA:
2759 case TYPE_EC:
2760 return true;
2761 default:
2762 return false;
2763 }
2764 } else if (device_api >= KEYMASTER_MODULE_API_VERSION_0_3) {
2765 switch (keyType) {
2766 case TYPE_RSA:
2767 return true;
2768 case TYPE_DSA:
2769 return device->flags & KEYMASTER_SUPPORTS_DSA;
2770 case TYPE_EC:
2771 return device->flags & KEYMASTER_SUPPORTS_EC;
2772 default:
2773 return false;
2774 }
2775 } else {
2776 return keyType == TYPE_RSA;
2777 }
2778 }
2779
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002780 /**
2781 * Check that all keymaster_key_param_t's provided by the application are
2782 * allowed. Any parameter that keystore adds itself should be disallowed here.
2783 */
2784 bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params) {
2785 for (auto param: params) {
2786 switch (param.tag) {
2787 case KM_TAG_AUTH_TOKEN:
2788 return false;
2789 default:
2790 break;
2791 }
2792 }
2793 return true;
2794 }
2795
2796 keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
2797 const keymaster1_device_t* dev,
2798 const std::vector<keymaster_key_param_t>& params,
2799 keymaster_key_characteristics_t* out) {
2800 UniquePtr<keymaster_blob_t> appId;
2801 UniquePtr<keymaster_blob_t> appData;
2802 for (auto param : params) {
2803 if (param.tag == KM_TAG_APPLICATION_ID) {
2804 appId.reset(new keymaster_blob_t);
2805 appId->data = param.blob.data;
2806 appId->data_length = param.blob.data_length;
2807 } else if (param.tag == KM_TAG_APPLICATION_DATA) {
2808 appData.reset(new keymaster_blob_t);
2809 appData->data = param.blob.data;
2810 appData->data_length = param.blob.data_length;
2811 }
2812 }
2813 keymaster_key_characteristics_t* result = NULL;
2814 if (!dev->get_key_characteristics) {
2815 return KM_ERROR_UNIMPLEMENTED;
2816 }
2817 keymaster_error_t error = dev->get_key_characteristics(dev, &key, appId.get(),
2818 appData.get(), &result);
2819 if (result) {
2820 *out = *result;
2821 free(result);
2822 }
2823 return error;
2824 }
2825
2826 /**
2827 * Get the auth token for this operation from the auth token table.
2828 *
2829 * Returns ::NO_ERROR if the auth token was set or none was required.
2830 * ::OP_AUTH_NEEDED if it is a per op authorization, no
2831 * authorization token exists for that operation and
2832 * failOnTokenMissing is false.
2833 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
2834 * token for the operation
2835 */
2836 int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
2837 keymaster_operation_handle_t handle,
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002838 keymaster_purpose_t purpose,
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002839 const hw_auth_token_t** authToken,
2840 bool failOnTokenMissing = true) {
2841
2842 std::vector<keymaster_key_param_t> allCharacteristics;
2843 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2844 allCharacteristics.push_back(characteristics->sw_enforced.params[i]);
2845 }
2846 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2847 allCharacteristics.push_back(characteristics->hw_enforced.params[i]);
2848 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002849 keymaster::AuthTokenTable::Error err = mAuthTokenTable.FindAuthorization(
2850 allCharacteristics.data(), allCharacteristics.size(), purpose, handle, authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002851 switch (err) {
2852 case keymaster::AuthTokenTable::OK:
2853 case keymaster::AuthTokenTable::AUTH_NOT_REQUIRED:
2854 return ::NO_ERROR;
2855 case keymaster::AuthTokenTable::AUTH_TOKEN_NOT_FOUND:
2856 case keymaster::AuthTokenTable::AUTH_TOKEN_EXPIRED:
2857 case keymaster::AuthTokenTable::AUTH_TOKEN_WRONG_SID:
2858 return KM_ERROR_KEY_USER_NOT_AUTHENTICATED;
2859 case keymaster::AuthTokenTable::OP_HANDLE_REQUIRED:
2860 return failOnTokenMissing ? (int32_t) KM_ERROR_KEY_USER_NOT_AUTHENTICATED :
2861 (int32_t) ::OP_AUTH_NEEDED;
2862 default:
2863 ALOGE("Unexpected FindAuthorization return value %d", err);
2864 return KM_ERROR_INVALID_ARGUMENT;
2865 }
2866 }
2867
2868 inline void addAuthToParams(std::vector<keymaster_key_param_t>* params,
2869 const hw_auth_token_t* token) {
2870 if (token) {
2871 params->push_back(keymaster_param_blob(KM_TAG_AUTH_TOKEN,
2872 reinterpret_cast<const uint8_t*>(token),
2873 sizeof(hw_auth_token_t)));
2874 }
2875 }
2876
2877 /**
2878 * Add the auth token for the operation to the param list if the operation
2879 * requires authorization. Uses the cached result in the OperationMap if available
2880 * otherwise gets the token from the AuthTokenTable and caches the result.
2881 *
2882 * Returns ::NO_ERROR if the auth token was added or not needed.
2883 * KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
2884 * authenticated.
2885 * KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
2886 * operation token.
2887 */
2888 int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
2889 std::vector<keymaster_key_param_t>* params) {
2890 const hw_auth_token_t* authToken = NULL;
Chad Brubaker7169a842015-04-29 19:58:34 -07002891 mOperationMap.getOperationAuthToken(token, &authToken);
2892 if (!authToken) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002893 const keymaster1_device_t* dev;
2894 keymaster_operation_handle_t handle;
2895 const keymaster_key_characteristics_t* characteristics = NULL;
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002896 keymaster_purpose_t purpose;
2897 if (!mOperationMap.getOperation(token, &handle, &purpose, &dev, &characteristics)) {
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002898 return KM_ERROR_INVALID_OPERATION_HANDLE;
2899 }
Shawn Willdenb2ffa422015-06-17 12:18:55 -06002900 int32_t result = getAuthToken(characteristics, handle, purpose, &authToken);
Chad Brubaker0cf34a22015-04-23 11:06:16 -07002901 if (result != ::NO_ERROR) {
2902 return result;
2903 }
2904 if (authToken) {
2905 mOperationMap.setOperationAuthToken(token, authToken);
2906 }
2907 }
2908 addAuthToParams(params, authToken);
2909 return ::NO_ERROR;
2910 }
2911
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002912 /**
2913 * Translate a result value to a legacy return value. All keystore errors are
2914 * preserved and keymaster errors become SYSTEM_ERRORs
2915 */
2916 inline int32_t translateResultToLegacyResult(int32_t result) {
2917 if (result > 0) {
2918 return result;
2919 }
2920 return ::SYSTEM_ERROR;
2921 }
2922
2923 void addLegacyKeyAuthorizations(std::vector<keymaster_key_param_t>& params) {
2924 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN));
2925 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_VERIFY));
2926 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
2927 params.push_back(keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_DECRYPT));
2928 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
2929 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
2930 params.push_back(keymaster_param_bool(KM_TAG_ALL_USERS));
2931 params.push_back(keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED));
2932 params.push_back(keymaster_param_date(KM_TAG_ORIGINATION_EXPIRE_DATETIME, LLONG_MAX));
2933 params.push_back(keymaster_param_date(KM_TAG_USAGE_EXPIRE_DATETIME, LLONG_MAX));
2934 params.push_back(keymaster_param_date(KM_TAG_ACTIVE_DATETIME, 0));
2935 uint64_t now = keymaster::java_time(time(NULL));
2936 params.push_back(keymaster_param_date(KM_TAG_CREATION_DATETIME, now));
2937 }
2938
2939 keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics) {
2940 for (size_t i = 0; i < characteristics->hw_enforced.length; i++) {
2941 if (characteristics->hw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
2942 return &characteristics->hw_enforced.params[i];
2943 }
2944 }
2945 for (size_t i = 0; i < characteristics->sw_enforced.length; i++) {
2946 if (characteristics->sw_enforced.params[i].tag == KM_TAG_ALGORITHM) {
2947 return &characteristics->sw_enforced.params[i];
2948 }
2949 }
2950 return NULL;
2951 }
2952
2953 void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params) {
2954 // All legacy keys are DIGEST_NONE/PAD_NONE.
2955 params.push_back(keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE));
2956 params.push_back(keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE));
2957
2958 // Look up the algorithm of the key.
2959 KeyCharacteristics characteristics;
2960 int32_t rc = getKeyCharacteristics(name, NULL, NULL, &characteristics);
2961 if (rc != ::NO_ERROR) {
2962 ALOGE("Failed to get key characteristics");
2963 return;
2964 }
2965 keymaster_key_param_t* algorithm = getKeyAlgorithm(&characteristics.characteristics);
2966 if (!algorithm) {
2967 ALOGE("getKeyCharacteristics did not include KM_TAG_ALGORITHM");
2968 return;
2969 }
2970 params.push_back(*algorithm);
2971 }
2972
2973 int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
2974 uint8_t** out, size_t* outLength, const uint8_t* signature,
2975 size_t signatureLength, keymaster_purpose_t purpose) {
2976
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002977 std::basic_stringstream<uint8_t> outBuffer;
2978 OperationResult result;
2979 KeymasterArguments inArgs;
2980 addLegacyBeginParams(name, inArgs.params);
2981 sp<IBinder> appToken(new BBinder);
2982 sp<IBinder> token;
2983
2984 begin(appToken, name, purpose, true, inArgs, NULL, 0, &result);
2985 if (result.resultCode != ResponseCode::NO_ERROR) {
Chad Brubakerdf705172015-06-17 20:17:51 -07002986 if (result.resultCode == ::KEY_NOT_FOUND) {
2987 ALOGW("Key not found");
2988 } else {
2989 ALOGW("Error in begin: %d", result.resultCode);
2990 }
Chad Brubaker3a7d9e62015-06-04 15:01:46 -07002991 return translateResultToLegacyResult(result.resultCode);
2992 }
2993 inArgs.params.clear();
2994 token = result.token;
2995 size_t consumed = 0;
2996 size_t lastConsumed = 0;
2997 do {
2998 update(token, inArgs, data + consumed, length - consumed, &result);
2999 if (result.resultCode != ResponseCode::NO_ERROR) {
3000 ALOGW("Error in update: %d", result.resultCode);
3001 return translateResultToLegacyResult(result.resultCode);
3002 }
3003 if (out) {
3004 outBuffer.write(result.data.get(), result.dataLength);
3005 }
3006 lastConsumed = result.inputConsumed;
3007 consumed += lastConsumed;
3008 } while (consumed < length && lastConsumed > 0);
3009
3010 if (consumed != length) {
3011 ALOGW("Not all data consumed. Consumed %zu of %zu", consumed, length);
3012 return ::SYSTEM_ERROR;
3013 }
3014
3015 finish(token, inArgs, signature, signatureLength, NULL, 0, &result);
3016 if (result.resultCode != ResponseCode::NO_ERROR) {
3017 ALOGW("Error in finish: %d", result.resultCode);
3018 return translateResultToLegacyResult(result.resultCode);
3019 }
3020 if (out) {
3021 outBuffer.write(result.data.get(), result.dataLength);
3022 }
3023
3024 if (out) {
3025 auto buf = outBuffer.str();
3026 *out = new uint8_t[buf.size()];
3027 memcpy(*out, buf.c_str(), buf.size());
3028 *outLength = buf.size();
3029 }
3030
3031 return ::NO_ERROR;
3032 }
3033
Kenny Root07438c82012-11-02 15:41:02 -07003034 ::KeyStore* mKeyStore;
Chad Brubaker40a1a9b2015-02-20 14:08:13 -08003035 OperationMap mOperationMap;
Chad Brubakerd80c7b42015-03-31 11:04:28 -07003036 keymaster::AuthTokenTable mAuthTokenTable;
Kenny Root07438c82012-11-02 15:41:02 -07003037};
3038
3039}; // namespace android
Kenny Roota91203b2012-02-15 15:00:46 -08003040
3041int main(int argc, char* argv[]) {
Kenny Roota91203b2012-02-15 15:00:46 -08003042 if (argc < 2) {
3043 ALOGE("A directory must be specified!");
3044 return 1;
3045 }
3046 if (chdir(argv[1]) == -1) {
3047 ALOGE("chdir: %s: %s", argv[1], strerror(errno));
3048 return 1;
3049 }
3050
3051 Entropy entropy;
3052 if (!entropy.open()) {
3053 return 1;
3054 }
Kenny Root70e3a862012-02-15 17:20:23 -08003055
Chad Brubakerbd07a232015-06-01 10:44:27 -07003056 keymaster1_device_t* dev;
Kenny Root70e3a862012-02-15 17:20:23 -08003057 if (keymaster_device_initialize(&dev)) {
3058 ALOGE("keystore keymaster could not be initialized; exiting");
3059 return 1;
3060 }
3061
Chad Brubaker67d2a502015-03-11 17:21:18 +00003062 keymaster1_device_t* fallback;
Chad Brubakerfc18edc2015-01-12 15:17:18 -08003063 if (fallback_keymaster_device_initialize(&fallback)) {
3064 ALOGE("software keymaster could not be initialized; exiting");
3065 return 1;
3066 }
3067
Riley Spahneaabae92014-06-30 12:39:52 -07003068 ks_is_selinux_enabled = is_selinux_enabled();
3069 if (ks_is_selinux_enabled) {
3070 union selinux_callback cb;
3071 cb.func_log = selinux_log_callback;
3072 selinux_set_callback(SELINUX_CB_LOG, cb);
3073 if (getcon(&tctx) != 0) {
3074 ALOGE("SELinux: Could not acquire target context. Aborting keystore.\n");
3075 return -1;
3076 }
3077 } else {
3078 ALOGI("SELinux: Keystore SELinux is disabled.\n");
3079 }
3080
Chad Brubakerbd07a232015-06-01 10:44:27 -07003081 KeyStore keyStore(&entropy, dev, fallback);
Kenny Root655b9582013-04-04 08:37:42 -07003082 keyStore.initialize();
Kenny Root07438c82012-11-02 15:41:02 -07003083 android::sp<android::IServiceManager> sm = android::defaultServiceManager();
3084 android::sp<android::KeyStoreProxy> proxy = new android::KeyStoreProxy(&keyStore);
3085 android::status_t ret = sm->addService(android::String16("android.security.keystore"), proxy);
3086 if (ret != android::OK) {
3087 ALOGE("Couldn't register binder service!");
3088 return -1;
Kenny Roota91203b2012-02-15 15:00:46 -08003089 }
Kenny Root07438c82012-11-02 15:41:02 -07003090
3091 /*
3092 * We're the only thread in existence, so we're just going to process
3093 * Binder transaction as a single-threaded program.
3094 */
3095 android::IPCThreadState::self()->joinThreadPool();
Kenny Root70e3a862012-02-15 17:20:23 -08003096
3097 keymaster_device_release(dev);
Kenny Roota91203b2012-02-15 15:00:46 -08003098 return 1;
3099}